1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved.
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 
16 #ifndef HIEBPF_COMMAND_H
17 #define HIEBPF_COMMAND_H
18 
19 #include <csignal>
20 #include <fstream>
21 #include <queue>
22 #include <string>
23 #include <vector>
24 
25 #include "bpf_controller.h"
26 #include "elf_symbol_info.h"
27 #include "maps_info.h"
28 #include "ring_buffer.h"
29 #include "hiebpf_common.h"
30 class Command {
31 public:
32     bool DispatchCommand(std::vector<std::string> args);
33     Command();
34     void DoWork();
35 
36 private:
37     bool ParseArgs(std::vector<std::string> arguments);
GetClockId(const std::string &str)38     int GetClockId(const std::string &str)
39     {
40         if (str == "realtime") {
41             return CLOCK_TYPE::RealTime;
42         } else if (str == "boottime") {
43             return CLOCK_TYPE::BootTime;
44         } else if (str == "monotonic") {
45             return CLOCK_TYPE::Monotonic;
46         } else if (str == "monotonicraw") {
47             return CLOCK_TYPE::MonotonicRaw;
48         }
49         return -1;
50     }
51 
52     void PrintHelp();
53     static int EventReceiver(BPFEvent* bpfEvent);
54 
55     void WriteHeader();
56     void WriteEventMaps(uint32_t pid);
57     void WriteSymbolInfo(const std::string &fileName);
58     void WriteEventFs(uint8_t* data);
59     void WriteEventMem();
60 private:
61     bool helpFlag_ = false;
62     BPFConfig bpfConfig;
63     std::unique_ptr<BPFController> bpfControllerPtr_;
64     // event type
65     std::vector<std::string> events_;
66     int clockId_ = CLOCK_TYPE::BootTime;
67     int duration_ = 1000;
68     std::string symbolFilePath_;
69     std::string symbolFileName_;
70     std::string fileName_ = "/data/local/tmp/ebpf.data";
71     std::vector<int> pids_;
72     std::string help_;
73     std::ofstream stream_ {};
74     std::string cmdLine_;
75     std::thread writeFileThread_;
76     bool ThreadRunningFlag_ = true;
77 
78     OHOS::Developtools::Hiebpf::MapsInfo mapsInfo_;
79     OHOS::Developtools::Hiebpf::ElfSymbolInfo elfSymbolInfo_;
80 
81     void GetArgsValues(const FSTraceEvent* bpfEvent, uint64_t* args, std::vector<ArgStr>& argStr);
82     void EventLoop();
83     bool CheckPids(std::vector<int>& pids);
84     bool SetTargetPids();
85     bool SetTargetEvents();
86 };
87 #endif
88