xref: /linux/tools/perf/util/data-convert-json.c (revision 390d5ea26622f794c2d29cefd5a01ef116b4fe1d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * JSON export.
4  *
5  * Copyright (C) 2021, CodeWeavers Inc. <nfraser@codeweavers.com>
6  */
7 
8 #include "data-convert.h"
9 
10 #include <fcntl.h>
11 #include <inttypes.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 
15 #include "linux/compiler.h"
16 #include "linux/err.h"
17 #include "util/auxtrace.h"
18 #include "util/debug.h"
19 #include "util/dso.h"
20 #include "util/event.h"
21 #include "util/evsel.h"
22 #include "util/evlist.h"
23 #include "util/header.h"
24 #include "util/map.h"
25 #include "util/session.h"
26 #include "util/symbol.h"
27 #include "util/thread.h"
28 #include "util/time-utils.h"
29 #include "util/tool.h"
30 
31 #ifdef HAVE_LIBTRACEEVENT
32 #include <event-parse.h>
33 #endif
34 
35 struct convert_json {
36 	struct perf_tool tool;
37 	FILE *out;
38 	bool first;
39 	struct perf_time_interval *ptime_range;
40 	int range_size;
41 	int range_num;
42 
43 	u64 events_count;
44 	u64 skipped;
45 };
46 
47 // Outputs a JSON-encoded string surrounded by quotes with characters escaped.
48 static void output_json_string(FILE *out, const char *s)
49 {
50 	fputc('"', out);
51 	if (!s)
52 		goto out;
53 
54 	while (*s) {
55 		switch (*s) {
56 
57 		// required escapes with special forms as per RFC 8259
58 		case '"':  fputs("\\\"", out); break;
59 		case '\\': fputs("\\\\", out); break;
60 		case '\b': fputs("\\b", out);  break;
61 		case '\f': fputs("\\f", out);  break;
62 		case '\n': fputs("\\n", out);  break;
63 		case '\r': fputs("\\r", out);  break;
64 		case '\t': fputs("\\t", out);  break;
65 
66 		default:
67 			// all other control characters must be escaped by hex code
68 			if (*s <= 0x1f)
69 				fprintf(out, "\\u%04x", *s);
70 			else
71 				fputc(*s, out);
72 			break;
73 		}
74 
75 		++s;
76 	}
77 out:
78 	fputc('"', out);
79 }
80 
81 // Outputs an optional comma, newline and indentation to delimit a new value
82 // from the previous one in a JSON object or array.
83 static void output_json_delimiters(FILE *out, bool comma, int depth)
84 {
85 	int i;
86 
87 	if (comma)
88 		fputc(',', out);
89 	fputc('\n', out);
90 	for (i = 0; i < depth; ++i)
91 		fputc('\t', out);
92 }
93 
94 // Outputs a printf format string (with delimiter) as a JSON value.
95 __printf(4, 5)
96 static void output_json_format(FILE *out, bool comma, int depth, const char *format, ...)
97 {
98 	va_list args;
99 
100 	output_json_delimiters(out, comma, depth);
101 	va_start(args, format);
102 	vfprintf(out,  format, args);
103 	va_end(args);
104 }
105 
106 // Outputs a JSON key-value pair where the value is a string.
107 static void output_json_key_string(FILE *out, bool comma, int depth,
108 		const char *key, const char *value)
109 {
110 	output_json_delimiters(out, comma, depth);
111 	output_json_string(out, key);
112 	fputs(": ", out);
113 	output_json_string(out, value);
114 }
115 
116 // Outputs a JSON key-value pair where the value is a printf format string.
117 __printf(5, 6)
118 static void output_json_key_format(FILE *out, bool comma, int depth,
119 		const char *key, const char *format, ...)
120 {
121 	va_list args;
122 
123 	output_json_delimiters(out, comma, depth);
124 	output_json_string(out, key);
125 	fputs(": ", out);
126 	va_start(args, format);
127 	vfprintf(out,  format, args);
128 	va_end(args);
129 }
130 
131 static void output_sample_callchain_entry(const struct perf_tool *tool,
132 		u64 ip, struct addr_location *al)
133 {
134 	struct convert_json *c = container_of(tool, struct convert_json, tool);
135 	FILE *out = c->out;
136 
137 	output_json_format(out, false, 4, "{");
138 	output_json_key_format(out, false, 5, "ip", "\"0x%" PRIx64 "\"", ip);
139 
140 	if (al && al->sym && al->sym->namelen) {
141 		struct dso *dso = al->map ? map__dso(al->map) : NULL;
142 
143 		fputc(',', out);
144 		output_json_key_string(out, false, 5, "symbol", al->sym->name);
145 
146 		if (dso) {
147 			const char *dso_name = dso__short_name(dso);
148 
149 			if (dso_name && strlen(dso_name) > 0) {
150 				fputc(',', out);
151 				output_json_key_string(out, false, 5, "dso", dso_name);
152 			}
153 		}
154 	}
155 
156 	output_json_format(out, false, 4, "}");
157 }
158 
159 static int process_sample_event(const struct perf_tool *tool,
160 				union perf_event *event __maybe_unused,
161 				struct perf_sample *sample,
162 				struct machine *machine)
163 {
164 	struct convert_json *c = container_of(tool, struct convert_json, tool);
165 	FILE *out = c->out;
166 	struct addr_location al;
167 	u64 sample_type = __evlist__combined_sample_type(sample->evsel->evlist);
168 	u8 cpumode = PERF_RECORD_MISC_USER;
169 
170 	addr_location__init(&al);
171 	if (machine__resolve(machine, &al, sample) < 0) {
172 		pr_err("Sample resolution failed!\n");
173 		addr_location__exit(&al);
174 		return -1;
175 	}
176 
177 	if (perf_time__ranges_skip_sample(c->ptime_range, c->range_num, sample->time)) {
178 		++c->skipped;
179 		return 0;
180 	}
181 
182 	++c->events_count;
183 
184 	if (c->first)
185 		c->first = false;
186 	else
187 		fputc(',', out);
188 	output_json_format(out, false, 2, "{");
189 
190 	output_json_key_format(out, false, 3, "timestamp", "%" PRIi64, sample->time);
191 	output_json_key_format(out, true, 3, "pid", "%i", thread__pid(al.thread));
192 	output_json_key_format(out, true, 3, "tid", "%i", thread__tid(al.thread));
193 
194 	if ((sample_type & PERF_SAMPLE_CPU))
195 		output_json_key_format(out, true, 3, "cpu", "%i", sample->cpu);
196 	else if (thread__cpu(al.thread) >= 0)
197 		output_json_key_format(out, true, 3, "cpu", "%i", thread__cpu(al.thread));
198 
199 	output_json_key_string(out, true, 3, "comm", thread__comm_str(al.thread));
200 
201 	output_json_key_format(out, true, 3, "callchain", "[");
202 	if (sample->callchain) {
203 		unsigned int i;
204 		bool ok;
205 		bool first_callchain = true;
206 
207 		for (i = 0; i < sample->callchain->nr; ++i) {
208 			u64 ip = sample->callchain->ips[i];
209 			struct addr_location tal;
210 
211 			if (ip >= PERF_CONTEXT_MAX) {
212 				switch (ip) {
213 				case PERF_CONTEXT_HV:
214 					cpumode = PERF_RECORD_MISC_HYPERVISOR;
215 					break;
216 				case PERF_CONTEXT_KERNEL:
217 					cpumode = PERF_RECORD_MISC_KERNEL;
218 					break;
219 				case PERF_CONTEXT_USER:
220 					cpumode = PERF_RECORD_MISC_USER;
221 					break;
222 				default:
223 					pr_debug("invalid callchain context: %"
224 							PRId64 "\n", (s64) ip);
225 					break;
226 				}
227 				continue;
228 			}
229 
230 			if (first_callchain)
231 				first_callchain = false;
232 			else
233 				fputc(',', out);
234 
235 			addr_location__init(&tal);
236 			ok = thread__find_symbol(al.thread, cpumode, ip, &tal);
237 			output_sample_callchain_entry(tool, ip, ok ? &tal : NULL);
238 			addr_location__exit(&tal);
239 		}
240 	} else {
241 		output_sample_callchain_entry(tool, sample->ip, &al);
242 	}
243 	output_json_format(out, false, 3, "]");
244 
245 #ifdef HAVE_LIBTRACEEVENT
246 	if (sample->raw_data) {
247 		struct tep_event *tp_format = evsel__tp_format(sample->evsel);
248 		struct tep_format_field **fields = tp_format ? tep_event_fields(tp_format) : NULL;
249 
250 		if (fields) {
251 			int i = 0;
252 
253 			while (fields[i]) {
254 				struct trace_seq s;
255 
256 				trace_seq_init(&s);
257 				tep_print_field(&s, sample->raw_data, fields[i]);
258 				output_json_key_string(out, true, 3, fields[i]->name, s.buffer);
259 
260 				i++;
261 			}
262 			free(fields);
263 		}
264 	}
265 #endif
266 	output_json_format(out, false, 2, "}");
267 	addr_location__exit(&al);
268 	return 0;
269 }
270 
271 static void output_headers(struct perf_session *session, struct convert_json *c)
272 {
273 	struct stat st;
274 	const struct perf_header *header = &session->header;
275 	const struct perf_env *env = perf_session__env(session);
276 	int ret;
277 	int fd = perf_data__fd(session->data);
278 	int i;
279 	FILE *out = c->out;
280 
281 	output_json_key_format(out, false, 2, "header-version", "%u", header->version);
282 
283 	ret = fstat(fd, &st);
284 	if (ret >= 0) {
285 		time_t stctime = st.st_mtime;
286 		char buf[256];
287 
288 		strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&stctime));
289 		output_json_key_string(out, true, 2, "captured-on", buf);
290 	} else {
291 		pr_debug("Failed to get mtime of source file, not writing captured-on");
292 	}
293 
294 	output_json_key_format(out, true, 2, "data-offset", "%" PRIu64, header->data_offset);
295 	output_json_key_format(out, true, 2, "data-size", "%" PRIu64, header->data_size);
296 	output_json_key_format(out, true, 2, "feat-offset", "%" PRIu64, header->feat_offset);
297 
298 	output_json_key_string(out, true, 2, "hostname", env->hostname);
299 	output_json_key_string(out, true, 2, "os-release", env->os_release);
300 	output_json_key_string(out, true, 2, "arch", env->arch);
301 
302 	if (env->cpu_desc)
303 		output_json_key_string(out, true, 2, "cpu-desc", env->cpu_desc);
304 
305 	output_json_key_string(out, true, 2, "cpuid", env->cpuid);
306 	output_json_key_format(out, true, 2, "nrcpus-online", "%u", env->nr_cpus_online);
307 	output_json_key_format(out, true, 2, "nrcpus-avail", "%u", env->nr_cpus_avail);
308 
309 	if (env->clock.enabled) {
310 		output_json_key_format(out, true, 2, "clockid",
311 				"%u", env->clock.clockid);
312 		output_json_key_format(out, true, 2, "clock-time",
313 				"%" PRIu64, env->clock.clockid_ns);
314 		output_json_key_format(out, true, 2, "real-time",
315 				"%" PRIu64, env->clock.tod_ns);
316 	}
317 
318 	output_json_key_string(out, true, 2, "perf-version", env->version);
319 
320 	output_json_key_format(out, true, 2, "cmdline", "[");
321 	for (i = 0; i < env->nr_cmdline; i++) {
322 		output_json_delimiters(out, i != 0, 3);
323 		output_json_string(c->out, env->cmdline_argv[i]);
324 	}
325 	output_json_format(out, false, 2, "]");
326 }
327 
328 int bt_convert__perf2json(const char *_input_name, const char *output_name,
329 		struct perf_data_convert_opts *opts __maybe_unused)
330 {
331 	struct perf_session *session;
332 	int fd;
333 	int ret = -1;
334 	struct convert_json c = {
335 		.first = true,
336 		.events_count = 0,
337 		.ptime_range = NULL,
338 		.range_size = 0,
339 		.range_num = 0,
340 		.skipped = 0,
341 	};
342 	struct perf_data data = {
343 		.mode = PERF_DATA_MODE_READ,
344 		.path = _input_name,
345 		.force = opts->force,
346 	};
347 
348 	perf_tool__init(&c.tool, /*ordered_events=*/true);
349 	c.tool.sample         = process_sample_event;
350 	c.tool.mmap           = perf_event__process_mmap;
351 	c.tool.mmap2          = perf_event__process_mmap2;
352 	c.tool.comm           = perf_event__process_comm;
353 	c.tool.namespaces     = perf_event__process_namespaces;
354 	c.tool.cgroup         = perf_event__process_cgroup;
355 	c.tool.exit           = perf_event__process_exit;
356 	c.tool.fork           = perf_event__process_fork;
357 	c.tool.lost           = perf_event__process_lost;
358 #ifdef HAVE_LIBTRACEEVENT
359 	c.tool.tracing_data   = perf_event__process_tracing_data;
360 #endif
361 	c.tool.build_id       = perf_event__process_build_id;
362 	c.tool.id_index       = perf_event__process_id_index;
363 	c.tool.auxtrace_info  = perf_event__process_auxtrace_info;
364 	c.tool.auxtrace       = perf_event__process_auxtrace;
365 	c.tool.event_update   = perf_event__process_event_update;
366 	c.tool.attr           = perf_event__process_attr;
367 	c.tool.feature        = perf_event__process_feature;
368 	c.tool.ordering_requires_timestamps = true;
369 
370 	if (opts->all) {
371 		pr_err("--all is currently unsupported for JSON output.\n");
372 		goto err;
373 	}
374 	if (opts->tod) {
375 		pr_err("--tod is currently unsupported for JSON output.\n");
376 		goto err;
377 	}
378 
379 	fd = open(output_name, O_CREAT | O_WRONLY | (opts->force ? O_TRUNC : O_EXCL), 0666);
380 	if (fd == -1) {
381 		if (errno == EEXIST)
382 			pr_err("Output file exists. Use --force to overwrite it.\n");
383 		else
384 			pr_err("Error opening output file!\n");
385 		goto err;
386 	}
387 
388 	c.out = fdopen(fd, "w");
389 	if (!c.out) {
390 		fprintf(stderr, "Error opening output file!\n");
391 		close(fd);
392 		goto err;
393 	}
394 
395 	session = perf_session__new(&data, &c.tool);
396 	if (IS_ERR(session)) {
397 		fprintf(stderr, "Error creating perf session!\n");
398 		goto err_fclose;
399 	}
400 	if (symbol__init(perf_session__env(session)) < 0) {
401 		fprintf(stderr, "Symbol init error!\n");
402 		goto err_session_delete;
403 	}
404 
405 	if (opts->time_str) {
406 		ret = perf_time__parse_for_ranges(opts->time_str, session,
407 						  &c.ptime_range,
408 						  &c.range_size,
409 						  &c.range_num);
410 		if (ret < 0)
411 			goto err_session_delete;
412 	}
413 
414 	// The opening brace is printed manually because it isn't delimited from a
415 	// previous value (i.e. we don't want a leading newline)
416 	fputc('{', c.out);
417 
418 	// Version number for future-proofing. Most additions should be able to be
419 	// done in a backwards-compatible way so this should only need to be bumped
420 	// if some major breaking change must be made.
421 	output_json_format(c.out, false, 1, "\"linux-perf-json-version\": 1");
422 
423 	// Output headers
424 	output_json_format(c.out, true, 1, "\"headers\": {");
425 	output_headers(session, &c);
426 	output_json_format(c.out, false, 1, "}");
427 
428 	// Output samples
429 	output_json_format(c.out, true, 1, "\"samples\": [");
430 	perf_session__process_events(session);
431 	output_json_format(c.out, false, 1, "]");
432 	output_json_format(c.out, false, 0, "}");
433 	fputc('\n', c.out);
434 
435 	fprintf(stderr,	"[ perf data convert: Converted '%s' into JSON data '%s' ]\n",
436 		data.path, output_name);
437 
438 	fprintf(stderr,
439 		"[ perf data convert: Converted and wrote %.3f MB (%" PRIu64 " samples) ]\n",
440 		(ftell(c.out)) / 1024.0 / 1024.0, c.events_count);
441 
442 	if (c.skipped) {
443 		fprintf(stderr,	"[ perf data convert: Skipped %" PRIu64 " samples ]\n",
444 			c.skipped);
445 	}
446 
447 	ret = 0;
448 
449 	if (c.ptime_range)
450 		zfree(&c.ptime_range);
451 
452 err_session_delete:
453 	perf_session__delete(session);
454 err_fclose:
455 	fclose(c.out);
456 err:
457 	return ret;
458 }
459