1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (c) 2015-2017 Daniel Borkmann */
3 /* Copyright (c) 2018 Netronome Systems, Inc. */
11 #include <linux/magic.h>
12 #include <sys/fcntl.h>
18 # define TRACEFS_MAGIC 0x74726163
21 #define _textify(x) #x
22 #define textify(x) _textify(x)
27 static int validate_tracefs_mnt(const char *mnt, unsigned long magic)
31 if (statfs(mnt, &st_fs) < 0)
33 if ((unsigned long)st_fs.f_type != magic)
40 find_tracefs_mnt_single(unsigned long magic, char *mnt, const char *mntpt)
44 if (validate_tracefs_mnt(mntpt, magic))
47 src_len = strlen(mntpt);
48 if (src_len + 1 >= PATH_MAX) {
49 p_err("tracefs mount point name too long");
57 static bool get_tracefs_pipe(char *mnt)
59 static const char * const known_mnts[] = {
60 "/sys/kernel/debug/tracing",
61 "/sys/kernel/tracing",
65 const char *pipe_name = "/trace_pipe";
66 const char *fstype = "tracefs";
67 char type[100], format[32];
68 const char * const *ptr;
72 for (ptr = known_mnts; ptr < known_mnts + ARRAY_SIZE(known_mnts); ptr++)
73 if (find_tracefs_mnt_single(TRACEFS_MAGIC, mnt, *ptr))
76 fp = fopen("/proc/mounts", "r");
80 /* Allow room for NULL terminating byte and pipe file name */
81 snprintf(format, sizeof(format), "%%*s %%%zds %%99s %%*s %%*d %%*d\\n",
82 PATH_MAX - strlen(pipe_name) - 1);
83 while (fscanf(fp, format, mnt, type) == 2)
84 if (strcmp(type, fstype) == 0) {
90 /* The string from fscanf() might be truncated, check mnt is valid */
91 if (found && validate_tracefs_mnt(mnt, TRACEFS_MAGIC))
97 p_info("could not find tracefs, attempting to mount it now");
98 /* Most of the time, tracefs is automatically mounted by debugfs at
99 * /sys/kernel/debug/tracing when we try to access it. If we could not
100 * find it, it is likely that debugfs is not mounted. Let's give one
101 * attempt at mounting just tracefs at /sys/kernel/tracing.
103 strcpy(mnt, known_mnts[1]);
104 if (mount_tracefs(mnt))
108 strcat(mnt, pipe_name);
112 static void exit_tracelog(int signum)
114 fclose(trace_pipe_fd);
118 jsonw_end_array(json_wtr);
119 jsonw_destroy(&json_wtr);
125 int do_tracelog(int argc, char **argv)
127 const struct sigaction act = {
128 .sa_handler = exit_tracelog
130 char trace_pipe[PATH_MAX];
134 jsonw_start_array(json_wtr);
136 if (!get_tracefs_pipe(trace_pipe))
139 trace_pipe_fd = fopen(trace_pipe, "r");
140 if (!trace_pipe_fd) {
141 p_err("could not open trace pipe: %s", strerror(errno));
145 sigaction(SIGHUP, &act, NULL);
146 sigaction(SIGINT, &act, NULL);
147 sigaction(SIGTERM, &act, NULL);
151 ret = getline(&buff, &buff_len, trace_pipe_fd);
153 p_err("failed to read content from trace pipe: %s",
158 jsonw_string(json_wtr, buff);
163 fclose(trace_pipe_fd);