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