Debian Codegraph @

utils/v4l2-tracer/v4l2-tracer.cpp

raw
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3 * Copyright 2022 Collabora Ltd.
4 */
5
6 #include "retrace.h"
7 #include <climits>
8 #include <sys/stat.h>
9 #include <sys/wait.h>
10 #include <time.h>
11
12 int tracer(int argc, char *argv[], bool retrace = false);
13
14 pid_t tracee_pid = 0;
15
16 void v4l2_tracer_sig_handler(int signum)
17 {
18 line_info("\n\tReceived signum: %d", signum);
19
20 /* If there is a tracee, wait for it to handle the signal first before exiting. */
21 if (tracee_pid) {
22 kill(tracee_pid, signum);
23 wait(nullptr);
24 }
25 }
26
27 enum Options {
28 V4l2TracerOptCompactPrint = 'c',
29 V4l2TracerOptSetVideoDevice = 'd',
30 V4l2TracerOptDebug = 'g',
31 V4l2TracerOptHelp = 'h',
32 V4l2TracerOptSetMediaDevice = 'm',
33 V4l2TracerOptWriteDecodedToJson = 'r',
34 V4l2TracerOptTraceUserspaceArg = 'u',
35 V4l2TracerOptVerbose = 'v',
36 V4l2TracerOptWriteDecodedToYUVFile = 'y',
37 };
38
39 const static struct option long_options[] = {
40 { "compact", no_argument, nullptr, V4l2TracerOptCompactPrint },
41 { "video_device", required_argument, nullptr, V4l2TracerOptSetVideoDevice },
42 { "debug", no_argument, nullptr, V4l2TracerOptDebug },
43 { "help", no_argument, nullptr, V4l2TracerOptHelp },
44 { "media_device", required_argument, nullptr, V4l2TracerOptSetMediaDevice },
45 { "raw", no_argument, nullptr, V4l2TracerOptWriteDecodedToJson },
46 { "userspace", no_argument, nullptr, V4l2TracerOptTraceUserspaceArg},
47 { "verbose", no_argument, nullptr, V4l2TracerOptVerbose },
48 { "yuv", no_argument, nullptr, V4l2TracerOptWriteDecodedToYUVFile },
49 { nullptr, 0, nullptr, 0 }
50 };
51
52 const char short_options[] = {
53 V4l2TracerOptCompactPrint,
54 V4l2TracerOptSetVideoDevice, ':',
55 V4l2TracerOptDebug,
56 V4l2TracerOptHelp,
57 V4l2TracerOptSetMediaDevice, ':',
58 V4l2TracerOptWriteDecodedToJson,
59 V4l2TracerOptTraceUserspaceArg,
60 V4l2TracerOptVerbose,
61 V4l2TracerOptWriteDecodedToYUVFile
62 };
63
64 int get_options(int argc, char *argv[])
65 {
66 int option = 0;
67
68 do {
69 /* If there are no commands after the valid options, return err. */
70 if (optind == argc) {
71 print_usage();
72 return -1;
73 }
74
75 /* Avoid reading the tracee's options. */
76 if ((strcmp(argv[optind], "trace") == 0) || (strcmp(argv[optind], "retrace") == 0))
77 return 0;
78
79 option = getopt_long(argc, argv, short_options, long_options, NULL);
80 switch (option) {
81 case V4l2TracerOptCompactPrint: {
82 setenv("V4L2_TRACER_OPTION_COMPACT_PRINT", "true", 0);
83 break;
84 }
85 case V4l2TracerOptSetVideoDevice: {
86 std::string device_num = optarg;
87 try {
88 std::stoi(device_num, nullptr, 0);
89 } catch (std::exception& e) {
90 line_info("\n\tCan't convert <dev> \'%s\' to integer.", device_num.c_str());
91 return -1;
92 }
93 if (device_num[0] >= '0' && device_num[0] <= '9' && device_num.length() <= 3) {
94 std::string path_video = "/dev/video";
95 path_video += optarg;
96 setenv("V4L2_TRACER_OPTION_SET_VIDEO_DEVICE", path_video.c_str(), 0);
97 } else {
98 line_info("\n\tCan't use device number\'%s\'", device_num.c_str());
99 return -1;
100 }
101 break;
102 }
103 case V4l2TracerOptDebug:
104 setenv("V4L2_TRACER_OPTION_VERBOSE", "true", 0);
105 setenv("V4L2_TRACER_OPTION_DEBUG", "true", 0);
106 break;
107 case V4l2TracerOptHelp:
108 print_usage();
109 return -1;
110 case V4l2TracerOptSetMediaDevice: {
111 std::string device_num = optarg;
112 try {
113 std::stoi(device_num, nullptr, 0);
114 } catch (std::exception& e) {
115 line_info("\n\tCan't convert <dev> \'%s\' to integer.", device_num.c_str());
116 return -1;
117 }
118 if (device_num[0] >= '0' && device_num[0] <= '9' && device_num.length() <= 3) {
119 std::string path_media = "/dev/media";
120 path_media += optarg;
121 setenv("V4L2_TRACER_OPTION_SET_MEDIA_DEVICE", path_media.c_str(), 0);
122 } else {
123 line_info("\n\tCan't use device number\'%s\'", device_num.c_str());
124 return -1;
125 }
126 break;
127 }
128 case V4l2TracerOptWriteDecodedToJson:
129 setenv("V4L2_TRACER_OPTION_WRITE_DECODED_TO_JSON_FILE", "true", 0);
130 break;
131 case V4l2TracerOptTraceUserspaceArg:
132 setenv("V4L2_TRACER_OPTION_TRACE_USERSPACE_ARG", "true", 0);
133 break;
134 case V4l2TracerOptVerbose:
135 setenv("V4L2_TRACER_OPTION_VERBOSE", "true", 0);
136 break;
137 case V4l2TracerOptWriteDecodedToYUVFile:
138 setenv("V4L2_TRACER_OPTION_WRITE_DECODED_TO_YUV_FILE", "true", 0);
139 break;
140 default:
141 break;
142 }
143
144 /* invalid option */
145 if (optopt > 0) {
146 print_usage();
147 return -1;
148 }
149
150 } while (option != -1);
151
152 return 0;
153 }
154
155 int clean(std::string trace_filename)
156 {
157 FILE *trace_file = fopen(trace_filename.c_str(), "r");
158 if (trace_file == nullptr) {
159 line_info("\n\tCan't open \'%s\'", trace_filename.c_str());
160 return 1;
161 }
162
163 fprintf(stderr, "Cleaning: %s\n", trace_filename.c_str());
164
165 std::string clean_filename = "clean_" + trace_filename;
166 FILE *clean_file = fopen(clean_filename.c_str(), "w");
167 if (clean_file == nullptr) {
168 line_info("\n\tCan't open \'%s\'", clean_filename.c_str());
169 return 1;
170 }
171
172 std::string line;
173 char buf[SHRT_MAX];
174 int count_total = 0;
175 int count_lines_removed = 0;
176
177 while (fgets(buf, SHRT_MAX, trace_file) != nullptr) {
178 line = buf;
179 count_total++;
180 if (line.find("fd") != std::string::npos) {
181 count_lines_removed++;
182 continue;
183 }
184 if (line.find("address") != std::string::npos) {
185 count_lines_removed++;
186 continue;
187 }
188 if (line.find("fildes") != std::string::npos) {
189 count_lines_removed++;
190 continue;
191 }
192 if (line.find("\"start\"") != std::string::npos) {
193 count_lines_removed++;
194 continue;
195 }
196 if (line.find("\"name\"") != std::string::npos) {
197 count_lines_removed++;
198 continue;
199 }
200
201 fputs(buf, clean_file);
202 }
203
204 fclose(trace_file);
205 fclose(clean_file);
206 fprintf(stderr, "Removed %d lines of %d total lines: %s\n",
207 count_lines_removed, count_total, clean_filename.c_str());
208
209 return 0;
210 }
211
212 int tracer(int argc, char *argv[], bool retrace)
213 {
214 char *exec[argc];
215 int exec_index = 0;
216
217 char retrace_command[] = "__retrace";
218
219 if (retrace) {
220 std::string trace_file = argv[optind];
221 if (trace_file.find(".json") == std::string::npos) {
222 line_info("\n\tTrace file \'%s\' must have .json file extension",
223 trace_file.c_str());
224 print_usage();
225 return -1;
226 }
227 }
228
229 /* Get the application to be traced. */
230 if (retrace) {
231 exec[exec_index++] = argv[0]; /* tracee is v4l2-tracer, local or installed */
232 exec[exec_index++] = retrace_command;
233 exec[exec_index++] = argv[optind]; /* json file to be retraced */
234 } else {
235 while (optind < argc)
236 exec[exec_index++] = argv[optind++];
237 }
238 exec[exec_index] = nullptr;
239
240 /* Create a unique trace filename and open a file. */
241 std::string trace_id;
242 if (retrace) {
243 std::string json_file_name = argv[optind];
244 trace_id = json_file_name.substr(0, json_file_name.find(".json"));
245 trace_id += "_retrace";
246 } else {
247 const int timestamp_start_pos = 1;
248 trace_id = std::to_string(100000 + time(nullptr) % 100000);
249 trace_id = trace_id.substr(timestamp_start_pos) + "_trace";
250 }
251 setenv("TRACE_ID", trace_id.c_str(), 0);
252 std::string trace_filename = trace_id + ".json";
253 FILE *trace_file = fopen(trace_filename.c_str(), "w");
254 if (trace_file == nullptr) {
255 fprintf(stderr, "Could not open trace file: %s\n", trace_filename.c_str());
256 perror("");
257 return errno;
258 }
259
260 /* Open the json array.*/
261 fputs("[\n", trace_file);
262
263 /* Add v4l-utils package and git info to the top of the trace file. */
264 std::string json_str;
265 json_object *v4l2_tracer_info_obj = json_object_new_object();
266 json_object_object_add(v4l2_tracer_info_obj, "package_version",
267 json_object_new_string(PACKAGE_VERSION));
268 std::string git_commit_cnt = STRING(GIT_COMMIT_CNT);
269 git_commit_cnt = git_commit_cnt.erase(0, 1); /* remove the hyphen in front of git_commit_cnt */
270 json_object_object_add(v4l2_tracer_info_obj, "git_commit_cnt",
271 json_object_new_string(git_commit_cnt.c_str()));
272 json_object_object_add(v4l2_tracer_info_obj, "git_sha",
273 json_object_new_string(STRING(GIT_SHA)));
274 json_object_object_add(v4l2_tracer_info_obj, "git_commit_date",
275 json_object_new_string(STRING(GIT_COMMIT_DATE)));
276 json_str = json_object_to_json_string(v4l2_tracer_info_obj);
277 fwrite(json_str.c_str(), sizeof(char), json_str.length(), trace_file);
278 fputs(",\n", trace_file);
279 json_object_put(v4l2_tracer_info_obj);
280
281 /* Add v4l2-tracer command line to the top of the trace file. */
282 json_object *tracee_obj = json_object_new_object();
283 std::string tracee;
284 for (int i = 0; i < argc; i++) {
285 tracee += argv[i];
286 tracee += " ";
287 }
288 json_object_object_add(tracee_obj, "Trace", json_object_new_string(tracee.c_str()));
289 const time_t current_time = time(nullptr);
290 json_object_object_add(tracee_obj, "Timestamp", json_object_new_string(ctime(&current_time)));
291
292 json_str = json_object_to_json_string(tracee_obj);
293 fwrite(json_str.c_str(), sizeof(char), json_str.length(), trace_file);
294 fputs(",\n", trace_file);
295 json_object_put(tracee_obj);
296 fclose(trace_file);
297
298 /*
299 * Preload the libv4l2tracer library. The tracer is looked up using following order:
300 * 1. Check if LD_PRELOAD is already set, in which case just honor it
301 * 2. Check V4L2_TRACER env is set (meson devenv / uninstalled)
302 * 3. Check in LIBTRACER_PATH for an installed tracer.
303 */
304 std::string libv4l2tracer_path;
305 if (getenv("LD_PRELOAD"))
306 libv4l2tracer_path = std::string(getenv("LD_PRELOAD"));
307 else if (getenv("V4L2_TRACER"))
308 libv4l2tracer_path = std::string(getenv("V4L2_TRACER"));
309 else
310 libv4l2tracer_path = std::string(LIBTRACER_PATH) + "/libv4l2tracer.so";
311
312 struct stat sb;
313 if (stat(libv4l2tracer_path.c_str(), &sb) == -1) {
314 if (stat(libv4l2tracer_path.c_str(), &sb) == -1) {
315 fprintf(stderr, "Exiting: can't find libv4l2tracer library in %s\n", libv4l2tracer_path.c_str());
316 fprintf(stderr, "If you are using a different location, try setting the env 'V4L2_TRACER'\n");
317 exit(EXIT_FAILURE);
318 }
319 }
320
321 if (is_verbose())
322 fprintf(stderr, "Loading libv4l2tracer: %s\n", libv4l2tracer_path.c_str());
323 setenv("LD_PRELOAD", libv4l2tracer_path.c_str(), 0);
324
325 tracee_pid = fork();
326 if (tracee_pid == 0) {
327
328 if (is_debug()) {
329 line_info();
330 fprintf(stderr, "\ttracee: ");
331 for (int i = 0; i < exec_index; i++)
332 fprintf(stderr,"%s ", exec[i]);
333 fprintf(stderr, "\n");
334 }
335
336 execvpe(exec[0], (char* const*) exec, environ);
337 line_info("\n\tCould not execute application \'%s\'", exec[0]);
338 perror(" ");
339 return errno;
340 }
341
342 int exec_result = 0;
343 wait(&exec_result);
344
345 if (WIFEXITED(exec_result))
346 WEXITSTATUS(exec_result);
347
348 fprintf(stderr, "Tracee exited with status: %d\n", exec_result);
349
350 /* Close the json-array and the trace file. */
351 trace_file = fopen(trace_filename.c_str(), "r+");
352 fseek(trace_file, -2L, SEEK_END);
353 fputs("\n]\n", trace_file);
354 fclose(trace_file);
355
356 if (retrace)
357 fprintf(stderr, "Retrace complete: ");
358 else
359 fprintf(stderr, "Trace complete: ");
360 fprintf(stderr, "%s", trace_filename.c_str());
361 fprintf(stderr, "\n");
362
363 unsetenv("LD_PRELOAD");
364 return exec_result;
365 }
366
367 int main(int argc, char *argv[])
368 {
369 int ret = -1;
370
371 if (argc <= 1) {
372 print_usage();
373 return ret;
374 }
375
376 ret = get_options(argc, argv);
377
378 if (ret < 0) {
379 debug_line_info();
380 return ret;
381 }
382
383 if (optind == argc) {
384 debug_line_info();
385 print_usage();
386 return ret;
387 }
388
389 std::string command = argv[optind++];
390
391 if (optind == argc) {
392 debug_line_info();
393 print_usage();
394 return ret;
395 }
396
397 struct sigaction act = {};
398 act.sa_handler = v4l2_tracer_sig_handler;
399 sigaction(SIGINT, &act, nullptr);
400 sigaction(SIGTERM, &act, nullptr);
401
402 if (command == "trace") {
403 ret = tracer(argc, argv);
404 } else if (command == "retrace") {
405 ret = tracer(argc, argv, true);
406 } else if (command == "__retrace") {
407 /*
408 * This command is meant to be used only internally to allow
409 * v4l2-tracer to recursively trace itself during a retrace.
410 */
411 ret = retrace(argv[optind]);
412 } else if (command == "clean") {
413 ret = clean (argv[optind]);
414 } else {
415 if (is_debug()) {
416 line_info("Invalid command");
417 for (int i = 0; i < argc; i++)
418 fprintf(stderr,"%s ", argv[i]);
419 fprintf(stderr, "\n");
420 }
421 print_usage();
422 }
423
424 return ret;
425 }