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