1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. 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 #include "hidump_plugin.h"
16 #include <sys/syscall.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <cstdio>
20 #include <cstring>
21 #include <fcntl.h>
22 #include <cinttypes>
23 #include <csignal>
24 #include <sstream>
25 #include <sys/wait.h>
26
27 #include "hidump_plugin_result.pbencoder.h"
28 #include "securec.h"
29
30 namespace {
31 using namespace OHOS::Developtools::Profiler;
32 const int REDIRECT_STDOUT = 1;
33 const int REDIRECT_STDERR = 2;
34 const int SLEEP_TIME = 50;
35 const int BUF_MAX_LEN = 64;
36 const int MS_PER_S = 1000;
37 const int US_PER_S = 1000000;
38 const char *g_fpsFormat = "SP_daemon -profilerfps 31104000 -sections 10";
39
40 static pid_t volatile g_child;
41 const int READ = 0;
42 const int WRITE = 1;
43 const int PIPE_LEN = 2;
44 const std::string BIN_COMMAND("/bin/SP_daemon");
45 } // namespace
46
HidumpPlugin()47 HidumpPlugin::HidumpPlugin() : fp_(nullptr, nullptr) {}
48
~HidumpPlugin()49 HidumpPlugin::~HidumpPlugin()
50 {
51 PROFILER_LOG_INFO(LOG_CORE, "%s: ready!", __func__);
52 std::unique_lock<std::mutex> locker(mutex_);
53 if (running_) {
54 running_ = false;
55 if (writeThread_.joinable()) {
56 writeThread_.join();
57 }
58 }
59 locker.unlock();
60
61 if (fp_ != nullptr) {
62 fp_.reset();
63 }
64 PROFILER_LOG_INFO(LOG_CORE, "%s: success!", __func__);
65 }
66
Start(const uint8_t * configData,uint32_t configSize)67 int HidumpPlugin::Start(const uint8_t* configData, uint32_t configSize)
68 {
69 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin:Start ----> !");
70 CHECK_TRUE(protoConfig_.ParseFromArray(configData, configSize) > 0, -1, "HidumpPlugin: ParseFromArray failed");
71
72 fp_ = std::unique_ptr<FILE, int (*)(FILE*)>(CustomPopen(std::to_string(protoConfig_.sections()).c_str(), "r"),
73 CustomPclose);
74 if (fp_.get() == nullptr) {
75 const int bufSize = 256;
76 char buf[bufSize] = {0};
77 strerror_r(errno, buf, bufSize);
78 PROFILER_LOG_ERROR(LOG_CORE, "HidumpPlugin: CustomPopen(%s) Failed, errno(%d:%s)", g_fpsFormat, errno, buf);
79 return -1;
80 }
81 CHECK_NOTNULL(resultWriter_, -1, "HidumpPlugin: Writer is no set!");
82 CHECK_NOTNULL(resultWriter_->write, -1, "HidumpPlugin: Writer.write is no set!");
83 CHECK_NOTNULL(resultWriter_->flush, -1, "HidumpPlugin: Writer.flush is no set!");
84 std::unique_lock<std::mutex> locker(mutex_);
85 running_ = true;
86 writeThread_ = std::thread(&HidumpPlugin::Loop, this);
87
88 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin: ---> Start success!");
89 return 0;
90 }
91
Stop()92 int HidumpPlugin::Stop()
93 {
94 std::unique_lock<std::mutex> locker(mutex_);
95 running_ = false;
96 locker.unlock();
97 if (writeThread_.joinable()) {
98 writeThread_.join();
99 }
100 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin:stop thread success!");
101 if (fp_ != nullptr) {
102 fp_.reset();
103 }
104 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin: stop success!");
105 return 0;
106 }
107
SetWriter(WriterStruct * writer)108 int HidumpPlugin::SetWriter(WriterStruct* writer)
109 {
110 resultWriter_ = writer;
111 return 0;
112 }
113
Loop(void)114 void HidumpPlugin::Loop(void)
115 {
116 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin: Loop start");
117 CHECK_NOTNULL(resultWriter_, NO_RETVAL, "%s: resultWriter_ nullptr", __func__);
118
119 fcntl(fileno(fp_.get()), F_SETFL, O_NONBLOCK);
120 while (running_) {
121 char buf[BUF_MAX_LEN] = { 0 };
122
123 if (fgets(buf, BUF_MAX_LEN - 1, fp_.get()) == nullptr) {
124 std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
125 continue;
126 }
127 if (resultWriter_->isProtobufSerialize) {
128 HidumpInfo dataProto;
129 if (!ParseHidumpInfo(dataProto, buf)) {
130 continue;
131 }
132 if (dataProto.ByteSizeLong() > 0) {
133 buffer_.resize(dataProto.ByteSizeLong());
134 dataProto.SerializeToArray(buffer_.data(), buffer_.size());
135 resultWriter_->write(resultWriter_, buffer_.data(), buffer_.size());
136 resultWriter_->flush(resultWriter_);
137 }
138 } else {
139 ProtoEncoder::HidumpInfo hidumpInfo(resultWriter_->startReport(resultWriter_));
140 if (!ParseHidumpInfo(hidumpInfo, buf)) {
141 PROFILER_LOG_ERROR(LOG_CORE, "parse hidump info failed!");
142 }
143 int messageLen = hidumpInfo.Finish();
144 resultWriter_->finishReport(resultWriter_, messageLen);
145 resultWriter_->flush(resultWriter_);
146 }
147 }
148
149 PROFILER_LOG_INFO(LOG_CORE, "HidumpPlugin: Loop exit");
150 }
151
152 template <typename T>
ParseHidumpInfo(T & hidumpInfoProto,char * buf)153 bool HidumpPlugin::ParseHidumpInfo(T& hidumpInfoProto, char *buf)
154 {
155 // format: fps:123|1501960484673
156 if (strncmp(buf, "fps:", strlen("fps:")) != 0 && strncmp(buf, "sectionsFps:", strlen("sectionsFps:")) != 0) {
157 if (strstr(buf, "inaccessible or not found") != nullptr) {
158 PROFILER_LOG_ERROR(LOG_CORE, "HidumpPlugin: fps command not found!");
159 } else {
160 PROFILER_LOG_ERROR(LOG_CORE, "format error. %s", buf);
161 }
162 return false;
163 }
164
165 if (strncmp(buf, "fps:", strlen("fps:")) == 0) {
166 buf += strlen("fps:");
167 } else if (strncmp(buf, "sectionsFps:", strlen("sectionsFps:")) == 0) {
168 buf += strlen("sectionsFps:");
169 }
170
171 char *tmp = strchr(buf, '|');
172 CHECK_NOTNULL(tmp, false, "format error. %s", buf);
173 *tmp = ' ';
174 std::stringstream strvalue(buf);
175 uint32_t fps = 0;
176 strvalue >> fps;
177 uint64_t time_ms;
178 strvalue >> time_ms;
179
180 auto* eve = hidumpInfoProto.add_fps_event();
181 eve->set_fps(fps);
182 eve->set_id(::FpsData::REALTIME);
183 auto* time = eve->mutable_time();
184 time->set_tv_sec(time_ms / MS_PER_S);
185 time->set_tv_nsec((time_ms % MS_PER_S) * US_PER_S);
186
187 return true;
188 }
189
CustomPopen(const char * command,const char * type)190 FILE* HidumpPlugin::CustomPopen(const char* command, const char* type)
191 {
192 CHECK_TRUE(command != nullptr && type != nullptr, nullptr, "HidumpPlugin:%s param invalid", __func__);
193
194 int fd[PIPE_LEN];
195 pipe(fd);
196
197 pid_t pid = fork();
198 if (pid == -1) {
199 perror("fork");
200 exit(1);
201 }
202
203 // child process
204 if (pid == 0) {
205 if (!strncmp(type, "r", strlen(type))) {
206 close(fd[READ]);
207 dup2(fd[WRITE], REDIRECT_STDOUT); // Redirect stdout to pipe
208 dup2(fd[WRITE], REDIRECT_STDERR); // Redirect stderr to pipe
209 } else {
210 close(fd[WRITE]);
211 dup2(fd[READ], 0); // Redirect stdin to pipe
212 }
213
214 setpgid(pid, pid);
215 execl(BIN_COMMAND.c_str(), "SP_daemon", "-profilerfps", "31104000", "-sections", command, nullptr);
216 exit(0);
217 } else {
218 if (!strncmp(type, "r", strlen(type))) {
219 // Close the WRITE end of the pipe since parent's fd is read-only
220 close(fd[WRITE]);
221 } else {
222 // Close the READ end of the pipe since parent's fd is write-only
223 close(fd[READ]);
224 }
225 }
226
227 g_child = pid;
228
229 if (!strncmp(type, "r", strlen(type))) {
230 return fdopen(fd[READ], "r");
231 }
232
233 return fdopen(fd[WRITE], "w");
234 }
235
CustomPclose(FILE * fp)236 int HidumpPlugin::CustomPclose(FILE* fp)
237 {
238 CHECK_NOTNULL(fp, -1, "HidumpPlugin:%s fp is null", __func__);
239 int stat;
240 if (fclose(fp) != 0) {
241 const int bufSize = 256;
242 char buf[bufSize] = { 0 };
243 strerror_r(errno, buf, bufSize);
244 PROFILER_LOG_ERROR(LOG_CORE, "HidumpPlugin:%s fclose failed! errno(%d:%s)", __func__, errno, buf);
245 return -1;
246 }
247 kill(g_child, SIGKILL);
248 if (waitpid(g_child, &stat, 0) == -1) {
249 if (errno != EINTR) {
250 stat = errno;
251 }
252 }
253 return stat;
254 }
255
SetConfig(HidumpConfig & config)256 void HidumpPlugin::SetConfig(HidumpConfig& config)
257 {
258 protoConfig_ = config;
259 }
260
SetTestCmd(const char * test_cmd)261 int HidumpPlugin::SetTestCmd(const char *test_cmd)
262 {
263 CHECK_NOTNULL(test_cmd, -1, "HidumpPlugin:%s test_cmd is null", __func__);
264 testCmd_ = const_cast<char *>(test_cmd);
265 return 0;
266 }
267
GetTestCmd(void)268 const char *HidumpPlugin::GetTestCmd(void)
269 {
270 return testCmd_;
271 }
272