1 /*
2 * Copyright (C) 2023 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 #include <errno.h>
16 #include <inttypes.h>
17 #include <limits.h>
18 #include <fcntl.h>
19 #include <pthread.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdbool.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <zlib.h>
26
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <sys/utsname.h>
30
31 #include "cJSON.h"
32 #include "init_module_engine.h"
33 #include "init_param.h"
34 #include "init_utils.h"
35 #include "plugin_adapter.h"
36 #include "securec.h"
37
38 #define MAX_SYS_FILES 11
39 #define CHUNK_SIZE 65536
40 #define BLOCK_SIZE 4096
41 #define WAIT_MILLISECONDS 10
42 #define BUFFER_SIZE_KB 10240 // 10M
43
44 #define TRACE_CFG_KERNEL "KERNEL"
45 #define TRACE_CFG_USER "USER"
46 #define TRACE_TAG_PARAMETER "debug.hitrace.tags.enableflags"
47 #define TRACE_DEBUG_FS_PATH "/sys/kernel/debug/tracing/"
48 #define TRACE_FS_PATH "/sys/kernel/tracing/"
49 #define TRACE_CFG_PATH STARTUP_INIT_UT_PATH"/system/etc/init_trace.cfg"
50 #define TRACE_OUTPUT_PATH "/data/service/el0/startup/init/init_trace.log"
51 #define TRACE_OUTPUT_PATH_ZIP "/data/service/el0/startup/init/init_trace.zip"
52
53 #define TRACE_CMD "ohos.servicectrl.init_trace"
54
55 // various operating paths of ftrace
56 #define TRACING_ON_PATH "tracing_on"
57 #define TRACE_PATH "trace"
58 #define TRACE_MARKER_PATH "trace_marker"
59 #define TRACE_CURRENT_TRACER "current_tracer"
60 #define TRACE_BUFFER_SIZE_KB "buffer_size_kb"
61 #define TRACE_CLOCK "trace_clock"
62 #define TRACE_DEF_CLOCK "boot"
63
64 typedef enum {
65 TRACE_STATE_IDLE,
66 TRACE_STATE_STARTED,
67 TRACE_STATE_STOPED,
68 TRACE_STATE_INTERRUPT
69 } TraceState;
70
71 typedef struct {
72 char *traceRootPath;
73 char buffer[PATH_MAX];
74 cJSON *jsonRootNode;
75 TraceState traceState;
76 uint32_t compress : 1;
77 } TraceWorkspace;
78
79 static TraceWorkspace g_traceWorkspace = {NULL, {0}, NULL, 0, 0};
GetTraceWorkspace(void)80 static TraceWorkspace *GetTraceWorkspace(void)
81 {
82 return &g_traceWorkspace;
83 }
84
ReadFile(const char * path)85 static char *ReadFile(const char *path)
86 {
87 struct stat fileStat = {0};
88 if (stat(path, &fileStat) != 0 || fileStat.st_size <= 0) {
89 PLUGIN_LOGE("Invalid file %s or buffer %zu", path, fileStat.st_size);
90 return NULL;
91 }
92 char realPath[PATH_MAX] = "";
93 realpath(path, realPath);
94 FILE *fd = fopen(realPath, "r");
95 PLUGIN_CHECK(fd != NULL, return NULL, "Failed to fopen path %s", path);
96 char *buffer = NULL;
97 do {
98 buffer = (char*)calloc((size_t)(fileStat.st_size + 1), sizeof(char));
99 PLUGIN_CHECK(buffer != NULL, break, "Failed to alloc memory for path %s", path);
100 if (fread(buffer, fileStat.st_size, 1, fd) != 1) {
101 PLUGIN_LOGE("Failed to read file %s errno:%d", path, errno);
102 free(buffer);
103 buffer = NULL;
104 } else {
105 buffer[fileStat.st_size] = '\0';
106 }
107 } while (0);
108 (void)fclose(fd);
109 return buffer;
110 }
111
InitTraceWorkspace(TraceWorkspace * workspace)112 static int InitTraceWorkspace(TraceWorkspace *workspace)
113 {
114 workspace->traceRootPath = NULL;
115 workspace->traceState = TRACE_STATE_IDLE;
116 workspace->compress = 0;
117 char *fileBuf = ReadFile(TRACE_CFG_PATH);
118 PLUGIN_CHECK(fileBuf != NULL, return -1, "Failed to read file content %s", TRACE_CFG_PATH);
119 workspace->jsonRootNode = cJSON_Parse(fileBuf);
120 PLUGIN_CHECK(workspace->jsonRootNode != NULL, free(fileBuf);
121 return -1, "Failed to parse json file %s", TRACE_CFG_PATH);
122 workspace->compress = cJSON_IsTrue(cJSON_GetObjectItem(workspace->jsonRootNode, "compress")) ? 1 : 0;
123 PLUGIN_LOGI("InitTraceWorkspace compress :%d", workspace->compress);
124 free(fileBuf);
125 return 0;
126 }
127
DestroyTraceWorkspace(TraceWorkspace * workspace)128 static void DestroyTraceWorkspace(TraceWorkspace *workspace)
129 {
130 if (workspace->traceRootPath) {
131 free(workspace->traceRootPath);
132 workspace->traceRootPath = NULL;
133 }
134 if (workspace->jsonRootNode) {
135 cJSON_Delete(workspace->jsonRootNode);
136 workspace->jsonRootNode = NULL;
137 }
138 workspace->traceState = TRACE_STATE_IDLE;
139 }
140
IsTraceMountedInner(TraceWorkspace * workspace,const char * fsPath)141 static bool IsTraceMountedInner(TraceWorkspace *workspace, const char *fsPath)
142 {
143 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer),
144 "%s%s", fsPath, TRACE_MARKER_PATH);
145 PLUGIN_CHECK(len > 0, return false, "Failed to format path %s", fsPath);
146 if (access(workspace->buffer, F_OK) != -1) {
147 workspace->traceRootPath = strdup(fsPath);
148 PLUGIN_CHECK(workspace->traceRootPath != NULL, return false, "Failed to dup fsPath");
149 return true;
150 }
151 return false;
152 }
153
IsTraceMounted(TraceWorkspace * workspace)154 static bool IsTraceMounted(TraceWorkspace *workspace)
155 {
156 return IsTraceMountedInner(workspace, TRACE_DEBUG_FS_PATH) ||
157 IsTraceMountedInner(workspace, TRACE_FS_PATH);
158 }
159
IsWritableFile(const char * filename)160 static bool IsWritableFile(const char *filename)
161 {
162 TraceWorkspace *workspace = GetTraceWorkspace();
163 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
164 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer),
165 "%s%s", workspace->traceRootPath, filename);
166 PLUGIN_CHECK(len > 0, return false, "Failed to format path %s", filename);
167 return access(workspace->buffer, W_OK) != -1;
168 }
169
WriteStrToFile(const char * filename,const char * str)170 static bool WriteStrToFile(const char *filename, const char *str)
171 {
172 PLUGIN_LOGV("WriteStrToFile filename %s %s", filename, str);
173 TraceWorkspace *workspace = GetTraceWorkspace();
174 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
175 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer),
176 "%s%s", workspace->traceRootPath, filename);
177 PLUGIN_CHECK(len > 0, return false, "Failed to format path %s", filename);
178 char realPath[PATH_MAX] = "";
179 realpath(workspace->buffer, realPath);
180 FILE *outfile = fopen(realPath, "w");
181 PLUGIN_CHECK(outfile != NULL, return false, "Failed to open file %s.", workspace->buffer);
182 (void)fprintf(outfile, "%s", str);
183 (void)fflush(outfile);
184 (void)fclose(outfile);
185 return true;
186 }
187
SetTraceEnabled(const char * path,bool enabled)188 static bool SetTraceEnabled(const char *path, bool enabled)
189 {
190 return WriteStrToFile(path, enabled ? "1" : "0");
191 }
192
SetBufferSize(int bufferSize)193 static bool SetBufferSize(int bufferSize)
194 {
195 if (!WriteStrToFile(TRACE_CURRENT_TRACER, "nop")) {
196 PLUGIN_LOGE("%s", "Error: write \"nop\" to %s\n", TRACE_CURRENT_TRACER);
197 }
198 char buffer[20] = {0}; // 20 max int number
199 int len = sprintf_s((char *)buffer, sizeof(buffer), "%d", bufferSize);
200 PLUGIN_CHECK(len > 0, return false, "Failed to format int %d", bufferSize);
201 PLUGIN_LOGE("SetBufferSize path %s %s", TRACE_BUFFER_SIZE_KB, buffer);
202 return WriteStrToFile(TRACE_BUFFER_SIZE_KB, buffer);
203 }
204
SetClock(const char * timeClock)205 static bool SetClock(const char *timeClock)
206 {
207 return WriteStrToFile(TRACE_CLOCK, timeClock);
208 }
209
SetOverWriteEnable(bool enabled)210 static bool SetOverWriteEnable(bool enabled)
211 {
212 return SetTraceEnabled("options/overwrite", enabled);
213 }
214
SetTgidEnable(bool enabled)215 static bool SetTgidEnable(bool enabled)
216 {
217 return SetTraceEnabled("options/record-tgid", enabled);
218 }
219
SetTraceTagsEnabled(uint64_t tags)220 static bool SetTraceTagsEnabled(uint64_t tags)
221 {
222 TraceWorkspace *workspace = GetTraceWorkspace();
223 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
224 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer), "%" PRIu64 "", tags);
225 PLUGIN_CHECK(len > 0, return false, "Failed to format tags %" PRId64 "", tags);
226 return SystemWriteParam(TRACE_TAG_PARAMETER, workspace->buffer) == 0;
227 }
228
RefreshServices()229 static bool RefreshServices()
230 {
231 return true;
232 }
233
GetArrayItem(const cJSON * fileRoot,int * arrSize,const char * arrName)234 static cJSON *GetArrayItem(const cJSON *fileRoot, int *arrSize, const char *arrName)
235 {
236 cJSON *arrItem = cJSON_GetObjectItemCaseSensitive(fileRoot, arrName);
237 PLUGIN_CHECK(cJSON_IsArray(arrItem), return NULL);
238 *arrSize = cJSON_GetArraySize(arrItem);
239 return *arrSize > 0 ? arrItem : NULL;
240 }
241
SetUserSpaceSettings(void)242 static bool SetUserSpaceSettings(void)
243 {
244 TraceWorkspace *workspace = GetTraceWorkspace();
245 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
246 int size = 0;
247 cJSON *userItem = GetArrayItem(workspace->jsonRootNode, &size, TRACE_CFG_USER);
248 PLUGIN_CHECK(userItem != NULL, return false, "Failed to get user info");
249
250 PLUGIN_LOGI("SetUserSpaceSettings: %d", size);
251 uint64_t enabledTags = 0;
252 for (int i = 0; i < size; i++) {
253 cJSON *item = cJSON_GetArrayItem(userItem, i);
254 PLUGIN_LOGI("Tag name = %s ", cJSON_GetStringValue(cJSON_GetObjectItem(item, "name")));
255 int tag = cJSON_GetNumberValue(cJSON_GetObjectItem(item, "tag"));
256 enabledTags |= 1ULL << tag;
257 }
258 PLUGIN_LOGI("User enabledTags: %" PRId64 "", enabledTags);
259 return SetTraceTagsEnabled(enabledTags) && RefreshServices();
260 }
261
ClearUserSpaceSettings(void)262 static bool ClearUserSpaceSettings(void)
263 {
264 return SetTraceTagsEnabled(0) && RefreshServices();
265 }
266
SetKernelTraceEnabled(const TraceWorkspace * workspace,bool enabled)267 static bool SetKernelTraceEnabled(const TraceWorkspace *workspace, bool enabled)
268 {
269 bool result = true;
270 PLUGIN_LOGI("SetKernelTraceEnabled %s", enabled ? "enable" : "disable");
271 int size = 0;
272 cJSON *kernelItem = GetArrayItem(workspace->jsonRootNode, &size, TRACE_CFG_KERNEL);
273 PLUGIN_CHECK(kernelItem != NULL, return false, "Failed to get user info");
274 for (int i = 0; i < size; i++) {
275 cJSON *tagJson = cJSON_GetArrayItem(kernelItem, i);
276 const char *name = cJSON_GetStringValue(cJSON_GetObjectItem(tagJson, "name"));
277 int pathCount = 0;
278 cJSON *paths = GetArrayItem(tagJson, &pathCount, "sys-files");
279 if (paths == NULL) {
280 continue;
281 }
282 PLUGIN_LOGV("Kernel tag name: %s sys-files %d", name, pathCount);
283 for (int j = 0; j < pathCount; j++) {
284 char *path = cJSON_GetStringValue(cJSON_GetArrayItem(paths, j));
285 PLUGIN_CHECK(path != NULL, continue);
286 if (!IsWritableFile(path)) {
287 PLUGIN_LOGW("Path %s is not writable for %s", path, name);
288 continue;
289 }
290 result = result && SetTraceEnabled(path, enabled);
291 }
292 }
293 return result;
294 }
295
DisableAllTraceEvents(void)296 static bool DisableAllTraceEvents(void)
297 {
298 TraceWorkspace *workspace = GetTraceWorkspace();
299 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
300 return SetKernelTraceEnabled(workspace, false);
301 }
302
CheckKernelType(bool * isLinux)303 static void CheckKernelType(bool *isLinux)
304 {
305 struct utsname uts;
306 if (uname(&uts) == -1) {
307 PLUGIN_LOGE("Kernel type get failed,errno:d", errno);
308 return;
309 }
310
311 if (strcmp(uts.sysname, "Linux") == 0) {
312 PLUGIN_LOGE("Kernel type is linux");
313 *isLinux = true;
314 return;
315 }
316
317 *isLinux = false;
318 }
319
SetKernelSpaceSettings(void)320 static bool SetKernelSpaceSettings(void)
321 {
322 TraceWorkspace *workspace = GetTraceWorkspace();
323 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
324 bool ret = SetBufferSize(BUFFER_SIZE_KB);
325 PLUGIN_CHECK(ret, return false, "Failed to set buffer");
326 ret = SetClock(TRACE_DEF_CLOCK);
327 PLUGIN_CHECK(ret, return false, "Failed to set clock");
328 bool isLinux = false;
329 CheckKernelType(&isLinux);
330 if (isLinux) {
331 ret = SetOverWriteEnable(true);
332 PLUGIN_CHECK(ret, return false, "Failed to set write enable");
333 ret = SetTgidEnable(true);
334 PLUGIN_CHECK(ret, return false, "Failed to set tgid enable");
335 }
336 ret = SetKernelTraceEnabled(workspace, false);
337 PLUGIN_CHECK(ret, return false, "Pre-clear kernel tracers failed");
338 return SetKernelTraceEnabled(workspace, true);
339 }
340
ClearKernelSpaceSettings(void)341 static bool ClearKernelSpaceSettings(void)
342 {
343 return DisableAllTraceEvents() && SetOverWriteEnable(true) && SetBufferSize(1) && SetClock("boot");
344 }
345
ClearTrace(void)346 static bool ClearTrace(void)
347 {
348 TraceWorkspace *workspace = GetTraceWorkspace();
349 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
350
351 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer),
352 "%s%s", workspace->traceRootPath, TRACE_PATH);
353 PLUGIN_CHECK(len > 0, return false, "Failed to format path %s", TRACE_PATH);
354 char realPath[PATH_MAX] = "";
355 realpath(workspace->buffer, realPath);
356 // clear old trace file
357 int fd = open(realPath, O_RDWR);
358 PLUGIN_CHECK(fd >= 0, return false, "Failed to open file %s errno %d", workspace->buffer, errno);
359 (void)ftruncate(fd, 0);
360 close(fd);
361 return true;
362 }
363
DumpCompressedTrace(int traceFd,int outFd)364 static void DumpCompressedTrace(int traceFd, int outFd)
365 {
366 int flush = Z_NO_FLUSH;
367 uint8_t *inBuffer = calloc(1, CHUNK_SIZE);
368 PLUGIN_CHECK(inBuffer != NULL, return, "Error: couldn't allocate buffers\n");
369 uint8_t *outBuffer = malloc(CHUNK_SIZE);
370 PLUGIN_CHECK(outBuffer != NULL, free(inBuffer);
371 return, "Error: couldn't allocate buffers\n");
372
373 z_stream zs = {};
374 int ret = 0;
375 deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, 8, Z_DEFAULT_STRATEGY); // 16 8 bit
376 do {
377 // read data
378 ssize_t bytesRead = TEMP_FAILURE_RETRY(read(traceFd, inBuffer, CHUNK_SIZE));
379 PLUGIN_CHECK(bytesRead >= 0, break, "Error: reading trace, errno: %d\n", errno);
380 zs.avail_in = (uInt)bytesRead;
381 flush = zs.avail_in == 0 ? Z_FINISH : Z_NO_FLUSH;
382 zs.next_in = inBuffer;
383 do {
384 zs.next_out = outBuffer;
385 zs.avail_out = CHUNK_SIZE;
386 ret = deflate(&zs, flush);
387 PLUGIN_CHECK(ret != Z_STREAM_ERROR, break, "Error: deflate trace, errno: %d\n", errno);
388 size_t have = CHUNK_SIZE - zs.avail_out;
389 size_t bytesWritten = (size_t)TEMP_FAILURE_RETRY(write(outFd, outBuffer, have));
390 PLUGIN_CHECK(bytesWritten >= have, flush = Z_FINISH; break,
391 "Error: writing deflated trace, errno: %d\n", errno);
392 } while (zs.avail_out == 0);
393 } while (flush != Z_FINISH);
394
395 ret = deflateEnd(&zs);
396 PLUGIN_ONLY_LOG(ret == Z_OK, "error cleaning up zlib: %d\n", ret);
397 free(inBuffer);
398 free(outBuffer);
399 }
400
DumpTrace(const TraceWorkspace * workspace,int outFd,const char * path)401 static void DumpTrace(const TraceWorkspace *workspace, int outFd, const char *path)
402 {
403 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer), "%s%s", workspace->traceRootPath, path);
404 PLUGIN_CHECK(len > 0, return, "Failed to format path %s", path);
405 char realPath[PATH_MAX] = "";
406 realpath(workspace->buffer, realPath);
407 int traceFd = open(realPath, O_RDWR);
408 PLUGIN_CHECK(traceFd >= 0, return, "Failed to open file %s errno %d", workspace->buffer, errno);
409
410 ssize_t bytesWritten;
411 ssize_t bytesRead;
412 if (workspace->compress) {
413 DumpCompressedTrace(traceFd, outFd);
414 } else {
415 char buffer[BLOCK_SIZE];
416 do {
417 bytesRead = TEMP_FAILURE_RETRY(read(traceFd, buffer, BLOCK_SIZE));
418 if ((bytesRead == 0) || (bytesRead == -1)) {
419 break;
420 }
421 bytesWritten = TEMP_FAILURE_RETRY(write(outFd, buffer, bytesRead));
422 } while (bytesWritten > 0);
423 }
424 close(traceFd);
425 }
426
MarkOthersClockSync(void)427 static bool MarkOthersClockSync(void)
428 {
429 TraceWorkspace *workspace = GetTraceWorkspace();
430 PLUGIN_CHECK(workspace != NULL, return false, "Failed to get trace workspace");
431 int len = sprintf_s((char *)workspace->buffer, sizeof(workspace->buffer), "%s%s",
432 workspace->traceRootPath, TRACE_MARKER_PATH);
433 PLUGIN_CHECK(len > 0, return false, "Failed to format path %s", TRACE_MARKER_PATH);
434
435 struct timespec mts = {0, 0};
436 struct timespec rts = {0, 0};
437 if (clock_gettime(CLOCK_REALTIME, &rts) == -1) {
438 PLUGIN_LOGE("Error: get realtime, errno: %d", errno);
439 return false;
440 } else if (clock_gettime(CLOCK_MONOTONIC, &mts) == -1) {
441 PLUGIN_LOGE("Error: get monotonic, errno: %d\n", errno);
442 return false;
443 }
444 const unsigned int nanoSeconds = 1000000000; // seconds converted to nanoseconds
445 const unsigned int nanoToMill = 1000000; // millisecond converted to nanoseconds
446 const float nanoToSecond = 1000000000.0f; // consistent with the ftrace timestamp format
447
448 PLUGIN_LOGE("MarkOthersClockSync %s", workspace->buffer);
449 char realPath[PATH_MAX] = { 0 };
450 realpath(workspace->buffer, realPath);
451 FILE *file = fopen(realPath, "wt+");
452 PLUGIN_CHECK(file != NULL, return false, "Error: opening %s, errno: %d", TRACE_MARKER_PATH, errno);
453 do {
454 int64_t realtime = ((int64_t)rts.tv_sec * nanoSeconds + rts.tv_nsec) / nanoToMill;
455 float parentTs = (float)((((float)mts.tv_sec) * nanoSeconds + mts.tv_nsec) / nanoToSecond);
456 int ret = fprintf(file, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime);
457 PLUGIN_CHECK(ret > 0, break, "Warning: writing clock sync marker, errno: %d", errno);
458 ret = fprintf(file, "trace_event_clock_sync: parent_ts=%f\n", parentTs);
459 PLUGIN_CHECK(ret > 0, break, "Warning: writing clock sync marker, errno: %d", errno);
460 } while (0);
461 (void)fclose(file);
462 return true;
463 }
464
InitStartTrace(void)465 static int InitStartTrace(void)
466 {
467 TraceWorkspace *workspace = GetTraceWorkspace();
468 PLUGIN_CHECK(workspace != NULL, return 0, "Failed to get trace workspace");
469 PLUGIN_CHECK(workspace->traceState == TRACE_STATE_IDLE, return 0,
470 "Invalid state for trace %d", workspace->traceState);
471
472 InitTraceWorkspace(workspace);
473 PLUGIN_CHECK(IsTraceMounted(workspace), return -1);
474
475 PLUGIN_CHECK(workspace->traceRootPath != NULL && workspace->jsonRootNode != NULL,
476 return -1, "No trace root path or config");
477
478 // load json init_trace.cfg
479 if (!SetKernelSpaceSettings() || !SetTraceEnabled(TRACING_ON_PATH, true)) {
480 PLUGIN_LOGE("Failed to enable kernel space setting");
481 ClearKernelSpaceSettings();
482 return -1;
483 }
484 ClearTrace();
485 PLUGIN_LOGI("capturing trace...");
486 if (!SetUserSpaceSettings()) {
487 PLUGIN_LOGE("Failed to enable user space setting");
488 ClearKernelSpaceSettings();
489 ClearUserSpaceSettings();
490 return -1;
491 }
492 workspace->traceState = TRACE_STATE_STARTED;
493 return 0;
494 }
495
InitStopTrace(void)496 static int InitStopTrace(void)
497 {
498 PLUGIN_LOGI("Stop trace now ...");
499 TraceWorkspace *workspace = GetTraceWorkspace();
500 PLUGIN_CHECK(workspace != NULL, return 0, "Failed to get trace workspace");
501 PLUGIN_CHECK(workspace->traceState == TRACE_STATE_STARTED, return 0, "Invalid state for trace %d",
502 workspace->traceState);
503 workspace->traceState = TRACE_STATE_STOPED;
504
505 MarkOthersClockSync();
506 // clear user tags first and sleep a little to let apps already be notified.
507 ClearUserSpaceSettings();
508 usleep(WAIT_MILLISECONDS);
509 SetTraceEnabled(TRACING_ON_PATH, false);
510
511 const char *path = workspace->compress ? TRACE_OUTPUT_PATH_ZIP : TRACE_OUTPUT_PATH;
512 int outFd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
513 if (outFd >= 0) {
514 DumpTrace(workspace, outFd, TRACE_PATH);
515 close(outFd);
516 } else {
517 PLUGIN_LOGE("Failed to open file '%s', err=%d", path, errno);
518 }
519
520 ClearTrace();
521 // clear kernel setting including clock type after dump(MUST) and tracing_on is off.
522 ClearKernelSpaceSettings();
523 // init hitrace config
524 DoJobNow("init-hitrace");
525 DestroyTraceWorkspace(workspace);
526 return 0;
527 }
528
InitInterruptTrace(void)529 static int InitInterruptTrace(void)
530 {
531 PLUGIN_LOGI("Interrupt trace now ...");
532 TraceWorkspace *workspace = GetTraceWorkspace();
533 PLUGIN_CHECK(workspace != NULL, return 0, "Failed to get trace workspace");
534 PLUGIN_CHECK(workspace->traceState == TRACE_STATE_STARTED, return 0,
535 "Invalid state for trace %d", workspace->traceState);
536
537 workspace->traceState = TRACE_STATE_INTERRUPT;
538 MarkOthersClockSync();
539 // clear user tags first and sleep a little to let apps already be notified.
540 ClearUserSpaceSettings();
541 SetTraceEnabled(TRACING_ON_PATH, false);
542 ClearTrace();
543 // clear kernel setting including clock type after dump(MUST) and tracing_on is off.
544 ClearKernelSpaceSettings();
545 // init hitrace config
546 DoJobNow("init-hitrace");
547 DestroyTraceWorkspace(workspace);
548 return 0;
549 }
550
IsTraceModeOpen(void)551 static bool IsTraceModeOpen(void)
552 {
553 char enabled[PARAM_VALUE_LEN_MAX] = {0};
554 uint32_t len = PARAM_VALUE_LEN_MAX;
555 int ret = SystemReadParam("persist.init.trace.enabled", enabled, &len);
556 PLUGIN_LOGI("SystemReadParam persist.init.trace.enabled:%s, ret:%d", enabled, ret);
557 if (ret == 0) {
558 if (strcmp(enabled, "1") == 0) {
559 return true;
560 }
561 }
562 return false;
563 }
564
DoInitTraceCmd(int id,const char * name,int argc,const char ** argv)565 static int DoInitTraceCmd(int id, const char *name, int argc, const char **argv)
566 {
567 PLUGIN_CHECK(IsTraceModeOpen(), return -1, "init trace disabled");
568 PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter");
569 PLUGIN_LOGI("DoInitTraceCmd argc %d cmd %s", argc, argv[0]);
570 if (strcmp(argv[0], "start") == 0) {
571 return InitStartTrace();
572 } else if (strcmp(argv[0], "stop") == 0) {
573 return InitStopTrace();
574 } else if (strcmp(argv[0], "1") == 0) {
575 return InitInterruptTrace();
576 }
577 return 0;
578 }
579
580 static int g_executorId = -1;
InitTraceInit(void)581 static int InitTraceInit(void)
582 {
583 if (g_executorId == -1) {
584 g_executorId = AddCmdExecutor("init_trace", DoInitTraceCmd);
585 PLUGIN_LOGI("InitTraceInit executorId %d", g_executorId);
586 }
587 return 0;
588 }
589
InitTraceExit(void)590 static void InitTraceExit(void)
591 {
592 PLUGIN_LOGI("InitTraceExit executorId %d", g_executorId);
593 if (g_executorId != -1) {
594 RemoveCmdExecutor("init_trace", g_executorId);
595 }
596 }
597
MODULE_CONSTRUCTOR(void)598 MODULE_CONSTRUCTOR(void)
599 {
600 PLUGIN_LOGI("Start trace now ...");
601 InitTraceInit();
602 }
603
MODULE_DESTRUCTOR(void)604 MODULE_DESTRUCTOR(void)
605 {
606 InitStopTrace();
607 InitTraceExit();
608 }
609