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