data-convert-json.c 12 KB

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