xref: /developtools/hdc/src/common/async_cmd.h (revision cc290419)
1/*
2 * Copyright (C) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#ifndef HDC_ASYNC_CMD_H
16#define HDC_ASYNC_CMD_H
17#include "common.h"
18
19namespace Hdc {
20class AsyncCmd {
21public:
22    AsyncCmd();
23    virtual ~AsyncCmd();
24    enum AsyncCmdOption {
25        OPTION_COMMAND_ONETIME = 1,
26        USB_OPTION_RESERVE2 = 2,
27        OPTION_READBACK_OUT = 4,  // deprecated, remove it later
28        USB_OPTION_RESERVE8 = 8,
29    };
30    // 1)is finish 2)exitStatus 3)resultString(maybe empty)
31    using CmdResultCallback = std::function<bool(bool, int64_t, const string)>;
32    // deprecated, remove it later
33    static uint32_t GetDefaultOption()
34    {
35        return OPTION_COMMAND_ONETIME;
36    }
37    // uv_loop_t loop is given to uv_spawn, which can't be const
38    bool Initial(uv_loop_t *loopIn, const CmdResultCallback callback, uint32_t optionsIn = 0);
39    void DoRelease();  // Release process resources
40    bool ExecuteCommand(const string &command);
41    bool ReadyForRelease();
42
43private:
44    static bool FinishShellProc(const void *context, const bool result, const string exitMsg);
45    static bool ChildReadCallback(const void *context, uint8_t *buf, const int size);
46    int ThreadFork(const string &command, bool readWrite, int &cpid);
47    static void *Popen(void *arg);
48#if !defined(_WIN32) && !defined(HDC_HOST)
49    bool GetDevItem(const char *key, string &out);
50#endif
51
52    uint32_t options = 0;
53    int fd = 0;
54    int pid = 0;
55    HdcFileDescriptor *childShell = nullptr;
56    uint32_t refCount = 0;
57    CmdResultCallback resultCallback;
58    uv_loop_t *loop = nullptr;
59    string cmdResult;
60};
61
62struct AsyncParams {
63    string commandParam;
64    bool readWriteParam;
65    int &cpidParam;
66    bool isRoot;
67
68    AsyncParams(const string &commandParam, bool readWriteParam, int &cpidParam, bool isRoot)
69        :commandParam(commandParam), readWriteParam(readWriteParam), cpidParam(cpidParam), isRoot(isRoot) {};
70};
71}  // namespace Hdc
72#endif
73