1 // SPDX-License-Identifier: GPL-2.0 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <stdbool.h> 5 #include <string.h> 6 #include <assert.h> 7 #include <errno.h> 8 #include <signal.h> 9 #include <inttypes.h> 10 #include <linux/err.h> 11 #include <linux/kernel.h> 12 #include <linux/zalloc.h> 13 #include <api/fs/fs.h> 14 15 #include <byteswap.h> 16 #include <unistd.h> 17 #include <sys/types.h> 18 #include <sys/mman.h> 19 #include <perf/cpumap.h> 20 #include <perf/event.h> 21 22 #include "map_symbol.h" 23 #include "branch.h" 24 #include "debug.h" 25 #include "dwarf-regs.h" 26 #include "env.h" 27 #include "evlist.h" 28 #include "evsel.h" 29 #include "memswap.h" 30 #include "map.h" 31 #include "symbol.h" 32 #include "session.h" 33 #include "tool.h" 34 #include "perf_regs.h" 35 #include "asm/bug.h" 36 #include "auxtrace.h" 37 #include "thread.h" 38 #include "thread-stack.h" 39 #include "sample-raw.h" 40 #include "stat.h" 41 #include "tsc.h" 42 #include "ui/progress.h" 43 #include "util.h" 44 #include "arch/common.h" 45 #include "units.h" 46 #include "annotate.h" 47 #include "perf.h" 48 #include <internal/lib.h> 49 50 static int perf_session__deliver_event(struct perf_session *session, 51 union perf_event *event, 52 const struct perf_tool *tool, 53 u64 file_offset, 54 const char *file_path); 55 56 static int perf_session__open(struct perf_session *session) 57 { 58 struct perf_data *data = session->data; 59 60 if (perf_session__read_header(session) < 0) { 61 pr_err("incompatible file format (rerun with -v to learn more)\n"); 62 return -1; 63 } 64 65 if (perf_header__has_feat(&session->header, HEADER_AUXTRACE)) { 66 /* Auxiliary events may reference exited threads, hold onto dead ones. */ 67 symbol_conf.keep_exited_threads = true; 68 } 69 70 if (perf_data__is_pipe(data)) 71 return 0; 72 73 if (perf_header__has_feat(&session->header, HEADER_STAT)) 74 return 0; 75 76 if (!evlist__valid_sample_type(session->evlist)) { 77 pr_err("non matching sample_type\n"); 78 return -1; 79 } 80 81 if (!evlist__valid_sample_id_all(session->evlist)) { 82 pr_err("non matching sample_id_all\n"); 83 return -1; 84 } 85 86 if (!evlist__valid_read_format(session->evlist)) { 87 pr_err("non matching read_format\n"); 88 return -1; 89 } 90 91 return 0; 92 } 93 94 void perf_session__set_id_hdr_size(struct perf_session *session) 95 { 96 u16 id_hdr_size = evlist__id_hdr_size(session->evlist); 97 98 machines__set_id_hdr_size(&session->machines, id_hdr_size); 99 } 100 101 int perf_session__create_kernel_maps(struct perf_session *session) 102 { 103 int ret = machine__create_kernel_maps(&session->machines.host); 104 105 if (ret >= 0) 106 ret = machines__create_guest_kernel_maps(&session->machines); 107 return ret; 108 } 109 110 static void perf_session__destroy_kernel_maps(struct perf_session *session) 111 { 112 machines__destroy_kernel_maps(&session->machines); 113 } 114 115 static bool perf_session__has_comm_exec(struct perf_session *session) 116 { 117 struct evsel *evsel; 118 119 evlist__for_each_entry(session->evlist, evsel) { 120 if (evsel->core.attr.comm_exec) 121 return true; 122 } 123 124 return false; 125 } 126 127 static void perf_session__set_comm_exec(struct perf_session *session) 128 { 129 bool comm_exec = perf_session__has_comm_exec(session); 130 131 machines__set_comm_exec(&session->machines, comm_exec); 132 } 133 134 static int ordered_events__deliver_event(struct ordered_events *oe, 135 struct ordered_event *event) 136 { 137 struct perf_session *session = container_of(oe, struct perf_session, 138 ordered_events); 139 int ret = perf_session__deliver_event(session, event->event, 140 session->tool, event->file_offset, 141 event->file_path); 142 143 if (ret) { 144 pr_err("%#" PRIx64 " [%#x]: ordered event processing failed (%d) for event of type: %s (%d)\n", 145 event->file_offset, event->event->header.size, ret, 146 perf_event__name(event->event->header.type), 147 event->event->header.type); 148 } 149 return ret; 150 } 151 152 struct perf_session *__perf_session__new(struct perf_data *data, 153 struct perf_tool *tool, 154 bool trace_event_repipe, 155 struct perf_env *host_env) 156 { 157 int ret = -ENOMEM; 158 struct perf_session *session = zalloc(sizeof(*session)); 159 160 if (!session) 161 goto out; 162 163 session->trace_event_repipe = trace_event_repipe; 164 session->tool = tool; 165 session->decomp_data.zstd_decomp = &session->zstd_data; 166 session->active_decomp = &session->decomp_data; 167 INIT_LIST_HEAD(&session->auxtrace_index); 168 perf_env__init(&session->header.env); 169 if (machines__init(&session->machines, session)) 170 goto out_delete; 171 172 ordered_events__init(&session->ordered_events, 173 ordered_events__deliver_event, NULL); 174 if (data) { 175 ret = perf_data__open(data); 176 if (ret < 0) 177 goto out_delete; 178 179 session->data = data; 180 181 if (perf_data__is_read(data)) { 182 ret = perf_session__open(session); 183 if (ret < 0) 184 goto out_delete; 185 186 /* 187 * set session attributes that are present in perf.data 188 * but not in pipe-mode. 189 */ 190 if (!data->is_pipe) { 191 perf_session__set_id_hdr_size(session); 192 perf_session__set_comm_exec(session); 193 } 194 195 evlist__init_trace_event_sample_raw(session->evlist, &session->header.env); 196 197 /* Open the directory data. */ 198 if (data->is_dir) { 199 ret = perf_data__open_dir(data); 200 if (ret) 201 goto out_delete; 202 } 203 204 if (!symbol_conf.kallsyms_name && 205 !symbol_conf.vmlinux_name) 206 symbol_conf.kallsyms_name = perf_data__kallsyms_name(data); 207 } 208 } else { 209 assert(host_env != NULL); 210 session->machines.host.env = host_env; 211 } 212 if (session->evlist) 213 evlist__set_session(session->evlist, session); 214 215 session->machines.host.single_address_space = 216 perf_env__single_address_space(session->machines.host.env); 217 218 if (!data || perf_data__is_write(data)) { 219 /* 220 * In O_RDONLY mode this will be performed when reading the 221 * kernel MMAP event, in perf_event__process_mmap(). 222 */ 223 if (perf_session__create_kernel_maps(session) < 0) 224 pr_warning("Cannot read kernel map\n"); 225 } 226 227 /* 228 * In pipe-mode, evlist is empty until PERF_RECORD_HEADER_ATTR is 229 * processed, so evlist__sample_id_all is not meaningful here. 230 */ 231 if ((!data || !data->is_pipe) && tool && tool->ordering_requires_timestamps && 232 tool->ordered_events && !evlist__sample_id_all(session->evlist)) { 233 dump_printf("WARNING: No sample_id_all support, falling back to unordered processing\n"); 234 tool->ordered_events = false; 235 } 236 237 return session; 238 239 out_delete: 240 perf_session__delete(session); 241 out: 242 return ERR_PTR(ret); 243 } 244 245 static void perf_decomp__release_events(struct decomp *next) 246 { 247 struct decomp *decomp; 248 size_t mmap_len; 249 250 do { 251 decomp = next; 252 if (decomp == NULL) 253 break; 254 next = decomp->next; 255 mmap_len = decomp->mmap_len; 256 munmap(decomp, mmap_len); 257 } while (1); 258 } 259 260 void perf_session__delete(struct perf_session *session) 261 { 262 if (session == NULL) 263 return; 264 auxtrace__free(session); 265 auxtrace_index__free(&session->auxtrace_index); 266 debuginfo_cache__delete(); 267 perf_session__destroy_kernel_maps(session); 268 perf_decomp__release_events(session->decomp_data.decomp); 269 perf_env__exit(&session->header.env); 270 machines__exit(&session->machines); 271 if (session->data) { 272 if (perf_data__is_read(session->data)) 273 evlist__put(session->evlist); 274 perf_data__close(session->data); 275 } 276 #ifdef HAVE_LIBTRACEEVENT 277 trace_event__cleanup(&session->tevent); 278 #endif 279 free(session); 280 } 281 282 static void swap_sample_id_all(union perf_event *event, void *data) 283 { 284 void *end = (void *) event + event->header.size; 285 int size; 286 287 if (data >= end) 288 return; 289 290 size = end - data; 291 if (size % sizeof(u64)) { 292 pr_warning("swap_sample_id_all: unaligned sample_id_all remainder (%d), skipping swap\n", size); 293 return; 294 } 295 if (size > 0) 296 mem_bswap_64(data, size); 297 } 298 299 static int perf_event__all64_swap(union perf_event *event, 300 bool sample_id_all __maybe_unused) 301 { 302 struct perf_event_header *hdr = &event->header; 303 size_t size = event->header.size - sizeof(*hdr); 304 305 /* mem_bswap_64 rounds up to 8-byte chunks — unaligned size overruns the buffer */ 306 if (size % sizeof(u64)) 307 return -1; 308 mem_bswap_64(hdr + 1, size); 309 return 0; 310 } 311 312 static int perf_event__comm_swap(union perf_event *event, bool sample_id_all) 313 { 314 event->comm.pid = bswap_32(event->comm.pid); 315 event->comm.tid = bswap_32(event->comm.tid); 316 317 if (sample_id_all) { 318 void *data = &event->comm.comm; 319 void *end = (void *)event + event->header.size; 320 size_t len = strnlen(data, end - data); 321 322 /* 323 * No NUL within the event boundary — can't locate where 324 * sample_id_all starts. Reject so the event is skipped 325 * rather than swapping garbage. 326 */ 327 if (len == (size_t)(end - data)) 328 return -1; 329 data += PERF_ALIGN(len + 1, sizeof(u64)); 330 swap_sample_id_all(event, data); 331 } 332 return 0; 333 } 334 335 static int perf_event__mmap_swap(union perf_event *event, 336 bool sample_id_all) 337 { 338 event->mmap.pid = bswap_32(event->mmap.pid); 339 event->mmap.tid = bswap_32(event->mmap.tid); 340 event->mmap.start = bswap_64(event->mmap.start); 341 event->mmap.len = bswap_64(event->mmap.len); 342 event->mmap.pgoff = bswap_64(event->mmap.pgoff); 343 344 if (sample_id_all) { 345 void *data = &event->mmap.filename; 346 void *end = (void *)event + event->header.size; 347 size_t len = strnlen(data, end - data); 348 349 /* See comment in perf_event__comm_swap() */ 350 if (len == (size_t)(end - data)) 351 return -1; 352 data += PERF_ALIGN(len + 1, sizeof(u64)); 353 swap_sample_id_all(event, data); 354 } 355 return 0; 356 } 357 358 static int perf_event__mmap2_swap(union perf_event *event, 359 bool sample_id_all) 360 { 361 event->mmap2.pid = bswap_32(event->mmap2.pid); 362 event->mmap2.tid = bswap_32(event->mmap2.tid); 363 event->mmap2.start = bswap_64(event->mmap2.start); 364 event->mmap2.len = bswap_64(event->mmap2.len); 365 event->mmap2.pgoff = bswap_64(event->mmap2.pgoff); 366 367 if (!(event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID)) { 368 event->mmap2.maj = bswap_32(event->mmap2.maj); 369 event->mmap2.min = bswap_32(event->mmap2.min); 370 event->mmap2.ino = bswap_64(event->mmap2.ino); 371 event->mmap2.ino_generation = bswap_64(event->mmap2.ino_generation); 372 } 373 374 if (sample_id_all) { 375 void *data = &event->mmap2.filename; 376 void *end = (void *)event + event->header.size; 377 size_t len = strnlen(data, end - data); 378 379 /* See comment in perf_event__comm_swap() */ 380 if (len == (size_t)(end - data)) 381 return -1; 382 data += PERF_ALIGN(len + 1, sizeof(u64)); 383 swap_sample_id_all(event, data); 384 } 385 return 0; 386 } 387 388 static int perf_event__task_swap(union perf_event *event, bool sample_id_all) 389 { 390 event->fork.pid = bswap_32(event->fork.pid); 391 event->fork.tid = bswap_32(event->fork.tid); 392 event->fork.ppid = bswap_32(event->fork.ppid); 393 event->fork.ptid = bswap_32(event->fork.ptid); 394 event->fork.time = bswap_64(event->fork.time); 395 396 if (sample_id_all) 397 swap_sample_id_all(event, &event->fork + 1); 398 return 0; 399 } 400 401 static int perf_event__read_swap(union perf_event *event, 402 bool sample_id_all __maybe_unused) 403 { 404 size_t tail; 405 406 event->read.pid = bswap_32(event->read.pid); 407 event->read.tid = bswap_32(event->read.tid); 408 /* 409 * Everything after pid/tid is u64: the read values (variable 410 * set determined by attr.read_format, which we don't have 411 * here) optionally followed by sample_id_all fields. 412 * Since all are u64, swap the entire remaining tail at once. 413 */ 414 tail = event->header.size - offsetof(struct perf_record_read, value); 415 /* mem_bswap_64 rounds up to 8-byte chunks — unaligned tail overruns the buffer */ 416 if (tail % sizeof(u64)) 417 return -1; 418 mem_bswap_64(&event->read.value, tail); 419 return 0; 420 } 421 422 static int perf_event__aux_swap(union perf_event *event, bool sample_id_all) 423 { 424 event->aux.aux_offset = bswap_64(event->aux.aux_offset); 425 event->aux.aux_size = bswap_64(event->aux.aux_size); 426 event->aux.flags = bswap_64(event->aux.flags); 427 428 if (sample_id_all) 429 swap_sample_id_all(event, &event->aux + 1); 430 return 0; 431 } 432 433 static int perf_event__itrace_start_swap(union perf_event *event, 434 bool sample_id_all) 435 { 436 event->itrace_start.pid = bswap_32(event->itrace_start.pid); 437 event->itrace_start.tid = bswap_32(event->itrace_start.tid); 438 439 if (sample_id_all) 440 swap_sample_id_all(event, &event->itrace_start + 1); 441 return 0; 442 } 443 444 static int perf_event__switch_swap(union perf_event *event, bool sample_id_all) 445 { 446 if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) { 447 event->context_switch.next_prev_pid = 448 bswap_32(event->context_switch.next_prev_pid); 449 event->context_switch.next_prev_tid = 450 bswap_32(event->context_switch.next_prev_tid); 451 } 452 453 if (sample_id_all) { 454 /* 455 * PERF_RECORD_SWITCH has no fields beyond the header; 456 * SWITCH_CPU_WIDE adds pid/tid. Use the right offset 457 * so sample_id starts at the correct position. 458 */ 459 if (event->header.type == PERF_RECORD_SWITCH) 460 swap_sample_id_all(event, (void *)event + sizeof(event->header)); 461 else 462 swap_sample_id_all(event, &event->context_switch + 1); 463 } 464 return 0; 465 } 466 467 static int perf_event__text_poke_swap(union perf_event *event, bool sample_id_all) 468 { 469 event->text_poke.addr = bswap_64(event->text_poke.addr); 470 event->text_poke.old_len = bswap_16(event->text_poke.old_len); 471 event->text_poke.new_len = bswap_16(event->text_poke.new_len); 472 473 if (sample_id_all) { 474 void *data = &event->text_poke.old_len; 475 void *end = (void *)event + event->header.size; 476 size_t len = sizeof(event->text_poke.old_len) + 477 sizeof(event->text_poke.new_len) + 478 event->text_poke.old_len + 479 event->text_poke.new_len; 480 481 /* old_len + new_len exceeds event — can't find sample_id_all */ 482 if (data + len > end) 483 return -1; 484 data += PERF_ALIGN(len, sizeof(u64)); 485 swap_sample_id_all(event, data); 486 } 487 return 0; 488 } 489 490 static int perf_event__throttle_swap(union perf_event *event, 491 bool sample_id_all) 492 { 493 event->throttle.time = bswap_64(event->throttle.time); 494 event->throttle.id = bswap_64(event->throttle.id); 495 event->throttle.stream_id = bswap_64(event->throttle.stream_id); 496 497 if (sample_id_all) 498 swap_sample_id_all(event, &event->throttle + 1); 499 return 0; 500 } 501 502 static int perf_event__namespaces_swap(union perf_event *event, 503 bool sample_id_all) 504 { 505 u64 i, nr, max_nr; 506 507 event->namespaces.pid = bswap_32(event->namespaces.pid); 508 event->namespaces.tid = bswap_32(event->namespaces.tid); 509 event->namespaces.nr_namespaces = bswap_64(event->namespaces.nr_namespaces); 510 511 nr = event->namespaces.nr_namespaces; 512 /* 513 * Cannot underflow: perf_event__min_size[] guarantees header.size >= sizeof. 514 * When sample_id_all is present max_nr slightly overestimates the 515 * array space because header.size includes the trailing sample_id. 516 * Harmless: both the per-element bswap_64 loop and swap_sample_id_all() 517 * perform the same u64 byte swap, so the result is correct regardless 518 * of where the boundary between array and sample_id falls. 519 */ 520 max_nr = (event->header.size - sizeof(event->namespaces)) / 521 sizeof(event->namespaces.link_info[0]); 522 /* 523 * Safe to clamp: each namespace entry is indexed by type; 524 * missing entries just won't be resolved. 525 */ 526 if (nr > max_nr) { 527 pr_warning("WARNING: PERF_RECORD_NAMESPACES: nr_namespaces %" PRIu64 " exceeds payload (max %" PRIu64 "), clamping\n", 528 nr, max_nr); 529 nr = max_nr; 530 event->namespaces.nr_namespaces = nr; 531 } 532 533 for (i = 0; i < nr; i++) { 534 struct perf_ns_link_info *ns = &event->namespaces.link_info[i]; 535 536 ns->dev = bswap_64(ns->dev); 537 ns->ino = bswap_64(ns->ino); 538 } 539 540 if (sample_id_all) 541 swap_sample_id_all(event, &event->namespaces.link_info[i]); 542 return 0; 543 } 544 545 static int perf_event__cgroup_swap(union perf_event *event, bool sample_id_all) 546 { 547 event->cgroup.id = bswap_64(event->cgroup.id); 548 549 if (sample_id_all) { 550 void *data = &event->cgroup.path; 551 void *end = (void *)event + event->header.size; 552 size_t len = strnlen(data, end - data); 553 554 /* See comment in perf_event__comm_swap() */ 555 if (len == (size_t)(end - data)) 556 return -1; 557 data += PERF_ALIGN(len + 1, sizeof(u64)); 558 swap_sample_id_all(event, data); 559 } 560 return 0; 561 } 562 563 static u8 revbyte(u8 b) 564 { 565 int rev = (b >> 4) | ((b & 0xf) << 4); 566 rev = ((rev & 0xcc) >> 2) | ((rev & 0x33) << 2); 567 rev = ((rev & 0xaa) >> 1) | ((rev & 0x55) << 1); 568 return (u8) rev; 569 } 570 571 /* 572 * XXX this is hack in attempt to carry flags bitfield 573 * through endian village. ABI says: 574 * 575 * Bit-fields are allocated from right to left (least to most significant) 576 * on little-endian implementations and from left to right (most to least 577 * significant) on big-endian implementations. 578 * 579 * The above seems to be byte specific, so we need to reverse each 580 * byte of the bitfield. 'Internet' also says this might be implementation 581 * specific and we probably need proper fix and carry perf_event_attr 582 * bitfield flags in separate data file FEAT_ section. Thought this seems 583 * to work for now. 584 */ 585 static void swap_bitfield(u8 *p, unsigned len) 586 { 587 unsigned i; 588 589 for (i = 0; i < len; i++) { 590 *p = revbyte(*p); 591 p++; 592 } 593 } 594 595 /* exported for swapping attributes in file header */ 596 void perf_event__attr_swap(struct perf_event_attr *attr) 597 { 598 attr->type = bswap_32(attr->type); 599 attr->size = bswap_32(attr->size); 600 601 /* 602 * ABI0: size == 0 means the producer didn't set it. 603 * Assume PERF_ATTR_SIZE_VER0 so bswap_safe() below 604 * correctly swaps the VER0 fields instead of skipping 605 * everything. Same convention as read_attr(). 606 */ 607 if (!attr->size) 608 attr->size = PERF_ATTR_SIZE_VER0; 609 610 /* Verify the full field extent fits, not just its start offset */ 611 #define bswap_safe(f, n) \ 612 (attr->size >= (offsetof(struct perf_event_attr, f) + \ 613 sizeof(attr->f) * ((n) + 1))) 614 #define bswap_field(f, sz) \ 615 do { \ 616 if (bswap_safe(f, 0)) \ 617 attr->f = bswap_##sz(attr->f); \ 618 } while(0) 619 #define bswap_field_16(f) bswap_field(f, 16) 620 #define bswap_field_32(f) bswap_field(f, 32) 621 #define bswap_field_64(f) bswap_field(f, 64) 622 623 bswap_field_64(config); 624 bswap_field_64(sample_period); 625 bswap_field_64(sample_type); 626 bswap_field_64(read_format); 627 bswap_field_32(wakeup_events); 628 bswap_field_32(bp_type); 629 bswap_field_64(bp_addr); 630 bswap_field_64(bp_len); 631 bswap_field_64(branch_sample_type); 632 bswap_field_64(sample_regs_user); 633 bswap_field_32(sample_stack_user); 634 bswap_field_32(aux_watermark); 635 bswap_field_16(sample_max_stack); 636 bswap_field_32(aux_sample_size); 637 /* 638 * aux_action aliases bitfields (e.g. aux_start_paused) in a union. 639 * Bitfields and plain u32 fields follow different endian rules, so 640 * both views cannot be swapped correctly at the same time. 641 * Leave aux_action unswapped until the ABI is represented in a 642 * byte-order-safe form. 643 */ 644 bswap_field_64(sig_data); 645 bswap_field_64(config3); 646 bswap_field_64(config4); 647 bswap_field_16(sample_simd_regs_enabled); 648 bswap_field_16(sample_simd_pred_reg_qwords); 649 bswap_field_16(sample_simd_vec_reg_qwords); 650 bswap_field_32(sample_simd_pred_reg_intr); 651 bswap_field_32(sample_simd_pred_reg_user); 652 bswap_field_64(sample_simd_vec_reg_intr); 653 bswap_field_64(sample_simd_vec_reg_user); 654 655 /* 656 * After read_format are bitfields. Check read_format because 657 * we are unable to use offsetof on bitfield. 658 */ 659 if (bswap_safe(read_format, 1)) 660 swap_bitfield((u8 *) (&attr->read_format + 1), 661 sizeof(u64)); 662 #undef bswap_field_64 663 #undef bswap_field_32 664 #undef bswap_field 665 #undef bswap_safe 666 } 667 668 static int perf_event__hdr_attr_swap(union perf_event *event, 669 bool sample_id_all __maybe_unused) 670 { 671 u32 attr_size, payload_size; 672 size_t size; 673 674 /* 675 * Validate attr.size (still foreign-endian) before calling 676 * perf_event__attr_swap(), which uses it via bswap_safe() 677 * to decide which fields to swap. A crafted attr.size 678 * larger than the event payload would swap past the event 679 * boundary and corrupt adjacent memory. 680 * 681 * header.size alignment is already validated by 682 * perf_session__process_event(). The min_size table 683 * guarantees header.size >= sizeof(header) + 684 * PERF_ATTR_SIZE_VER0, so attr.size is safe to access. 685 */ 686 attr_size = bswap_32(event->attr.attr.size); 687 /* 688 * ABI0: size field not set. This only happens in pipe/inject 689 * mode where HEADER_ATTR events carry their own attr. For 690 * regular perf.data files, read_attr() uses f_header.attr_size 691 * from the file header instead. Assume PERF_ATTR_SIZE_VER0. 692 */ 693 if (!attr_size) 694 attr_size = PERF_ATTR_SIZE_VER0; 695 payload_size = event->header.size - sizeof(event->header); 696 697 if (attr_size < PERF_ATTR_SIZE_VER0 || attr_size % sizeof(u64) || 698 attr_size > payload_size) { 699 pr_err("PERF_RECORD_HEADER_ATTR: invalid attr.size %u (min: %d, max: %u, 8-byte aligned)\n", 700 attr_size, PERF_ATTR_SIZE_VER0, payload_size); 701 return -1; 702 } 703 704 perf_event__attr_swap(&event->attr.attr); 705 706 size = event->header.size; 707 size -= perf_record_header_attr_id(event) - (void *)event; 708 mem_bswap_64(perf_record_header_attr_id(event), size); 709 return 0; 710 } 711 712 static int perf_event__build_id_swap(union perf_event *event, 713 bool sample_id_all) 714 { 715 event->build_id.pid = bswap_32(event->build_id.pid); 716 717 if (sample_id_all) { 718 void *data = &event->build_id.filename; 719 void *end = (void *)event + event->header.size; 720 size_t len = strnlen(data, end - data); 721 722 /* See comment in perf_event__comm_swap() */ 723 if (len == (size_t)(end - data)) 724 return -1; 725 data += PERF_ALIGN(len + 1, sizeof(u64)); 726 swap_sample_id_all(event, data); 727 } 728 return 0; 729 } 730 731 static int perf_event__event_update_swap(union perf_event *event, 732 bool sample_id_all __maybe_unused) 733 { 734 struct perf_record_event_update *ev = &event->event_update; 735 736 ev->type = bswap_64(ev->type); 737 ev->id = bswap_64(ev->id); 738 739 /* 740 * Swap variant-specific fields so the processing path 741 * sees native byte order. 742 */ 743 if (ev->type == PERF_EVENT_UPDATE__SCALE) { 744 if (event->header.size < offsetof(struct perf_record_event_update, scale) + 745 sizeof(ev->scale)) 746 return -1; 747 mem_bswap_64(&ev->scale.scale, sizeof(ev->scale.scale)); 748 } else if (ev->type == PERF_EVENT_UPDATE__CPUS) { 749 u32 cpus_payload; 750 struct perf_record_cpu_map_data *data = &ev->cpus.cpus; 751 752 /* CPUS fields start at the same offset as scale (union) */ 753 if (event->header.size < offsetof(struct perf_record_event_update, cpus) + 754 sizeof(__u16) + sizeof(struct perf_record_range_cpu_map)) 755 return -1; 756 cpus_payload = event->header.size - offsetof(struct perf_record_event_update, cpus); 757 data->type = bswap_16(data->type); 758 /* 759 * Full swap including array elements — same logic as 760 * perf_event__cpu_map_swap() but scoped to the 761 * embedded cpu_map_data within EVENT_UPDATE. 762 */ 763 switch (data->type) { 764 case PERF_CPU_MAP__CPUS: { 765 u16 nr, max_nr; 766 767 data->cpus_data.nr = bswap_16(data->cpus_data.nr); 768 nr = data->cpus_data.nr; 769 max_nr = (cpus_payload - offsetof(struct perf_record_cpu_map_data, 770 cpus_data.cpu)) / 771 sizeof(data->cpus_data.cpu[0]); 772 if (nr > max_nr) { 773 nr = max_nr; 774 data->cpus_data.nr = nr; 775 } 776 for (unsigned int i = 0; i < nr; i++) 777 data->cpus_data.cpu[i] = bswap_16(data->cpus_data.cpu[i]); 778 break; 779 } 780 case PERF_CPU_MAP__MASK: 781 data->mask32_data.long_size = bswap_16(data->mask32_data.long_size); 782 switch (data->mask32_data.long_size) { 783 case 4: { 784 u16 nr, max_nr; 785 786 data->mask32_data.nr = bswap_16(data->mask32_data.nr); 787 nr = data->mask32_data.nr; 788 max_nr = (cpus_payload - offsetof(struct perf_record_cpu_map_data, 789 mask32_data.mask)) / 790 sizeof(data->mask32_data.mask[0]); 791 if (nr > max_nr) { 792 nr = max_nr; 793 data->mask32_data.nr = nr; 794 } 795 for (unsigned int i = 0; i < nr; i++) 796 data->mask32_data.mask[i] = bswap_32(data->mask32_data.mask[i]); 797 break; 798 } 799 case 8: { 800 u16 nr, max_nr; 801 802 data->mask64_data.nr = bswap_16(data->mask64_data.nr); 803 nr = data->mask64_data.nr; 804 if (cpus_payload < offsetof(struct perf_record_cpu_map_data, mask64_data.mask)) { 805 data->mask64_data.nr = 0; 806 break; 807 } 808 max_nr = (cpus_payload - offsetof(struct perf_record_cpu_map_data, 809 mask64_data.mask)) / 810 sizeof(data->mask64_data.mask[0]); 811 if (nr > max_nr) { 812 nr = max_nr; 813 data->mask64_data.nr = nr; 814 } 815 for (unsigned int i = 0; i < nr; i++) 816 data->mask64_data.mask[i] = bswap_64(data->mask64_data.mask[i]); 817 break; 818 } 819 default: 820 break; 821 } 822 break; 823 case PERF_CPU_MAP__RANGE_CPUS: 824 data->range_cpu_data.start_cpu = bswap_16(data->range_cpu_data.start_cpu); 825 data->range_cpu_data.end_cpu = bswap_16(data->range_cpu_data.end_cpu); 826 break; 827 default: 828 break; 829 } 830 } 831 return 0; 832 } 833 834 static int perf_event__event_type_swap(union perf_event *event, 835 bool sample_id_all __maybe_unused) 836 { 837 event->event_type.event_type.event_id = 838 bswap_64(event->event_type.event_type.event_id); 839 return 0; 840 } 841 842 static int perf_event__tracing_data_swap(union perf_event *event, 843 bool sample_id_all __maybe_unused) 844 { 845 event->tracing_data.size = bswap_32(event->tracing_data.size); 846 return 0; 847 } 848 849 static int perf_event__auxtrace_info_swap(union perf_event *event, 850 bool sample_id_all __maybe_unused) 851 { 852 size_t size; 853 854 event->auxtrace_info.type = bswap_32(event->auxtrace_info.type); 855 856 size = event->header.size; 857 size -= (void *)&event->auxtrace_info.priv - (void *)event; 858 mem_bswap_64(event->auxtrace_info.priv, size); 859 return 0; 860 } 861 862 static int perf_event__auxtrace_swap(union perf_event *event, 863 bool sample_id_all __maybe_unused) 864 { 865 event->auxtrace.size = bswap_64(event->auxtrace.size); 866 event->auxtrace.offset = bswap_64(event->auxtrace.offset); 867 event->auxtrace.reference = bswap_64(event->auxtrace.reference); 868 event->auxtrace.idx = bswap_32(event->auxtrace.idx); 869 event->auxtrace.tid = bswap_32(event->auxtrace.tid); 870 event->auxtrace.cpu = bswap_32(event->auxtrace.cpu); 871 return 0; 872 } 873 874 static int perf_event__auxtrace_error_swap(union perf_event *event, 875 bool sample_id_all __maybe_unused) 876 { 877 event->auxtrace_error.type = bswap_32(event->auxtrace_error.type); 878 event->auxtrace_error.code = bswap_32(event->auxtrace_error.code); 879 event->auxtrace_error.cpu = bswap_32(event->auxtrace_error.cpu); 880 event->auxtrace_error.pid = bswap_32(event->auxtrace_error.pid); 881 event->auxtrace_error.tid = bswap_32(event->auxtrace_error.tid); 882 event->auxtrace_error.fmt = bswap_32(event->auxtrace_error.fmt); 883 event->auxtrace_error.ip = bswap_64(event->auxtrace_error.ip); 884 if (event->auxtrace_error.fmt) 885 event->auxtrace_error.time = bswap_64(event->auxtrace_error.time); 886 if (event->auxtrace_error.fmt >= 2) { 887 /* 888 * fmt >= 2 adds machine_pid and vcpu after msg[64]. 889 * Older files may have fmt >= 2 but an event size 890 * that doesn't include these fields — downgrade to 891 * avoid swapping out of bounds. 892 */ 893 if (event->header.size < offsetof(typeof(event->auxtrace_error), vcpu) + 894 sizeof(event->auxtrace_error.vcpu)) { 895 pr_warning("WARNING: PERF_RECORD_AUXTRACE_ERROR: fmt %u but event too small for machine_pid/vcpu (%u bytes), downgrading fmt\n", 896 event->auxtrace_error.fmt, 897 event->header.size); 898 event->auxtrace_error.fmt = 1; 899 } else { 900 event->auxtrace_error.machine_pid = bswap_32(event->auxtrace_error.machine_pid); 901 event->auxtrace_error.vcpu = bswap_32(event->auxtrace_error.vcpu); 902 } 903 } 904 return 0; 905 } 906 907 static int perf_event__thread_map_swap(union perf_event *event, 908 bool sample_id_all __maybe_unused) 909 { 910 unsigned int i; 911 u64 nr; 912 913 event->thread_map.nr = bswap_64(event->thread_map.nr); 914 915 /* 916 * Reject rather than clamp: unlike namespaces (indexed by type) 917 * or stat_config (self-describing tags), a truncated thread map 918 * is structurally broken — downstream would get a wrong map. 919 */ 920 /* Cannot underflow: perf_event__min_size[] guarantees header.size >= sizeof */ 921 nr = event->thread_map.nr; 922 if (nr > (event->header.size - sizeof(event->thread_map)) / 923 sizeof(event->thread_map.entries[0])) 924 return -1; 925 926 for (i = 0; i < nr; i++) 927 event->thread_map.entries[i].pid = bswap_64(event->thread_map.entries[i].pid); 928 return 0; 929 } 930 931 static int perf_event__cpu_map_swap(union perf_event *event, 932 bool sample_id_all __maybe_unused) 933 { 934 struct perf_record_cpu_map_data *data = &event->cpu_map.data; 935 u32 payload = event->header.size - sizeof(event->header); 936 937 data->type = bswap_16(data->type); 938 939 /* 940 * Safe to clamp: a shorter CPU map just means some CPUs 941 * are absent; tools process the CPUs that are present. 942 */ 943 switch (data->type) { 944 case PERF_CPU_MAP__CPUS: { 945 u16 nr, max_nr; 946 947 data->cpus_data.nr = bswap_16(data->cpus_data.nr); 948 nr = data->cpus_data.nr; 949 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 950 cpus_data.cpu)) / 951 sizeof(data->cpus_data.cpu[0]); 952 if (nr > max_nr) { 953 pr_warning("WARNING: PERF_RECORD_CPU_MAP: nr %u exceeds payload (max %u), clamping\n", 954 nr, max_nr); 955 nr = max_nr; 956 data->cpus_data.nr = nr; 957 } 958 for (unsigned int i = 0; i < nr; i++) 959 data->cpus_data.cpu[i] = bswap_16(data->cpus_data.cpu[i]); 960 break; 961 } 962 case PERF_CPU_MAP__MASK: 963 data->mask32_data.long_size = bswap_16(data->mask32_data.long_size); 964 965 switch (data->mask32_data.long_size) { 966 case 4: { 967 u16 nr, max_nr; 968 969 data->mask32_data.nr = bswap_16(data->mask32_data.nr); 970 nr = data->mask32_data.nr; 971 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 972 mask32_data.mask)) / 973 sizeof(data->mask32_data.mask[0]); 974 if (nr > max_nr) { 975 pr_warning("WARNING: PERF_RECORD_CPU_MAP mask32: nr %u exceeds payload (max %u), clamping\n", 976 nr, max_nr); 977 nr = max_nr; 978 data->mask32_data.nr = nr; 979 } 980 for (unsigned int i = 0; i < nr; i++) 981 data->mask32_data.mask[i] = bswap_32(data->mask32_data.mask[i]); 982 break; 983 } 984 case 8: { 985 u16 nr, max_nr; 986 987 data->mask64_data.nr = bswap_16(data->mask64_data.nr); 988 nr = data->mask64_data.nr; 989 if (payload < offsetof(struct perf_record_cpu_map_data, mask64_data.mask)) { 990 data->mask64_data.nr = 0; 991 break; 992 } 993 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 994 mask64_data.mask)) / 995 sizeof(data->mask64_data.mask[0]); 996 if (nr > max_nr) { 997 pr_warning("WARNING: PERF_RECORD_CPU_MAP mask64: nr %u exceeds payload (max %u), clamping\n", 998 nr, max_nr); 999 nr = max_nr; 1000 data->mask64_data.nr = nr; 1001 } 1002 for (unsigned int i = 0; i < nr; i++) 1003 data->mask64_data.mask[i] = bswap_64(data->mask64_data.mask[i]); 1004 break; 1005 } 1006 default: 1007 pr_err("cpu_map swap: unsupported long size %u\n", 1008 data->mask32_data.long_size); 1009 } 1010 break; 1011 case PERF_CPU_MAP__RANGE_CPUS: 1012 data->range_cpu_data.start_cpu = bswap_16(data->range_cpu_data.start_cpu); 1013 data->range_cpu_data.end_cpu = bswap_16(data->range_cpu_data.end_cpu); 1014 break; 1015 default: 1016 break; 1017 } 1018 return 0; 1019 } 1020 1021 static int perf_event__stat_config_swap(union perf_event *event, 1022 bool sample_id_all __maybe_unused) 1023 { 1024 u64 nr, max_nr, size; 1025 1026 nr = bswap_64(event->stat_config.nr); 1027 /* Cannot underflow: perf_event__min_size[] guarantees header.size >= sizeof */ 1028 max_nr = (event->header.size - sizeof(event->stat_config)) / 1029 sizeof(event->stat_config.data[0]); 1030 /* 1031 * Safe to clamp: each config entry is self-describing 1032 * via its tag; missing entries keep their defaults. 1033 */ 1034 if (nr > max_nr) { 1035 pr_warning("WARNING: PERF_RECORD_STAT_CONFIG: nr %" PRIu64 " exceeds payload (max %" PRIu64 "), clamping\n", 1036 nr, max_nr); 1037 nr = max_nr; 1038 } 1039 size = nr * sizeof(event->stat_config.data[0]); 1040 /* The swap starts at &nr, so add its size to cover the full range */ 1041 size += sizeof(event->stat_config.nr); 1042 mem_bswap_64(&event->stat_config.nr, size); 1043 /* Persist the clamped value in native byte order */ 1044 event->stat_config.nr = nr; 1045 return 0; 1046 } 1047 1048 static int perf_event__stat_swap(union perf_event *event, 1049 bool sample_id_all __maybe_unused) 1050 { 1051 event->stat.id = bswap_64(event->stat.id); 1052 event->stat.thread = bswap_32(event->stat.thread); 1053 event->stat.cpu = bswap_32(event->stat.cpu); 1054 event->stat.val = bswap_64(event->stat.val); 1055 event->stat.ena = bswap_64(event->stat.ena); 1056 event->stat.run = bswap_64(event->stat.run); 1057 return 0; 1058 } 1059 1060 static int perf_event__stat_round_swap(union perf_event *event, 1061 bool sample_id_all __maybe_unused) 1062 { 1063 event->stat_round.type = bswap_64(event->stat_round.type); 1064 event->stat_round.time = bswap_64(event->stat_round.time); 1065 return 0; 1066 } 1067 1068 static int perf_event__time_conv_swap(union perf_event *event, 1069 bool sample_id_all __maybe_unused) 1070 { 1071 event->time_conv.time_shift = bswap_64(event->time_conv.time_shift); 1072 event->time_conv.time_mult = bswap_64(event->time_conv.time_mult); 1073 event->time_conv.time_zero = bswap_64(event->time_conv.time_zero); 1074 1075 if (event_contains(event->time_conv, time_cycles)) 1076 event->time_conv.time_cycles = bswap_64(event->time_conv.time_cycles); 1077 if (event_contains(event->time_conv, time_mask)) 1078 event->time_conv.time_mask = bswap_64(event->time_conv.time_mask); 1079 return 0; 1080 } 1081 1082 static int perf_event__compressed2_swap(union perf_event *event, 1083 bool sample_id_all __maybe_unused) 1084 { 1085 /* Only data_size needs swapping — compressed payload is a raw byte stream */ 1086 event->pack2.data_size = bswap_64(event->pack2.data_size); 1087 return 0; 1088 } 1089 1090 static int perf_event__bpf_metadata_swap(union perf_event *event, 1091 bool sample_id_all __maybe_unused) 1092 { 1093 u64 i, nr, max_nr; 1094 1095 /* Fixed header must fit before accessing nr_entries or prog_name */ 1096 if (event->header.size < sizeof(event->bpf_metadata)) 1097 return -1; 1098 1099 event->bpf_metadata.nr_entries = bswap_64(event->bpf_metadata.nr_entries); 1100 1101 /* 1102 * Ensure NUL-termination on the cross-endian path where the 1103 * mapping is writable (MAP_PRIVATE + PROT_WRITE). Fixing 1104 * the string in place is preferred over rejecting because it 1105 * preserves the event for downstream processing — only the 1106 * last byte is lost. 1107 * 1108 * The native-endian path (MAP_SHARED + PROT_READ) cannot 1109 * write, so it validates and skips unterminated events in 1110 * perf_session__process_user_event() instead. The two 1111 * strategies produce different outcomes for the same 1112 * malformed input (fix vs skip), which is inherent in the 1113 * writable-vs-read-only mapping model. 1114 */ 1115 event->bpf_metadata.prog_name[BPF_PROG_NAME_LEN - 1] = '\0'; 1116 1117 nr = event->bpf_metadata.nr_entries; 1118 max_nr = (event->header.size - sizeof(event->bpf_metadata)) / 1119 sizeof(event->bpf_metadata.entries[0]); 1120 if (nr > max_nr) { 1121 /* Persist clamped value so the native path processes entries, not skips */ 1122 nr = max_nr; 1123 event->bpf_metadata.nr_entries = nr; 1124 } 1125 1126 for (i = 0; i < nr; i++) { 1127 event->bpf_metadata.entries[i].key[BPF_METADATA_KEY_LEN - 1] = '\0'; 1128 event->bpf_metadata.entries[i].value[BPF_METADATA_VALUE_LEN - 1] = '\0'; 1129 } 1130 return 0; 1131 } 1132 static int 1133 perf_event__schedstat_cpu_swap(union perf_event *event __maybe_unused, 1134 bool sample_id_all __maybe_unused) 1135 { 1136 /* FIXME */ 1137 return 0; 1138 } 1139 1140 static int 1141 perf_event__schedstat_domain_swap(union perf_event *event __maybe_unused, 1142 bool sample_id_all __maybe_unused) 1143 { 1144 /* FIXME */ 1145 return 0; 1146 } 1147 1148 static int perf_event__ksymbol_swap(union perf_event *event, 1149 bool sample_id_all) 1150 { 1151 event->ksymbol.addr = bswap_64(event->ksymbol.addr); 1152 event->ksymbol.len = bswap_32(event->ksymbol.len); 1153 event->ksymbol.ksym_type = bswap_16(event->ksymbol.ksym_type); 1154 event->ksymbol.flags = bswap_16(event->ksymbol.flags); 1155 1156 if (sample_id_all) { 1157 void *data = &event->ksymbol.name; 1158 void *end = (void *)event + event->header.size; 1159 size_t len = strnlen(data, end - data); 1160 1161 /* See comment in perf_event__comm_swap() */ 1162 if (len == (size_t)(end - data)) 1163 return -1; 1164 data += PERF_ALIGN(len + 1, sizeof(u64)); 1165 swap_sample_id_all(event, data); 1166 } 1167 return 0; 1168 } 1169 1170 static int perf_event__bpf_event_swap(union perf_event *event, 1171 bool sample_id_all) 1172 { 1173 event->bpf.type = bswap_16(event->bpf.type); 1174 event->bpf.flags = bswap_16(event->bpf.flags); 1175 event->bpf.id = bswap_32(event->bpf.id); 1176 1177 if (sample_id_all) 1178 swap_sample_id_all(event, &event->bpf + 1); 1179 return 0; 1180 } 1181 1182 static int perf_event__header_feature_swap(union perf_event *event, 1183 bool sample_id_all __maybe_unused) 1184 { 1185 event->feat.feat_id = bswap_64(event->feat.feat_id); 1186 return 0; 1187 } 1188 1189 typedef int (*perf_event__swap_op)(union perf_event *event, 1190 bool sample_id_all); 1191 1192 static perf_event__swap_op perf_event__swap_ops[] = { 1193 [PERF_RECORD_MMAP] = perf_event__mmap_swap, 1194 [PERF_RECORD_MMAP2] = perf_event__mmap2_swap, 1195 [PERF_RECORD_COMM] = perf_event__comm_swap, 1196 [PERF_RECORD_FORK] = perf_event__task_swap, 1197 [PERF_RECORD_EXIT] = perf_event__task_swap, 1198 [PERF_RECORD_LOST] = perf_event__all64_swap, 1199 [PERF_RECORD_READ] = perf_event__read_swap, 1200 [PERF_RECORD_THROTTLE] = perf_event__throttle_swap, 1201 [PERF_RECORD_UNTHROTTLE] = perf_event__throttle_swap, 1202 [PERF_RECORD_SAMPLE] = perf_event__all64_swap, 1203 [PERF_RECORD_AUX] = perf_event__aux_swap, 1204 [PERF_RECORD_ITRACE_START] = perf_event__itrace_start_swap, 1205 [PERF_RECORD_LOST_SAMPLES] = perf_event__all64_swap, 1206 [PERF_RECORD_SWITCH] = perf_event__switch_swap, 1207 [PERF_RECORD_SWITCH_CPU_WIDE] = perf_event__switch_swap, 1208 [PERF_RECORD_NAMESPACES] = perf_event__namespaces_swap, 1209 [PERF_RECORD_CGROUP] = perf_event__cgroup_swap, 1210 [PERF_RECORD_KSYMBOL] = perf_event__ksymbol_swap, 1211 [PERF_RECORD_BPF_EVENT] = perf_event__bpf_event_swap, 1212 [PERF_RECORD_TEXT_POKE] = perf_event__text_poke_swap, 1213 [PERF_RECORD_AUX_OUTPUT_HW_ID] = perf_event__all64_swap, 1214 [PERF_RECORD_CALLCHAIN_DEFERRED] = perf_event__all64_swap, 1215 [PERF_RECORD_HEADER_ATTR] = perf_event__hdr_attr_swap, 1216 [PERF_RECORD_HEADER_EVENT_TYPE] = perf_event__event_type_swap, 1217 [PERF_RECORD_HEADER_TRACING_DATA] = perf_event__tracing_data_swap, 1218 [PERF_RECORD_HEADER_BUILD_ID] = perf_event__build_id_swap, 1219 [PERF_RECORD_HEADER_FEATURE] = perf_event__header_feature_swap, 1220 [PERF_RECORD_ID_INDEX] = perf_event__all64_swap, 1221 [PERF_RECORD_AUXTRACE_INFO] = perf_event__auxtrace_info_swap, 1222 [PERF_RECORD_AUXTRACE] = perf_event__auxtrace_swap, 1223 [PERF_RECORD_AUXTRACE_ERROR] = perf_event__auxtrace_error_swap, 1224 [PERF_RECORD_THREAD_MAP] = perf_event__thread_map_swap, 1225 [PERF_RECORD_CPU_MAP] = perf_event__cpu_map_swap, 1226 [PERF_RECORD_STAT_CONFIG] = perf_event__stat_config_swap, 1227 [PERF_RECORD_STAT] = perf_event__stat_swap, 1228 [PERF_RECORD_STAT_ROUND] = perf_event__stat_round_swap, 1229 [PERF_RECORD_EVENT_UPDATE] = perf_event__event_update_swap, 1230 [PERF_RECORD_TIME_CONV] = perf_event__time_conv_swap, 1231 [PERF_RECORD_COMPRESSED2] = perf_event__compressed2_swap, 1232 [PERF_RECORD_BPF_METADATA] = perf_event__bpf_metadata_swap, 1233 [PERF_RECORD_SCHEDSTAT_CPU] = perf_event__schedstat_cpu_swap, 1234 [PERF_RECORD_SCHEDSTAT_DOMAIN] = perf_event__schedstat_domain_swap, 1235 [PERF_RECORD_HEADER_MAX] = NULL, 1236 }; 1237 1238 /* 1239 * When perf record finishes a pass on every buffers, it records this pseudo 1240 * event. 1241 * We record the max timestamp t found in the pass n. 1242 * Assuming these timestamps are monotonic across cpus, we know that if 1243 * a buffer still has events with timestamps below t, they will be all 1244 * available and then read in the pass n + 1. 1245 * Hence when we start to read the pass n + 2, we can safely flush every 1246 * events with timestamps below t. 1247 * 1248 * ============ PASS n ================= 1249 * CPU 0 | CPU 1 1250 * | 1251 * cnt1 timestamps | cnt2 timestamps 1252 * 1 | 2 1253 * 2 | 3 1254 * - | 4 <--- max recorded 1255 * 1256 * ============ PASS n + 1 ============== 1257 * CPU 0 | CPU 1 1258 * | 1259 * cnt1 timestamps | cnt2 timestamps 1260 * 3 | 5 1261 * 4 | 6 1262 * 5 | 7 <---- max recorded 1263 * 1264 * Flush every events below timestamp 4 1265 * 1266 * ============ PASS n + 2 ============== 1267 * CPU 0 | CPU 1 1268 * | 1269 * cnt1 timestamps | cnt2 timestamps 1270 * 6 | 8 1271 * 7 | 9 1272 * - | 10 1273 * 1274 * Flush every events below timestamp 7 1275 * etc... 1276 */ 1277 int perf_event__process_finished_round(const struct perf_tool *tool __maybe_unused, 1278 union perf_event *event __maybe_unused, 1279 struct ordered_events *oe) 1280 { 1281 if (dump_trace) 1282 fprintf(stdout, "\n"); 1283 return ordered_events__flush(oe, OE_FLUSH__ROUND); 1284 } 1285 1286 int perf_session__queue_event(struct perf_session *s, union perf_event *event, 1287 u64 timestamp, u64 file_offset, const char *file_path) 1288 { 1289 return ordered_events__queue(&s->ordered_events, event, timestamp, file_offset, file_path); 1290 } 1291 1292 static void callchain__lbr_callstack_printf(struct perf_sample *sample) 1293 { 1294 struct ip_callchain *callchain = sample->callchain; 1295 struct branch_stack *lbr_stack = sample->branch_stack; 1296 struct branch_entry *entries = perf_sample__branch_entries(sample); 1297 u64 kernel_callchain_nr = callchain->nr; 1298 unsigned int i; 1299 1300 for (i = 0; i < kernel_callchain_nr; i++) { 1301 if (callchain->ips[i] == PERF_CONTEXT_USER) 1302 break; 1303 } 1304 1305 if ((i != kernel_callchain_nr) && lbr_stack->nr) { 1306 u64 total_nr; 1307 /* 1308 * LBR callstack can only get user call chain, 1309 * i is kernel call chain number, 1310 * 1 is PERF_CONTEXT_USER. 1311 * 1312 * The user call chain is stored in LBR registers. 1313 * LBR are pair registers. The caller is stored 1314 * in "from" register, while the callee is stored 1315 * in "to" register. 1316 * For example, there is a call stack 1317 * "A"->"B"->"C"->"D". 1318 * The LBR registers will be recorded like 1319 * "C"->"D", "B"->"C", "A"->"B". 1320 * So only the first "to" register and all "from" 1321 * registers are needed to construct the whole stack. 1322 */ 1323 total_nr = i + 1 + lbr_stack->nr + 1; 1324 kernel_callchain_nr = i + 1; 1325 1326 printf("... LBR call chain: nr:%" PRIu64 "\n", total_nr); 1327 1328 for (i = 0; i < kernel_callchain_nr; i++) 1329 printf("..... %2d: %016" PRIx64 "\n", 1330 i, callchain->ips[i]); 1331 1332 printf("..... %2d: %016" PRIx64 "\n", 1333 (int)(kernel_callchain_nr), entries[0].to); 1334 for (i = 0; i < lbr_stack->nr; i++) 1335 printf("..... %2d: %016" PRIx64 "\n", 1336 (int)(i + kernel_callchain_nr + 1), entries[i].from); 1337 } 1338 } 1339 1340 static const char *callchain_context_str(u64 ip) 1341 { 1342 switch (ip) { 1343 case PERF_CONTEXT_HV: 1344 return " (PERF_CONTEXT_HV)"; 1345 case PERF_CONTEXT_KERNEL: 1346 return " (PERF_CONTEXT_KERNEL)"; 1347 case PERF_CONTEXT_USER: 1348 return " (PERF_CONTEXT_USER)"; 1349 case PERF_CONTEXT_GUEST: 1350 return " (PERF_CONTEXT_GUEST)"; 1351 case PERF_CONTEXT_GUEST_KERNEL: 1352 return " (PERF_CONTEXT_GUEST_KERNEL)"; 1353 case PERF_CONTEXT_GUEST_USER: 1354 return " (PERF_CONTEXT_GUEST_USER)"; 1355 case PERF_CONTEXT_USER_DEFERRED: 1356 return " (PERF_CONTEXT_USER_DEFERRED)"; 1357 default: 1358 return ""; 1359 } 1360 } 1361 1362 static void callchain__printf(struct evsel *evsel, 1363 struct perf_sample *sample) 1364 { 1365 unsigned int i; 1366 struct ip_callchain *callchain = sample->callchain; 1367 1368 if (evsel__has_branch_callstack(evsel)) 1369 callchain__lbr_callstack_printf(sample); 1370 1371 printf("... FP chain: nr:%" PRIu64 "\n", callchain->nr); 1372 1373 for (i = 0; i < callchain->nr; i++) 1374 printf("..... %2d: %016" PRIx64 "%s\n", 1375 i, callchain->ips[i], 1376 callchain_context_str(callchain->ips[i])); 1377 1378 if (sample->deferred_callchain) 1379 printf("...... (deferred)\n"); 1380 } 1381 1382 static void branch_stack__printf(struct perf_sample *sample, 1383 struct evsel *evsel) 1384 { 1385 struct branch_entry *entries = perf_sample__branch_entries(sample); 1386 bool callstack = evsel__has_branch_callstack(evsel); 1387 u64 *branch_stack_cntr = sample->branch_stack_cntr; 1388 uint64_t i; 1389 1390 if (!callstack) { 1391 printf("%s: nr:%" PRIu64 "\n", "... branch stack", sample->branch_stack->nr); 1392 } else { 1393 /* the reason of adding 1 to nr is because after expanding 1394 * branch stack it generates nr + 1 callstack records. e.g., 1395 * B()->C() 1396 * A()->B() 1397 * the final callstack should be: 1398 * C() 1399 * B() 1400 * A() 1401 */ 1402 printf("%s: nr:%" PRIu64 "\n", "... branch callstack", sample->branch_stack->nr+1); 1403 } 1404 1405 for (i = 0; i < sample->branch_stack->nr; i++) { 1406 struct branch_entry *e = &entries[i]; 1407 1408 if (!callstack) { 1409 printf("..... %2"PRIu64": %016" PRIx64 " -> %016" PRIx64 " %hu cycles %s%s%s%s %x %s %s\n", 1410 i, e->from, e->to, 1411 (unsigned short)e->flags.cycles, 1412 e->flags.mispred ? "M" : " ", 1413 e->flags.predicted ? "P" : " ", 1414 e->flags.abort ? "A" : " ", 1415 e->flags.in_tx ? "T" : " ", 1416 (unsigned)e->flags.reserved, 1417 get_branch_type(e), 1418 e->flags.spec ? branch_spec_desc(e->flags.spec) : ""); 1419 } else { 1420 if (i == 0) { 1421 printf("..... %2"PRIu64": %016" PRIx64 "\n" 1422 "..... %2"PRIu64": %016" PRIx64 "\n", 1423 i, e->to, i+1, e->from); 1424 } else { 1425 printf("..... %2"PRIu64": %016" PRIx64 "\n", i+1, e->from); 1426 } 1427 } 1428 } 1429 1430 if (branch_stack_cntr) { 1431 unsigned int br_cntr_width, br_cntr_nr; 1432 1433 perf_env__find_br_cntr_info(evsel__env(evsel), &br_cntr_nr, &br_cntr_width); 1434 printf("... branch stack counters: nr:%" PRIu64 " (counter width: %u max counter nr:%u)\n", 1435 sample->branch_stack->nr, br_cntr_width, br_cntr_nr); 1436 for (i = 0; i < sample->branch_stack->nr; i++) 1437 printf("..... %2"PRIu64": %016" PRIx64 "\n", i, branch_stack_cntr[i]); 1438 } 1439 } 1440 1441 static void regs_dump__printf(u64 mask, struct regs_dump *regs, 1442 uint16_t e_machine, uint32_t e_flags) 1443 { 1444 unsigned rid, i = 0; 1445 1446 for_each_set_bit(rid, (unsigned long *) &mask, sizeof(mask) * 8) { 1447 u64 val = regs->regs[i++]; 1448 1449 printf(".... %-5s 0x%016" PRIx64 "\n", 1450 perf_reg_name(rid, e_machine, e_flags, regs->abi), val); 1451 } 1452 } 1453 1454 static void simd_regs_dump__printf(uint16_t e_machine, struct regs_dump *regs, bool intr) 1455 { 1456 const char *name = "unknown"; 1457 const char *simd_header; 1458 u32 i, j, idx, pred_base; 1459 uint16_t qwords; 1460 int reg_c; 1461 1462 if (!(regs->abi & PERF_SAMPLE_REGS_ABI_SIMD)) 1463 return; 1464 1465 if (!regs->nr_vectors && !regs->nr_pred) 1466 return; 1467 1468 simd_header = "... SIMD ABI nr_vectors %" PRIu64 " vector_qwords %" PRIu64 \ 1469 " nr_pred %" PRIu64 " pred_qwords %" PRIu64 "\n"; 1470 printf(simd_header, regs->nr_vectors, regs->vector_qwords, 1471 regs->nr_pred, regs->pred_qwords); 1472 1473 for (reg_c = 0; reg_c < 64; reg_c++) { 1474 if (!regs->nr_vectors) 1475 break; 1476 if (intr) { 1477 perf_intr_simd_reg_class_bitmap_qwords(e_machine, reg_c, 1478 &qwords, /*pred=*/false); 1479 } else { 1480 perf_user_simd_reg_class_bitmap_qwords(e_machine, reg_c, 1481 &qwords, /*pred=*/false); 1482 } 1483 if (regs->vector_qwords == qwords) { 1484 name = perf_simd_reg_class_name(e_machine, reg_c, /*pred=*/false); 1485 break; 1486 } 1487 } 1488 1489 for (i = 0; i < regs->nr_vectors; i++) { 1490 for (j = 0; j < regs->vector_qwords; j++) { 1491 idx = i * regs->vector_qwords + j; 1492 if (regs->vector_qwords > 1) { 1493 printf(".... %3s[%d][%d] 0x%016" PRIx64 "\n", 1494 name, i, j, regs->simd_data[idx]); 1495 } else { 1496 printf(".... %3s[%d] 0x%016" PRIx64 "\n", 1497 name, i, regs->simd_data[idx]); 1498 } 1499 } 1500 } 1501 1502 name = "unknown"; 1503 for (reg_c = 0; reg_c < 64; reg_c++) { 1504 if (!regs->nr_pred) 1505 break; 1506 if (intr) { 1507 perf_intr_simd_reg_class_bitmap_qwords(e_machine, reg_c, 1508 &qwords, /*pred=*/true); 1509 } else { 1510 perf_user_simd_reg_class_bitmap_qwords(e_machine, reg_c, 1511 &qwords, /*pred=*/true); 1512 } 1513 if (regs->pred_qwords == qwords) { 1514 name = perf_simd_reg_class_name(e_machine, reg_c, /*pred=*/true); 1515 break; 1516 } 1517 } 1518 1519 pred_base = regs->nr_vectors * regs->vector_qwords; 1520 for (i = 0; i < regs->nr_pred; i++) { 1521 for (j = 0; j < regs->pred_qwords; j++) { 1522 idx = pred_base + i * regs->pred_qwords + j; 1523 if (regs->pred_qwords > 1) { 1524 printf(".... %3s[%d][%d] 0x%016" PRIx64 "\n", 1525 name, i, j, regs->simd_data[idx]); 1526 } else { 1527 printf(".... %3s[%d] 0x%016" PRIx64 "\n", 1528 name, i, regs->simd_data[idx]); 1529 } 1530 } 1531 } 1532 } 1533 1534 static const char *regs_abi[] = { 1535 [PERF_SAMPLE_REGS_ABI_NONE] = "none", 1536 [PERF_SAMPLE_REGS_ABI_32] = "32-bit", 1537 [PERF_SAMPLE_REGS_ABI_64] = "64-bit", 1538 [PERF_SAMPLE_REGS_ABI_SIMD | PERF_SAMPLE_REGS_ABI_32] = "32-bit SIMD", 1539 [PERF_SAMPLE_REGS_ABI_SIMD | PERF_SAMPLE_REGS_ABI_64] = "64-bit SIMD", 1540 }; 1541 1542 static inline const char *regs_dump_abi(struct regs_dump *d) 1543 { 1544 if (d->abi >= ARRAY_SIZE(regs_abi) || !regs_abi[d->abi]) 1545 return "unknown"; 1546 1547 return regs_abi[d->abi]; 1548 } 1549 1550 static void regs__printf(const char *type, struct regs_dump *regs, 1551 uint16_t e_machine, uint32_t e_flags) 1552 { 1553 u64 mask = regs->mask; 1554 1555 printf("... %s regs: mask 0x%" PRIx64 " ABI %s\n", 1556 type, 1557 mask, 1558 regs_dump_abi(regs)); 1559 1560 regs_dump__printf(mask, regs, e_machine, e_flags); 1561 } 1562 1563 static void regs_user__printf(struct perf_sample *sample, uint16_t e_machine, uint32_t e_flags) 1564 { 1565 struct regs_dump *user_regs; 1566 1567 if (!sample->user_regs) 1568 return; 1569 1570 user_regs = perf_sample__user_regs(sample); 1571 1572 if (user_regs->regs) 1573 regs__printf("user", user_regs, e_machine, e_flags); 1574 simd_regs_dump__printf(e_machine, user_regs, /*intr=*/false); 1575 } 1576 1577 static void regs_intr__printf(struct perf_sample *sample, uint16_t e_machine, uint32_t e_flags) 1578 { 1579 struct regs_dump *intr_regs; 1580 1581 if (!sample->intr_regs) 1582 return; 1583 1584 intr_regs = perf_sample__intr_regs(sample); 1585 1586 if (intr_regs->regs) 1587 regs__printf("intr", intr_regs, e_machine, e_flags); 1588 simd_regs_dump__printf(e_machine, intr_regs, /*intr=*/true); 1589 } 1590 1591 static void stack_user__printf(struct stack_dump *dump) 1592 { 1593 printf("... ustack: size %" PRIu64 ", offset 0x%x\n", 1594 dump->size, dump->offset); 1595 } 1596 1597 static void evlist__print_tstamp(struct evlist *evlist, union perf_event *event, struct perf_sample *sample) 1598 { 1599 u64 sample_type = __evlist__combined_sample_type(evlist); 1600 1601 if (event->header.type != PERF_RECORD_SAMPLE && 1602 !evlist__sample_id_all(evlist)) { 1603 fputs("-1 -1 ", stdout); 1604 return; 1605 } 1606 1607 if ((sample_type & PERF_SAMPLE_CPU)) 1608 printf("%u ", sample->cpu); 1609 1610 if (sample_type & PERF_SAMPLE_TIME) 1611 printf("%" PRIu64 " ", sample->time); 1612 } 1613 1614 static void sample_read__printf(struct perf_sample *sample, u64 read_format) 1615 { 1616 printf("... sample_read:\n"); 1617 1618 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 1619 printf("...... time enabled %016" PRIx64 "\n", 1620 sample->read.time_enabled); 1621 1622 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 1623 printf("...... time running %016" PRIx64 "\n", 1624 sample->read.time_running); 1625 1626 if (read_format & PERF_FORMAT_GROUP) { 1627 struct sample_read_value *value = sample->read.group.values; 1628 1629 printf(".... group nr %" PRIu64 "\n", sample->read.group.nr); 1630 1631 sample_read_group__for_each(value, sample->read.group.nr, read_format) { 1632 printf("..... id %016" PRIx64 1633 ", value %016" PRIx64, 1634 value->id, value->value); 1635 if (read_format & PERF_FORMAT_LOST) 1636 printf(", lost %" PRIu64, value->lost); 1637 printf("\n"); 1638 } 1639 } else { 1640 printf("..... id %016" PRIx64 ", value %016" PRIx64, 1641 sample->read.one.id, sample->read.one.value); 1642 if (read_format & PERF_FORMAT_LOST) 1643 printf(", lost %" PRIu64, sample->read.one.lost); 1644 printf("\n"); 1645 } 1646 } 1647 1648 static void dump_event(struct evlist *evlist, union perf_event *event, 1649 u64 file_offset, struct perf_sample *sample, 1650 const char *file_path) 1651 { 1652 if (!dump_trace) 1653 return; 1654 1655 printf("\n%#" PRIx64 "@%s [%#x]: event: %d\n", 1656 file_offset, file_path, event->header.size, event->header.type); 1657 1658 trace_event(event); 1659 if (event->header.type == PERF_RECORD_SAMPLE && evlist__trace_event_sample_raw(evlist)) 1660 evlist__trace_event_sample_raw(evlist)(evlist, event, sample); 1661 1662 if (sample) 1663 evlist__print_tstamp(evlist, event, sample); 1664 1665 printf("%#" PRIx64 " [%#x]: PERF_RECORD_%s", file_offset, 1666 event->header.size, perf_event__name(event->header.type)); 1667 } 1668 1669 char *get_page_size_name(u64 size, char *str) 1670 { 1671 if (!size || !unit_number__scnprintf(str, PAGE_SIZE_NAME_LEN, size)) 1672 snprintf(str, PAGE_SIZE_NAME_LEN, "%s", "N/A"); 1673 1674 return str; 1675 } 1676 1677 static void dump_sample(struct machine *machine, union perf_event *event, 1678 struct perf_sample *sample) 1679 { 1680 struct evsel *evsel = sample->evsel; 1681 u64 sample_type; 1682 char str[PAGE_SIZE_NAME_LEN]; 1683 uint16_t e_machine = EM_NONE; 1684 uint32_t e_flags = 0; 1685 1686 if (!dump_trace) 1687 return; 1688 1689 sample_type = evsel->core.attr.sample_type; 1690 1691 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_REGS_INTR)) { 1692 struct thread *thread = machine__find_thread(machine, sample->pid, sample->pid); 1693 1694 e_machine = thread__e_machine(thread, machine, &e_flags); 1695 } 1696 1697 printf("(IP, 0x%x): %d/%d: %#" PRIx64 " period: %" PRIu64 " addr: %#" PRIx64 "\n", 1698 event->header.misc, sample->pid, sample->tid, sample->ip, 1699 sample->period, sample->addr); 1700 1701 if (evsel__has_callchain(evsel)) 1702 callchain__printf(evsel, sample); 1703 1704 if (evsel__has_br_stack(evsel)) 1705 branch_stack__printf(sample, evsel); 1706 1707 if (sample_type & PERF_SAMPLE_REGS_USER) 1708 regs_user__printf(sample, e_machine, e_flags); 1709 1710 if (sample_type & PERF_SAMPLE_REGS_INTR) 1711 regs_intr__printf(sample, e_machine, e_flags); 1712 1713 if (sample_type & PERF_SAMPLE_STACK_USER) 1714 stack_user__printf(&sample->user_stack); 1715 1716 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 1717 printf("... weight: %" PRIu64 "", sample->weight); 1718 if (sample_type & PERF_SAMPLE_WEIGHT_STRUCT) { 1719 printf(",0x%"PRIx16"", sample->ins_lat); 1720 printf(",0x%"PRIx16"", sample->weight3); 1721 } 1722 printf("\n"); 1723 } 1724 1725 if (sample_type & PERF_SAMPLE_DATA_SRC) 1726 printf(" . data_src: 0x%"PRIx64"\n", sample->data_src); 1727 1728 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 1729 printf(" .. phys_addr: 0x%"PRIx64"\n", sample->phys_addr); 1730 1731 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 1732 printf(" .. data page size: %s\n", get_page_size_name(sample->data_page_size, str)); 1733 1734 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 1735 printf(" .. code page size: %s\n", get_page_size_name(sample->code_page_size, str)); 1736 1737 if (sample_type & PERF_SAMPLE_TRANSACTION) 1738 printf("... transaction: %" PRIx64 "\n", sample->transaction); 1739 1740 if (sample_type & PERF_SAMPLE_READ) 1741 sample_read__printf(sample, evsel->core.attr.read_format); 1742 } 1743 1744 static void dump_deferred_callchain(union perf_event *event, struct perf_sample *sample) 1745 { 1746 struct evsel *evsel = sample->evsel; 1747 1748 if (!dump_trace) 1749 return; 1750 1751 printf("(IP, 0x%x): %d/%d: %#" PRIx64 "\n", 1752 event->header.misc, sample->pid, sample->tid, sample->deferred_cookie); 1753 1754 if (evsel__has_callchain(evsel)) 1755 callchain__printf(evsel, sample); 1756 } 1757 1758 static void dump_read(struct evsel *evsel, union perf_event *event) 1759 { 1760 u64 read_format; 1761 __u64 *array; 1762 void *end; 1763 1764 if (!dump_trace) 1765 return; 1766 1767 printf(": %d %d %s %" PRI_lu64 "\n", event->read.pid, event->read.tid, 1768 evsel__name(evsel), event->read.value); 1769 1770 if (!evsel) 1771 return; 1772 1773 read_format = evsel->core.attr.read_format; 1774 /* 1775 * The kernel packs only the enabled read_format fields 1776 * after value, with no gaps. Walk the packed array 1777 * instead of using fixed struct offsets. 1778 */ 1779 array = &event->read.value + 1; 1780 end = (void *)event + event->header.size; 1781 1782 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 1783 if ((void *)(array + 1) > end) 1784 return; 1785 printf("... time enabled : %" PRI_lu64 "\n", *array++); 1786 } 1787 1788 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 1789 if ((void *)(array + 1) > end) 1790 return; 1791 printf("... time running : %" PRI_lu64 "\n", *array++); 1792 } 1793 1794 if (read_format & PERF_FORMAT_ID) { 1795 if ((void *)(array + 1) > end) 1796 return; 1797 printf("... id : %" PRI_lu64 "\n", *array++); 1798 } 1799 1800 if (read_format & PERF_FORMAT_LOST) { 1801 if ((void *)(array + 1) > end) 1802 return; 1803 printf("... lost : %" PRI_lu64 "\n", *array++); 1804 } 1805 } 1806 1807 static struct machine *machines__find_for_cpumode(struct machines *machines, 1808 union perf_event *event, 1809 struct perf_sample *sample) 1810 { 1811 if (perf_guest && 1812 ((sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL) || 1813 (sample->cpumode == PERF_RECORD_MISC_GUEST_USER))) { 1814 u32 pid; 1815 1816 if (sample->machine_pid) 1817 pid = sample->machine_pid; 1818 else if (event->header.type == PERF_RECORD_MMAP 1819 || event->header.type == PERF_RECORD_MMAP2) 1820 pid = event->mmap.pid; 1821 else 1822 pid = sample->pid; 1823 1824 /* 1825 * Guest code machine is created as needed and does not use 1826 * DEFAULT_GUEST_KERNEL_ID. 1827 */ 1828 if (symbol_conf.guest_code) 1829 return machines__findnew(machines, pid); 1830 1831 return machines__find_guest(machines, pid); 1832 } 1833 1834 return &machines->host; 1835 } 1836 1837 static int deliver_sample_value(struct evlist *evlist, 1838 const struct perf_tool *tool, 1839 union perf_event *event, 1840 struct perf_sample *sample, 1841 struct sample_read_value *v, 1842 struct machine *machine, 1843 bool per_thread) 1844 { 1845 struct perf_sample_id *sid = evlist__id2sid(evlist, v->id); 1846 struct evsel *saved_evsel = sample->evsel; 1847 u64 *storage = NULL; 1848 int ret; 1849 1850 if (sid) { 1851 storage = perf_sample_id__get_period_storage(sid, sample->tid, per_thread); 1852 } 1853 1854 if (storage) { 1855 sample->id = v->id; 1856 sample->period = v->value - *storage; 1857 *storage = v->value; 1858 } 1859 1860 if (!storage || sid->evsel == NULL) { 1861 ++evlist__stats(evlist)->nr_unknown_id; 1862 return 0; 1863 } 1864 1865 /* 1866 * There's no reason to deliver sample 1867 * for zero period, bail out. 1868 */ 1869 if (!sample->period) 1870 return 0; 1871 1872 sample->evsel = container_of(sid->evsel, struct evsel, core); 1873 ret = tool->sample(tool, event, sample, machine); 1874 sample->evsel = saved_evsel; 1875 return ret; 1876 } 1877 1878 static int deliver_sample_group(struct evlist *evlist, 1879 const struct perf_tool *tool, 1880 union perf_event *event, 1881 struct perf_sample *sample, 1882 struct machine *machine, 1883 u64 read_format, 1884 bool per_thread) 1885 { 1886 int ret = -EINVAL; 1887 struct sample_read_value *v = sample->read.group.values; 1888 1889 if (tool->dont_split_sample_group) 1890 return deliver_sample_value(evlist, tool, event, sample, v, machine, 1891 per_thread); 1892 1893 sample_read_group__for_each(v, sample->read.group.nr, read_format) { 1894 ret = deliver_sample_value(evlist, tool, event, sample, v, 1895 machine, per_thread); 1896 if (ret) 1897 break; 1898 } 1899 1900 return ret; 1901 } 1902 1903 static int evlist__deliver_sample(struct evlist *evlist, const struct perf_tool *tool, 1904 union perf_event *event, struct perf_sample *sample, 1905 struct machine *machine) 1906 { 1907 struct evsel *evsel = sample->evsel; 1908 /* We know evsel != NULL. */ 1909 u64 sample_type = evsel->core.attr.sample_type; 1910 u64 read_format = evsel->core.attr.read_format; 1911 bool per_thread = perf_evsel__attr_has_per_thread_sample_period(&evsel->core); 1912 1913 /* Standard sample delivery. */ 1914 if (!(sample_type & PERF_SAMPLE_READ)) 1915 return tool->sample(tool, event, sample, machine); 1916 1917 /* For PERF_SAMPLE_READ we have either single or group mode. */ 1918 if (read_format & PERF_FORMAT_GROUP) 1919 return deliver_sample_group(evlist, tool, event, sample, 1920 machine, read_format, per_thread); 1921 else 1922 return deliver_sample_value(evlist, tool, event, sample, 1923 &sample->read.one, machine, 1924 per_thread); 1925 } 1926 1927 /* 1928 * Samples with deferred callchains should wait for the next matching 1929 * PERF_RECORD_CALLCHAIN_RECORD entries. Keep the events in a list and 1930 * deliver them once it finds the callchains. 1931 */ 1932 struct deferred_event { 1933 struct list_head list; 1934 union perf_event *event; 1935 u64 file_offset; 1936 }; 1937 1938 /* 1939 * This is called when a deferred callchain record comes up. Find all matching 1940 * samples, merge the callchains and process them. 1941 */ 1942 static int evlist__deliver_deferred_callchain(struct evlist *evlist, 1943 const struct perf_tool *tool, 1944 union perf_event *event, 1945 struct perf_sample *sample, 1946 struct machine *machine) 1947 { 1948 struct deferred_event *de, *tmp; 1949 int ret = 0; 1950 1951 if (!tool->merge_deferred_callchains) { 1952 struct evsel *saved_evsel = sample->evsel; 1953 1954 sample->evsel = evlist__id2evsel(evlist, sample->id); 1955 if (sample->evsel) 1956 sample->evsel = evsel__get(sample->evsel); 1957 ret = tool->callchain_deferred(tool, event, sample, machine); 1958 evsel__put(sample->evsel); 1959 sample->evsel = saved_evsel; 1960 return ret; 1961 } 1962 1963 list_for_each_entry_safe(de, tmp, evlist__deferred_samples(evlist), list) { 1964 struct perf_sample orig_sample; 1965 struct evsel *new_evsel; 1966 1967 perf_sample__init(&orig_sample, /*all=*/false); 1968 ret = evlist__parse_sample(evlist, de->event, &orig_sample); 1969 if (ret < 0) { 1970 pr_err("failed to parse original sample\n"); 1971 perf_sample__exit(&orig_sample); 1972 break; 1973 } 1974 orig_sample.file_offset = de->file_offset; 1975 1976 if (sample->tid != orig_sample.tid) { 1977 perf_sample__exit(&orig_sample); 1978 continue; 1979 } 1980 1981 if (event->callchain_deferred.cookie == orig_sample.deferred_cookie) 1982 sample__merge_deferred_callchain(&orig_sample, sample); 1983 else 1984 orig_sample.deferred_callchain = false; 1985 1986 new_evsel = evlist__id2evsel(evlist, orig_sample.id); 1987 if (new_evsel != orig_sample.evsel) { 1988 evsel__put(orig_sample.evsel); 1989 orig_sample.evsel = evsel__get(new_evsel); 1990 } 1991 ret = evlist__deliver_sample(evlist, tool, de->event, 1992 &orig_sample, machine); 1993 1994 perf_sample__exit(&orig_sample); 1995 list_del(&de->list); 1996 free(de->event); 1997 free(de); 1998 1999 if (ret) 2000 break; 2001 } 2002 return ret; 2003 } 2004 2005 /* 2006 * This is called at the end of the data processing for the session. Flush the 2007 * remaining samples as there's no hope for matching deferred callchains. 2008 */ 2009 static int session__flush_deferred_samples(struct perf_session *session, 2010 const struct perf_tool *tool) 2011 { 2012 struct evlist *evlist = session->evlist; 2013 struct machine *machine = &session->machines.host; 2014 struct deferred_event *de, *tmp; 2015 int ret = 0; 2016 2017 list_for_each_entry_safe(de, tmp, evlist__deferred_samples(evlist), list) { 2018 struct perf_sample sample; 2019 struct evsel *new_evsel; 2020 2021 if (session_done()) { 2022 /* Processing was stopped early, discard the sample. */ 2023 list_del(&de->list); 2024 free(de->event); 2025 free(de); 2026 continue; 2027 } 2028 2029 perf_sample__init(&sample, /*all=*/false); 2030 ret = evlist__parse_sample(evlist, de->event, &sample); 2031 if (ret < 0) { 2032 pr_err("failed to parse original sample\n"); 2033 perf_sample__exit(&sample); 2034 break; 2035 } 2036 sample.file_offset = de->file_offset; 2037 2038 new_evsel = evlist__id2evsel(evlist, sample.id); 2039 if (new_evsel != sample.evsel) { 2040 evsel__put(sample.evsel); 2041 sample.evsel = evsel__get(new_evsel); 2042 } 2043 ret = evlist__deliver_sample(evlist, tool, de->event, 2044 &sample, machine); 2045 2046 perf_sample__exit(&sample); 2047 list_del(&de->list); 2048 free(de->event); 2049 free(de); 2050 2051 if (ret) 2052 break; 2053 } 2054 return ret; 2055 } 2056 2057 /* 2058 * Return true if the string field is properly null-terminated 2059 * within the event boundary. Native-endian files are mapped 2060 * read-only (MAP_SHARED + PROT_READ) so we cannot write a 2061 * null byte in place; skip the event instead. 2062 */ 2063 static bool perf_event__check_nul(const char *str, const void *end, 2064 const char *event_name, u64 file_offset) 2065 { 2066 size_t max_len = (const char *)end - str; 2067 2068 if (max_len == 0 || strnlen(str, max_len) == max_len) { 2069 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_%s: string not null-terminated, skipping event\n", 2070 file_offset, event_name); 2071 return false; 2072 } 2073 2074 return true; 2075 } 2076 2077 static int machines__deliver_event(struct machines *machines, 2078 struct evlist *evlist, 2079 union perf_event *event, 2080 struct perf_sample *sample, 2081 const struct perf_tool *tool, u64 file_offset, 2082 const char *file_path) 2083 { 2084 struct machine *machine; 2085 2086 dump_event(evlist, event, file_offset, sample, file_path); 2087 2088 if (!sample->evsel) { 2089 sample->evsel = evlist__id2evsel(evlist, sample->id); 2090 if (sample->evsel) 2091 sample->evsel = evsel__get(sample->evsel); 2092 } 2093 else 2094 assert(sample->evsel == evlist__id2evsel(evlist, sample->id)); 2095 machine = machines__find_for_cpumode(machines, event, sample); 2096 2097 switch (event->header.type) { 2098 case PERF_RECORD_SAMPLE: 2099 if (sample->evsel == NULL) { 2100 ++evlist__stats(evlist)->nr_unknown_id; 2101 return 0; 2102 } 2103 if (machine == NULL) { 2104 ++evlist__stats(evlist)->nr_unprocessable_samples; 2105 dump_sample(machine, event, sample); 2106 return 0; 2107 } 2108 dump_sample(machine, event, sample); 2109 if (sample->deferred_callchain && tool->merge_deferred_callchains) { 2110 struct deferred_event *de = malloc(sizeof(*de)); 2111 size_t sz = event->header.size; 2112 2113 if (de == NULL) 2114 return -ENOMEM; 2115 2116 de->event = malloc(sz); 2117 if (de->event == NULL) { 2118 free(de); 2119 return -ENOMEM; 2120 } 2121 memcpy(de->event, event, sz); 2122 de->file_offset = sample->file_offset; 2123 list_add_tail(&de->list, evlist__deferred_samples(evlist)); 2124 return 0; 2125 } 2126 return evlist__deliver_sample(evlist, tool, event, sample, machine); 2127 case PERF_RECORD_MMAP: 2128 if (!perf_event__check_nul(event->mmap.filename, 2129 (void *)event + event->header.size, 2130 "MMAP", file_offset)) 2131 return 0; 2132 return tool->mmap(tool, event, sample, machine); 2133 case PERF_RECORD_MMAP2: 2134 if (event->header.misc & PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT) 2135 ++evlist__stats(evlist)->nr_proc_map_timeout; 2136 if (!perf_event__check_nul(event->mmap2.filename, 2137 (void *)event + event->header.size, 2138 "MMAP2", file_offset)) 2139 return 0; 2140 return tool->mmap2(tool, event, sample, machine); 2141 case PERF_RECORD_COMM: 2142 if (!perf_event__check_nul(event->comm.comm, 2143 (void *)event + event->header.size, 2144 "COMM", file_offset)) 2145 return 0; 2146 return tool->comm(tool, event, sample, machine); 2147 case PERF_RECORD_NAMESPACES: { 2148 /* 2149 * Cannot underflow: perf_event__min_size[] guarantees header.size >= sizeof. 2150 * Includes trailing sample_id space when present, but prevents OOB. 2151 */ 2152 u64 max_nr = (event->header.size - sizeof(event->namespaces)) / 2153 sizeof(event->namespaces.link_info[0]); 2154 2155 /* 2156 * Native-endian events are mmap'd read-only, so we 2157 * cannot clamp nr in place. Skip the event instead. 2158 * The swap handler already clamps on the writable 2159 * cross-endian path. 2160 */ 2161 if (event->namespaces.nr_namespaces > max_nr) { 2162 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_NAMESPACES: nr_namespaces %" PRIu64 " exceeds payload (max %" PRIu64 "), skipping\n", 2163 file_offset, (u64)event->namespaces.nr_namespaces, max_nr); 2164 return 0; 2165 } 2166 return tool->namespaces(tool, event, sample, machine); 2167 } 2168 case PERF_RECORD_CGROUP: 2169 if (!perf_event__check_nul(event->cgroup.path, 2170 (void *)event + event->header.size, 2171 "CGROUP", file_offset)) 2172 return 0; 2173 return tool->cgroup(tool, event, sample, machine); 2174 case PERF_RECORD_FORK: 2175 return tool->fork(tool, event, sample, machine); 2176 case PERF_RECORD_EXIT: 2177 return tool->exit(tool, event, sample, machine); 2178 case PERF_RECORD_LOST: 2179 if (tool->lost == perf_event__process_lost) 2180 evlist__stats(evlist)->total_lost += event->lost.lost; 2181 return tool->lost(tool, event, sample, machine); 2182 case PERF_RECORD_LOST_SAMPLES: 2183 if (event->header.misc & PERF_RECORD_MISC_LOST_SAMPLES_BPF) 2184 evlist__stats(evlist)->total_dropped_samples += event->lost_samples.lost; 2185 else if (tool->lost_samples == perf_event__process_lost_samples) 2186 evlist__stats(evlist)->total_lost_samples += event->lost_samples.lost; 2187 return tool->lost_samples(tool, event, sample, machine); 2188 case PERF_RECORD_READ: 2189 dump_read(sample->evsel, event); 2190 return tool->read(tool, event, sample, machine); 2191 case PERF_RECORD_THROTTLE: 2192 return tool->throttle(tool, event, sample, machine); 2193 case PERF_RECORD_UNTHROTTLE: 2194 return tool->unthrottle(tool, event, sample, machine); 2195 case PERF_RECORD_AUX: 2196 if (tool->aux == perf_event__process_aux) { 2197 if (event->aux.flags & PERF_AUX_FLAG_TRUNCATED) 2198 evlist__stats(evlist)->total_aux_lost += 1; 2199 if (event->aux.flags & PERF_AUX_FLAG_PARTIAL) 2200 evlist__stats(evlist)->total_aux_partial += 1; 2201 if (event->aux.flags & PERF_AUX_FLAG_COLLISION) 2202 evlist__stats(evlist)->total_aux_collision += 1; 2203 } 2204 return tool->aux(tool, event, sample, machine); 2205 case PERF_RECORD_ITRACE_START: 2206 return tool->itrace_start(tool, event, sample, machine); 2207 case PERF_RECORD_SWITCH: 2208 case PERF_RECORD_SWITCH_CPU_WIDE: 2209 return tool->context_switch(tool, event, sample, machine); 2210 case PERF_RECORD_KSYMBOL: 2211 if (!perf_event__check_nul(event->ksymbol.name, 2212 (void *)event + event->header.size, 2213 "KSYMBOL", file_offset)) 2214 return 0; 2215 return tool->ksymbol(tool, event, sample, machine); 2216 case PERF_RECORD_BPF_EVENT: 2217 return tool->bpf(tool, event, sample, machine); 2218 case PERF_RECORD_TEXT_POKE: { 2219 /* offsetof(bytes), not sizeof — sizeof includes padding past the flexible array */ 2220 size_t text_poke_len = offsetof(struct perf_record_text_poke_event, bytes) + 2221 event->text_poke.old_len + 2222 event->text_poke.new_len; 2223 2224 if (event->header.size < text_poke_len) { 2225 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_TEXT_POKE: old_len+new_len exceeds event, skipping\n", 2226 file_offset); 2227 return 0; 2228 } 2229 return tool->text_poke(tool, event, sample, machine); 2230 } 2231 case PERF_RECORD_AUX_OUTPUT_HW_ID: 2232 return tool->aux_output_hw_id(tool, event, sample, machine); 2233 case PERF_RECORD_CALLCHAIN_DEFERRED: 2234 dump_deferred_callchain(event, sample); 2235 return evlist__deliver_deferred_callchain(evlist, tool, event, 2236 sample, machine); 2237 default: 2238 ++evlist__stats(evlist)->nr_unknown_events; 2239 return -1; 2240 } 2241 } 2242 2243 static int perf_session__deliver_event(struct perf_session *session, 2244 union perf_event *event, 2245 const struct perf_tool *tool, 2246 u64 file_offset, 2247 const char *file_path) 2248 { 2249 struct perf_sample sample; 2250 struct evsel *evsel; 2251 int ret; 2252 2253 perf_sample__init(&sample, /*all=*/false); 2254 evsel = evlist__event2evsel(session->evlist, event); 2255 if (!evsel) { 2256 pr_err("ERROR: at offset %#" PRIx64 ": no evsel found for %s (%u) event\n", 2257 file_offset, perf_event__name(event->header.type), 2258 event->header.type); 2259 ret = -EFAULT; 2260 goto out; 2261 } 2262 ret = evsel__parse_sample(evsel, event, &sample); 2263 if (ret) { 2264 pr_err("ERROR: at offset %#" PRIx64 ": can't parse %s (%u) sample, err = %d\n", 2265 file_offset, perf_event__name(event->header.type), 2266 event->header.type, ret); 2267 goto out; 2268 } 2269 sample.file_offset = file_offset; 2270 /* 2271 * evsel__parse_sample() doesn't populate machine_pid/vcpu, 2272 * which are needed by machines__find_for_cpumode() to 2273 * attribute samples to guest VMs. The SID table maps 2274 * sample IDs to the guest that owns the event. 2275 */ 2276 if (perf_guest && sample.id) { 2277 struct perf_sample_id *sid = evlist__id2sid(session->evlist, sample.id); 2278 2279 if (sid) { 2280 sample.machine_pid = sid->machine_pid; 2281 sample.vcpu = sid->vcpu.cpu; 2282 } 2283 } 2284 2285 /* 2286 * Validate sample.cpu before any callback can use it as an 2287 * array index (kwork cpus_runtime, timechart cpus_cstate_*, 2288 * sched cpu_last_switched). 2289 * 2290 * When PERF_SAMPLE_CPU is absent, evsel__parse_sample() leaves 2291 * sample.cpu as (u32)-1 — a sentinel that downstream tools 2292 * (script, inject) check to identify events without CPU info. 2293 * Only check when sample.cpu was actually populated from event 2294 * data: PERF_RECORD_SAMPLE always has it when PERF_SAMPLE_CPU 2295 * is set; non-sample events only have it when sample_id_all is 2296 * enabled. Otherwise sample.cpu is the (u32)-1 sentinel from 2297 * evsel__parse_sample() and must not be validated or clamped. 2298 */ 2299 if ((evsel->core.attr.sample_type & PERF_SAMPLE_CPU) && 2300 (event->header.type == PERF_RECORD_SAMPLE || 2301 evsel->core.attr.sample_id_all)) { 2302 int nr_cpus_avail = perf_session__env(session)->nr_cpus_avail; 2303 2304 /* 2305 * For perf.data files the MAX_NR_CPUS fallback in 2306 * perf_session__read_header() guarantees this is set. 2307 * For pipe mode, HEADER_NRCPUS may arrive late or not 2308 * at all (pre-2017 perf, third-party tools). Fall 2309 * back to MAX_NR_CPUS so the bounds check still works 2310 * against fixed-size downstream arrays. 2311 * 2312 * Do NOT write back to env: this function runs during 2313 * recording (synthesized events) when nr_cpus_avail is 2314 * legitimately 0. Writing MAX_NR_CPUS would cause 2315 * write_cpu_topology() to emit 4096 core_id/socket_id 2316 * pairs instead of the real CPU count, corrupting the 2317 * topology section in the generated perf.data. 2318 */ 2319 if (nr_cpus_avail <= 0) 2320 nr_cpus_avail = MAX_NR_CPUS; 2321 /* 2322 * Cap at MAX_NR_CPUS for the bounds check — downstream 2323 * consumers use fixed-size arrays of that size. Keep 2324 * the true nr_cpus_avail in env for header parsing 2325 * (e.g. process_cpu_topology) which needs the real count. 2326 */ 2327 if (nr_cpus_avail > MAX_NR_CPUS) 2328 nr_cpus_avail = MAX_NR_CPUS; 2329 if (sample.cpu >= (u32)nr_cpus_avail && 2330 sample.cpu != (u32)-1) { 2331 /* 2332 * Warn rather than abort: synthesized events 2333 * (MMAP, COMM) lack sample_id_all data, so 2334 * parse_id_sample reads garbage from the event 2335 * payload. Clamping to 0 protects downstream 2336 * array indexing while keeping the session alive. 2337 * 2338 * Preserve (u32)-1: perf script and perf inject 2339 * use it as a sentinel for "CPU not applicable." 2340 * Downstream array users (timechart, kwork) have 2341 * their own per-callback bounds checks. 2342 */ 2343 pr_warning_once("WARNING: at offset %#" PRIx64 ": sample CPU %u >= nr_cpus_avail %u, clamping to 0\n", 2344 file_offset, sample.cpu, nr_cpus_avail); 2345 sample.cpu = 0; 2346 } 2347 } 2348 2349 ret = auxtrace__process_event(session, event, &sample, tool); 2350 if (ret < 0) 2351 goto out; 2352 if (ret > 0) { 2353 ret = 0; 2354 goto out; 2355 } 2356 2357 ret = machines__deliver_event(&session->machines, session->evlist, 2358 event, &sample, tool, file_offset, file_path); 2359 2360 if (dump_trace && sample.aux_sample.size) 2361 auxtrace__dump_auxtrace_sample(session, &sample); 2362 out: 2363 perf_sample__exit(&sample); 2364 return ret; 2365 } 2366 2367 static s64 perf_session__process_user_event(struct perf_session *session, 2368 union perf_event *event, 2369 u64 file_offset, 2370 const char *file_path) 2371 { 2372 struct ordered_events *oe = &session->ordered_events; 2373 const struct perf_tool *tool = session->tool; 2374 const u32 event_size = READ_ONCE(event->header.size); 2375 struct perf_sample sample; 2376 int fd = perf_data__fd(session->data); 2377 s64 err; 2378 2379 perf_sample__init(&sample, /*all=*/true); 2380 if ((event->header.type != PERF_RECORD_COMPRESSED && 2381 event->header.type != PERF_RECORD_COMPRESSED2) || 2382 perf_tool__compressed_is_stub(tool)) 2383 dump_event(session->evlist, event, file_offset, &sample, file_path); 2384 2385 /* These events are processed right away */ 2386 switch (event->header.type) { 2387 case PERF_RECORD_HEADER_ATTR: 2388 err = tool->attr(tool, event, &session->evlist); 2389 if (err == 0) { 2390 perf_session__set_id_hdr_size(session); 2391 perf_session__set_comm_exec(session); 2392 } 2393 break; 2394 case PERF_RECORD_EVENT_UPDATE: 2395 err = tool->event_update(tool, event, &session->evlist); 2396 break; 2397 case PERF_RECORD_HEADER_EVENT_TYPE: 2398 /* 2399 * Deprecated, but we need to handle it for sake 2400 * of old data files create in pipe mode. 2401 */ 2402 err = 0; 2403 break; 2404 case PERF_RECORD_HEADER_TRACING_DATA: 2405 /* 2406 * Setup for reading amidst mmap, but only when we 2407 * are in 'file' mode. The 'pipe' fd is in proper 2408 * place already. 2409 */ 2410 if (!perf_data__is_pipe(session->data)) 2411 lseek(fd, file_offset, SEEK_SET); 2412 err = tool->tracing_data(tool, session, event); 2413 break; 2414 case PERF_RECORD_HEADER_BUILD_ID: 2415 if (!perf_event__check_nul(event->build_id.filename, 2416 (void *)event + event_size, 2417 "HEADER_BUILD_ID", file_offset)) { 2418 err = 0; 2419 break; 2420 } 2421 err = tool->build_id(tool, session, event); 2422 break; 2423 case PERF_RECORD_FINISHED_ROUND: 2424 err = tool->finished_round(tool, event, oe); 2425 break; 2426 case PERF_RECORD_ID_INDEX: 2427 err = tool->id_index(tool, session, event); 2428 break; 2429 case PERF_RECORD_AUXTRACE_INFO: 2430 err = tool->auxtrace_info(tool, session, event); 2431 break; 2432 case PERF_RECORD_AUXTRACE: 2433 /* 2434 * Setup for reading amidst mmap, but only when we 2435 * are in 'file' mode. The 'pipe' fd is in proper 2436 * place already. 2437 */ 2438 if (!perf_data__is_pipe(session->data)) 2439 lseek(fd, file_offset + event_size, SEEK_SET); 2440 err = tool->auxtrace(tool, session, event); 2441 break; 2442 case PERF_RECORD_AUXTRACE_ERROR: 2443 perf_session__auxtrace_error_inc(session, event); 2444 err = tool->auxtrace_error(tool, session, event); 2445 break; 2446 case PERF_RECORD_THREAD_MAP: { 2447 u64 max_nr; 2448 2449 if (event_size < sizeof(event->thread_map)) { 2450 pr_err("ERROR: at offset %#" PRIx64 ": PERF_RECORD_THREAD_MAP: header.size (%u) too small\n", 2451 file_offset, event_size); 2452 err = -EINVAL; 2453 break; 2454 } 2455 2456 max_nr = (event_size - sizeof(event->thread_map)) / 2457 sizeof(event->thread_map.entries[0]); 2458 if (event->thread_map.nr > max_nr) { 2459 pr_err("ERROR: at offset %#" PRIx64 ": PERF_RECORD_THREAD_MAP: nr %" PRIu64 " exceeds max %" PRIu64 "\n", 2460 file_offset, (u64)event->thread_map.nr, max_nr); 2461 err = -EINVAL; 2462 break; 2463 } 2464 2465 err = tool->thread_map(tool, session, event); 2466 break; 2467 } 2468 case PERF_RECORD_CPU_MAP: { 2469 struct perf_record_cpu_map_data *data = &event->cpu_map.data; 2470 u32 payload = event_size - sizeof(event->header); 2471 2472 /* 2473 * Native-endian events are mmap'd read-only, so we 2474 * cannot clamp nr fields in place. Skip the event 2475 * if any variant overflows. 2476 */ 2477 switch (data->type) { 2478 case PERF_CPU_MAP__CPUS: { 2479 u16 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 2480 cpus_data.cpu)) / 2481 sizeof(data->cpus_data.cpu[0]); 2482 2483 if (data->cpus_data.nr > max_nr) { 2484 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_CPU_MAP: nr %u exceeds payload (max %u), skipping\n", 2485 file_offset, data->cpus_data.nr, max_nr); 2486 err = 0; 2487 goto out; 2488 } 2489 break; 2490 } 2491 case PERF_CPU_MAP__MASK: 2492 if (data->mask32_data.long_size == 4) { 2493 u16 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 2494 mask32_data.mask)) / 2495 sizeof(data->mask32_data.mask[0]); 2496 2497 if (data->mask32_data.nr > max_nr) { 2498 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_CPU_MAP mask32: nr %u exceeds payload (max %u), skipping\n", 2499 file_offset, data->mask32_data.nr, max_nr); 2500 err = 0; 2501 goto out; 2502 } 2503 } else if (data->mask64_data.long_size == 8) { 2504 u16 max_nr; 2505 2506 if (payload < offsetof(struct perf_record_cpu_map_data, mask64_data.mask)) { 2507 err = 0; 2508 goto out; 2509 } 2510 max_nr = (payload - offsetof(struct perf_record_cpu_map_data, 2511 mask64_data.mask)) / 2512 sizeof(data->mask64_data.mask[0]); 2513 if (data->mask64_data.nr > max_nr) { 2514 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_CPU_MAP mask64: nr %u exceeds payload (max %u), skipping\n", 2515 file_offset, data->mask64_data.nr, max_nr); 2516 err = 0; 2517 goto out; 2518 } 2519 } else { 2520 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_CPU_MAP: unsupported long_size %u, skipping\n", 2521 file_offset, data->mask32_data.long_size); 2522 err = 0; 2523 goto out; 2524 } 2525 break; 2526 default: 2527 break; 2528 } 2529 2530 err = tool->cpu_map(tool, session, event); 2531 break; 2532 } 2533 case PERF_RECORD_STAT_CONFIG: { 2534 /* Cannot underflow: perf_event__min_size[] guarantees event_size >= sizeof */ 2535 u64 max_nr = (event_size - sizeof(event->stat_config)) / 2536 sizeof(event->stat_config.data[0]); 2537 2538 /* 2539 * Native-endian events are mmap'd read-only, so we 2540 * cannot clamp nr in place. Skip the event instead. 2541 */ 2542 if (event->stat_config.nr > max_nr) { 2543 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_STAT_CONFIG: nr %" PRIu64 " exceeds payload (max %" PRIu64 "), skipping\n", 2544 file_offset, (u64)event->stat_config.nr, max_nr); 2545 err = 0; 2546 goto out; 2547 } 2548 2549 err = tool->stat_config(tool, session, event); 2550 break; 2551 } 2552 case PERF_RECORD_STAT: 2553 err = tool->stat(tool, session, event); 2554 break; 2555 case PERF_RECORD_STAT_ROUND: 2556 err = tool->stat_round(tool, session, event); 2557 break; 2558 case PERF_RECORD_TIME_CONV: 2559 /* 2560 * Bounded copy: older kernels emit a shorter struct 2561 * without time_cycles/time_mask/cap_user_time_*. 2562 * Zero the rest so extended fields default to off. 2563 */ 2564 memset(&session->time_conv, 0, sizeof(session->time_conv)); 2565 memcpy(&session->time_conv, &event->time_conv, 2566 min((size_t)event_size, sizeof(session->time_conv))); 2567 err = tool->time_conv(tool, session, event); 2568 break; 2569 case PERF_RECORD_HEADER_FEATURE: 2570 err = tool->feature(tool, session, event); 2571 break; 2572 case PERF_RECORD_COMPRESSED: 2573 case PERF_RECORD_COMPRESSED2: 2574 err = tool->compressed(tool, session, event, file_offset, file_path); 2575 if (err) 2576 dump_event(session->evlist, event, file_offset, &sample, file_path); 2577 break; 2578 case PERF_RECORD_FINISHED_INIT: 2579 err = tool->finished_init(tool, session, event); 2580 break; 2581 case PERF_RECORD_BPF_METADATA: { 2582 u64 nr_entries, max_entries; 2583 2584 if (event_size < sizeof(event->bpf_metadata)) { 2585 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_BPF_METADATA: header.size (%u) too small, skipping\n", 2586 file_offset, event_size); 2587 err = 0; 2588 break; 2589 } 2590 2591 /* 2592 * Native-endian files are mmap'd read-only — validate 2593 * NUL-termination instead of writing. 2594 */ 2595 if (strnlen(event->bpf_metadata.prog_name, 2596 BPF_PROG_NAME_LEN) == BPF_PROG_NAME_LEN) { 2597 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_BPF_METADATA: prog_name not null-terminated, skipping\n", 2598 file_offset); 2599 err = 0; 2600 break; 2601 } 2602 2603 nr_entries = READ_ONCE(event->bpf_metadata.nr_entries); 2604 max_entries = (event_size - sizeof(event->bpf_metadata)) / 2605 sizeof(event->bpf_metadata.entries[0]); 2606 if (nr_entries > max_entries) { 2607 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_BPF_METADATA: nr_entries %" PRIu64 " exceeds max %" PRIu64 ", skipping\n", 2608 file_offset, nr_entries, max_entries); 2609 err = 0; 2610 break; 2611 } 2612 2613 for (u64 i = 0; i < nr_entries; i++) { 2614 if (strnlen(event->bpf_metadata.entries[i].key, 2615 BPF_METADATA_KEY_LEN) == BPF_METADATA_KEY_LEN || 2616 strnlen(event->bpf_metadata.entries[i].value, 2617 BPF_METADATA_VALUE_LEN) == BPF_METADATA_VALUE_LEN) { 2618 pr_warning("WARNING: at offset %#" PRIx64 ": PERF_RECORD_BPF_METADATA: entry %" PRIu64 " key/value not null-terminated, skipping\n", 2619 file_offset, i); 2620 err = 0; 2621 goto out; 2622 } 2623 } 2624 2625 err = tool->bpf_metadata(tool, session, event); 2626 break; 2627 } 2628 case PERF_RECORD_SCHEDSTAT_CPU: 2629 err = tool->schedstat_cpu(tool, session, event); 2630 break; 2631 case PERF_RECORD_SCHEDSTAT_DOMAIN: 2632 err = tool->schedstat_domain(tool, session, event); 2633 break; 2634 default: 2635 err = -EINVAL; 2636 break; 2637 } 2638 out: 2639 perf_sample__exit(&sample); 2640 return err; 2641 } 2642 2643 int perf_session__deliver_synth_event(struct perf_session *session, 2644 union perf_event *event, 2645 struct perf_sample *sample) 2646 { 2647 struct evlist *evlist = session->evlist; 2648 const struct perf_tool *tool = session->tool; 2649 2650 events_stats__inc(evlist__stats(evlist), event->header.type); 2651 2652 if (event->header.type >= PERF_RECORD_USER_TYPE_START) 2653 return perf_session__process_user_event(session, event, 0, NULL); 2654 2655 return machines__deliver_event(&session->machines, evlist, event, sample, tool, 0, NULL); 2656 } 2657 2658 int perf_session__deliver_synth_attr_event(struct perf_session *session, 2659 const struct perf_event_attr *attr, 2660 u64 id) 2661 { 2662 union { 2663 struct { 2664 struct perf_record_header_attr attr; 2665 u64 ids[1]; 2666 } attr_id; 2667 union perf_event ev; 2668 } ev = { 2669 .attr_id.attr.header.type = PERF_RECORD_HEADER_ATTR, 2670 .attr_id.attr.header.size = sizeof(ev.attr_id), 2671 .attr_id.ids[0] = id, 2672 }; 2673 2674 if (attr->size != sizeof(ev.attr_id.attr.attr)) { 2675 pr_debug("Unexpected perf_event_attr size\n"); 2676 return -EINVAL; 2677 } 2678 ev.attr_id.attr.attr = *attr; 2679 return perf_session__deliver_synth_event(session, &ev.ev, NULL); 2680 } 2681 2682 /* Caller must ensure event->header.type < PERF_RECORD_HEADER_MAX */ 2683 static int event_swap(union perf_event *event, bool sample_id_all) 2684 { 2685 perf_event__swap_op swap = perf_event__swap_ops[event->header.type]; 2686 2687 if (swap) 2688 return swap(event, sample_id_all); 2689 return 0; 2690 } 2691 2692 /* 2693 * Minimum event sizes indexed by type. Checked before swap and 2694 * processing so that both cross-endian and native-endian paths 2695 * are protected from accessing fields past the event boundary. 2696 * Zero means no minimum beyond the 8-byte header (already 2697 * enforced by the reader). 2698 * 2699 * These values represent the smallest event the kernel has ever 2700 * emitted for each type, so they do not reject legitimate legacy 2701 * perf.data files from older kernels. Variable-length events 2702 * use offsetof() to the first variable field; the variable 2703 * content is validated separately (e.g., perf_event__check_nul). 2704 */ 2705 static const u32 perf_event__min_size[PERF_RECORD_HEADER_MAX] = { 2706 /* 2707 * offsetof() + 1 for types with a trailing variable-length 2708 * string (filename, comm, path, name, msg): the +1 ensures 2709 * room for at least a null terminator. Full null-termination 2710 * within the event boundary is checked separately. 2711 * 2712 * PERF_RECORD_SAMPLE is omitted: all64_swap is bounded by 2713 * header.size, and the internal layout varies by sample_type 2714 * so a fixed minimum is not meaningful. 2715 */ 2716 [PERF_RECORD_MMAP] = offsetof(struct perf_record_mmap, filename) + 1, 2717 [PERF_RECORD_LOST] = sizeof(struct perf_record_lost), 2718 [PERF_RECORD_COMM] = offsetof(struct perf_record_comm, comm) + 1, 2719 [PERF_RECORD_EXIT] = sizeof(struct perf_record_fork), 2720 [PERF_RECORD_THROTTLE] = sizeof(struct perf_record_throttle), 2721 [PERF_RECORD_UNTHROTTLE] = sizeof(struct perf_record_throttle), 2722 [PERF_RECORD_FORK] = sizeof(struct perf_record_fork), 2723 /* 2724 * The kernel dynamically sizes PERF_RECORD_READ based on 2725 * attr.read_format — only the enabled fields are emitted, 2726 * packed with no gaps. The minimum valid event has just 2727 * pid + tid + one u64 value (no optional fields). 2728 */ 2729 [PERF_RECORD_READ] = offsetof(struct perf_record_read, time_enabled), 2730 [PERF_RECORD_MMAP2] = offsetof(struct perf_record_mmap2, filename) + 1, 2731 [PERF_RECORD_LOST_SAMPLES] = sizeof(struct perf_record_lost_samples), 2732 [PERF_RECORD_AUX] = sizeof(struct perf_record_aux), 2733 [PERF_RECORD_ITRACE_START] = sizeof(struct perf_record_itrace_start), 2734 [PERF_RECORD_SWITCH] = sizeof(struct perf_event_header), 2735 [PERF_RECORD_SWITCH_CPU_WIDE] = sizeof(struct perf_record_switch), 2736 [PERF_RECORD_NAMESPACES] = sizeof(struct perf_record_namespaces), 2737 [PERF_RECORD_CGROUP] = offsetof(struct perf_record_cgroup, path) + 1, 2738 [PERF_RECORD_TEXT_POKE] = sizeof(struct perf_record_text_poke_event), 2739 [PERF_RECORD_KSYMBOL] = offsetof(struct perf_record_ksymbol, name) + 1, 2740 [PERF_RECORD_BPF_EVENT] = sizeof(struct perf_record_bpf_event), 2741 [PERF_RECORD_HEADER_ATTR] = sizeof(struct perf_event_header) + PERF_ATTR_SIZE_VER0, 2742 [PERF_RECORD_HEADER_EVENT_TYPE] = sizeof(struct perf_record_header_event_type), 2743 /* Legacy events predate the __u32 pad field, accept 12-byte records */ 2744 [PERF_RECORD_HEADER_TRACING_DATA] = offsetof(struct perf_record_header_tracing_data, pad), 2745 [PERF_RECORD_AUX_OUTPUT_HW_ID] = sizeof(struct perf_record_aux_output_hw_id), 2746 [PERF_RECORD_AUXTRACE_INFO] = sizeof(struct perf_record_auxtrace_info), 2747 [PERF_RECORD_AUXTRACE] = sizeof(struct perf_record_auxtrace), 2748 [PERF_RECORD_AUXTRACE_ERROR] = offsetof(struct perf_record_auxtrace_error, msg) + 1, 2749 [PERF_RECORD_THREAD_MAP] = sizeof(struct perf_record_thread_map), 2750 /* 2751 * sizeof(perf_record_cpu_map) is 20 because the outer struct 2752 * isn't packed and GCC adds 2 bytes of trailing padding. 2753 * The smallest valid variant (RANGE_CPUS) is only 16 bytes: 2754 * header(8) + type(2) + range_cpu_data(6). Per-variant 2755 * bounds are checked in the swap handler via payload. 2756 */ 2757 [PERF_RECORD_CPU_MAP] = sizeof(struct perf_event_header) + 2758 sizeof(__u16) + 2759 sizeof(struct perf_record_range_cpu_map), 2760 [PERF_RECORD_STAT_CONFIG] = sizeof(struct perf_record_stat_config), 2761 [PERF_RECORD_STAT] = sizeof(struct perf_record_stat), 2762 [PERF_RECORD_STAT_ROUND] = sizeof(struct perf_record_stat_round), 2763 /* 2764 * EVENT_UPDATE has a union whose largest member (cpus) 2765 * inflates sizeof to 40, but SCALE events are only 32 2766 * and UNIT/NAME events can be even smaller. Use the 2767 * fixed header fields (header + type + id) as minimum. 2768 */ 2769 [PERF_RECORD_EVENT_UPDATE] = offsetof(struct perf_record_event_update, scale), 2770 [PERF_RECORD_TIME_CONV] = offsetof(struct perf_record_time_conv, time_cycles), 2771 [PERF_RECORD_ID_INDEX] = sizeof(struct perf_record_id_index), 2772 [PERF_RECORD_HEADER_BUILD_ID] = sizeof(struct perf_record_header_build_id), 2773 [PERF_RECORD_HEADER_FEATURE] = sizeof(struct perf_record_header_feature), 2774 [PERF_RECORD_COMPRESSED2] = sizeof(struct perf_record_compressed2), 2775 [PERF_RECORD_BPF_METADATA] = sizeof(struct perf_record_bpf_metadata), 2776 [PERF_RECORD_CALLCHAIN_DEFERRED] = sizeof(struct perf_event_header) + sizeof(__u64), 2777 /* 2778 * SCHEDSTAT events have a version-dependent union after the 2779 * fixed header fields; the minimum is the base (pre-union) 2780 * portion so old and new versions both pass. 2781 */ 2782 [PERF_RECORD_SCHEDSTAT_CPU] = offsetof(struct perf_record_schedstat_cpu, v15), 2783 [PERF_RECORD_SCHEDSTAT_DOMAIN] = offsetof(struct perf_record_schedstat_domain, v15), 2784 }; 2785 2786 /* 2787 * Return true if the event is too small for its declared type. 2788 * Caller must ensure event->header.type < PERF_RECORD_HEADER_MAX. 2789 * If min is non-NULL, stores the required minimum on failure. 2790 */ 2791 bool perf_event__too_small(const union perf_event *event, u32 *min) 2792 { 2793 u32 min_sz = perf_event__min_size[event->header.type]; 2794 2795 if (min_sz && event->header.size < min_sz) { 2796 if (min) 2797 *min = min_sz; 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 /* 2805 * Read and validate the event at @file_offset. 2806 * 2807 * Returns: 2808 * 0 — success: *event_ptr is set and safe to access. 2809 * -1 — error; check *event_ptr to decide whether to advance or abort: 2810 * *event_ptr set — event header was read but the event is 2811 * malformed (too small for its type, or byte-swap 2812 * failed). header.size is still valid, so the 2813 * caller can advance past the event. 2814 * *event_ptr NULL — fatal: couldn't read the header at all 2815 * (I/O error, offset out of range, pipe mode). 2816 * Caller must abort. 2817 */ 2818 int perf_session__peek_event(struct perf_session *session, off_t file_offset, 2819 void *buf, size_t buf_sz, 2820 union perf_event **event_ptr, 2821 struct perf_sample *sample) 2822 { 2823 union perf_event *event; 2824 size_t hdr_sz, rest; 2825 u32 min_sz; 2826 int fd; 2827 2828 *event_ptr = NULL; 2829 2830 if (session->one_mmap && !session->header.needs_swap) { 2831 u64 offset_in_mmap; 2832 2833 /* Validate offset with integer arithmetic to avoid pointer UB */ 2834 if ((u64)file_offset < session->one_mmap_offset) 2835 return -1; 2836 2837 offset_in_mmap = (u64)file_offset - session->one_mmap_offset; 2838 2839 /* Use subtraction to avoid addition overflow */ 2840 if (offset_in_mmap >= session->one_mmap_size || 2841 session->one_mmap_size - offset_in_mmap < sizeof(struct perf_event_header)) 2842 return -1; 2843 2844 event = session->one_mmap_addr + offset_in_mmap; 2845 2846 if (event->header.size < sizeof(struct perf_event_header)) 2847 return -1; 2848 2849 /* Ensure full event is within the mmap region */ 2850 if (session->one_mmap_size - offset_in_mmap < event->header.size) 2851 return -1; 2852 } else { 2853 if (perf_data__is_pipe(session->data)) 2854 return -1; 2855 2856 fd = perf_data__fd(session->data); 2857 hdr_sz = sizeof(struct perf_event_header); 2858 2859 if (buf_sz < hdr_sz) 2860 return -1; 2861 2862 if (lseek(fd, file_offset, SEEK_SET) == (off_t)-1 || 2863 readn(fd, buf, hdr_sz) != (ssize_t)hdr_sz) 2864 return -1; 2865 2866 event = (union perf_event *)buf; 2867 2868 if (session->header.needs_swap) 2869 perf_event_header__bswap(&event->header); 2870 2871 if (event->header.size < hdr_sz || event->header.size > buf_sz) 2872 return -1; 2873 2874 buf += hdr_sz; 2875 rest = event->header.size - hdr_sz; 2876 2877 if (readn(fd, buf, rest) != (ssize_t)rest) 2878 return -1; 2879 } 2880 2881 /* Event data is fully loaded — expose so callers can advance */ 2882 *event_ptr = event; 2883 2884 /* 2885 * Check alignment before type: an unaligned size misaligns the 2886 * stream for all subsequent reads regardless of event type. 2887 * Three legacy user events predate the 8-byte rule — exempt them. 2888 */ 2889 if (event->header.size % sizeof(u64) && 2890 event->header.type != PERF_RECORD_HEADER_TRACING_DATA && 2891 event->header.type != PERF_RECORD_COMPRESSED && 2892 event->header.type != PERF_RECORD_HEADER_FEATURE) { 2893 pr_warning("WARNING: at offset %#" PRIx64 ": %s (%u) event size %u not aligned to %zu\n", 2894 (u64)file_offset, perf_event__name(event->header.type), 2895 event->header.type, event->header.size, sizeof(u64)); 2896 return -1; 2897 } 2898 2899 if (event->header.type >= PERF_RECORD_HEADER_MAX) { 2900 pr_warning("WARNING: at offset %#" PRIx64 ": unsupported event type %u, skipping\n", 2901 (u64)file_offset, event->header.type); 2902 return 0; 2903 } 2904 2905 if (perf_event__too_small(event, &min_sz)) { 2906 pr_warning("WARNING: at offset %#" PRIx64 ": %s (%u) event size %u too small (min %u)\n", 2907 (u64)file_offset, perf_event__name(event->header.type), 2908 event->header.type, event->header.size, min_sz); 2909 return -1; 2910 } 2911 2912 if (session->header.needs_swap && 2913 event_swap(event, evlist__sample_id_all(session->evlist))) { 2914 /* 2915 * The header was already swapped so header.size is 2916 * valid — expose the event so callers can advance 2917 * past this malformed entry instead of aborting. 2918 */ 2919 *event_ptr = event; 2920 return -1; 2921 } 2922 2923 if (sample && event->header.type < PERF_RECORD_USER_TYPE_START && 2924 evlist__parse_sample(session->evlist, event, sample)) 2925 return -1; 2926 2927 return 0; 2928 } 2929 2930 int perf_session__peek_events(struct perf_session *session, u64 offset, 2931 u64 size, peek_events_cb_t cb, void *data) 2932 { 2933 u64 max_offset = offset + size; 2934 char buf[PERF_SAMPLE_MAX_SIZE]; 2935 union perf_event *event; 2936 int err; 2937 2938 do { 2939 event = NULL; 2940 err = perf_session__peek_event(session, offset, buf, 2941 PERF_SAMPLE_MAX_SIZE, &event, 2942 NULL); 2943 if (err) { 2944 /* 2945 * Recoverable error: peek_event returns -1 but 2946 * sets event_ptr when the header was read 2947 * successfully but the event is malformed (too 2948 * small or swap failed). Skip past it using 2949 * header.size — don't invoke the callback since 2950 * type-specific fields may be truncated. 2951 * 2952 * Must abort if: event_ptr is NULL (I/O error), 2953 * size is 0 (can't advance), type is AUXTRACE 2954 * (payload extends beyond header.size), or size 2955 * is unaligned (would misalign all subsequent reads). 2956 * 2957 * Direct callers (auxtrace, cs-etm) treat any 2958 * non-zero return as fatal — only this loop skips. 2959 */ 2960 if (event && event->header.size && 2961 event->header.type != PERF_RECORD_AUXTRACE && 2962 event->header.size % sizeof(u64) == 0) { 2963 offset += event->header.size; 2964 err = 0; 2965 } else { 2966 return err; 2967 } 2968 continue; 2969 } 2970 2971 err = cb(session, event, offset, data); 2972 if (err) 2973 return err; 2974 2975 offset += event->header.size; 2976 if (event->header.type == PERF_RECORD_AUXTRACE) 2977 offset += event->auxtrace.size; 2978 2979 } while (offset < max_offset); 2980 2981 return err; 2982 } 2983 2984 static s64 perf_session__process_event(struct perf_session *session, 2985 union perf_event *event, u64 file_offset, 2986 const char *file_path) 2987 { 2988 struct evlist *evlist = session->evlist; 2989 const struct perf_tool *tool = session->tool; 2990 u32 min_sz; 2991 int ret; 2992 2993 /* 2994 * The kernel aligns all event sizes to sizeof(u64) — see 2995 * perf_event_comm_event() (ALIGN), perf_event_mmap_event(), 2996 * perf_event_cgroup(), perf_event_ksymbol() (IS_ALIGNED loops), 2997 * and perf_event_text_poke() (ALIGN) in kernel/events/core.c. 2998 * 2999 * An unaligned size means the file is corrupted or crafted. 3000 * Abort: there is no point continuing to read unaligned records 3001 * because the caller advances rd->head by event->header.size, 3002 * so every subsequent read would start at a misaligned offset, 3003 * producing garbage headers for the rest of the file. 3004 * 3005 * Exempt three legacy user events that predate the alignment rule: 3006 * 3007 * TRACING_DATA (66): struct tracing_data_event was 12 bytes before 3008 * b39c915a4f36 ("libperf event: Ensure tracing data is multiple 3009 * of 8 sized") added __u32 pad; old perf.data files still contain 3010 * 12-byte records. 3011 * TODO: introduce HEADER_TRACING_DATA2 with guaranteed alignment. 3012 * 3013 * COMPRESSED (81): raw ZSTD output, arbitrary length. Already 3014 * superseded by COMPRESSED2 (83) with PERF_ALIGN. 3015 * 3016 * HEADER_FEATURE (80): do_write_string() uses a 4-byte length 3017 * prefix with no padding to 8-byte total. 3018 * TODO: introduce HEADER_FEATURE2 with guaranteed alignment. 3019 */ 3020 if (event->header.size % sizeof(u64) && 3021 event->header.type != PERF_RECORD_HEADER_TRACING_DATA && 3022 event->header.type != PERF_RECORD_COMPRESSED && 3023 event->header.type != PERF_RECORD_HEADER_FEATURE) { 3024 pr_err("ERROR: at offset %#" PRIx64 ": %s (%u) event size %u is not 8-byte aligned, aborting\n", 3025 file_offset, perf_event__name(event->header.type), 3026 event->header.type, event->header.size); 3027 return -EINVAL; 3028 } 3029 3030 if (event->header.type >= PERF_RECORD_HEADER_MAX) { 3031 /* This perf is outdated and does not support the latest event type. */ 3032 ui__warning("Unsupported header type %u, please consider updating perf.\n", 3033 event->header.type); 3034 /* 3035 * Return 0 to skip: the caller (reader__read_event) 3036 * already advances by event->header.size. 3037 */ 3038 return 0; 3039 } 3040 3041 /* 3042 * Skip rather than abort: a too-small-but-aligned event 3043 * can be safely stepped over without misaligning the stream. 3044 */ 3045 if (perf_event__too_small(event, &min_sz)) { 3046 pr_warning("WARNING: at offset %#" PRIx64 ": %s (%u) event size %u too small (min %u), skipping\n", 3047 file_offset, perf_event__name(event->header.type), 3048 event->header.type, event->header.size, min_sz); 3049 return 0; 3050 } 3051 3052 if (session->header.needs_swap && 3053 event_swap(event, evlist__sample_id_all(evlist))) { 3054 pr_warning("WARNING: at offset %#" PRIx64 ": swap failed for %s (%u) event, skipping\n", 3055 file_offset, perf_event__name(event->header.type), 3056 event->header.type); 3057 return 0; 3058 } 3059 3060 events_stats__inc(evlist__stats(evlist), event->header.type); 3061 3062 if (event->header.type >= PERF_RECORD_USER_TYPE_START) 3063 return perf_session__process_user_event(session, event, file_offset, file_path); 3064 3065 if (tool->ordered_events) { 3066 u64 timestamp = -1ULL; 3067 3068 ret = evlist__parse_sample_timestamp(evlist, event, ×tamp); 3069 if (ret && ret != -1) 3070 return ret; 3071 3072 ret = perf_session__queue_event(session, event, timestamp, file_offset, file_path); 3073 if (ret != -ETIME) 3074 return ret; 3075 } 3076 3077 return perf_session__deliver_event(session, event, tool, file_offset, file_path); 3078 } 3079 3080 void perf_event_header__bswap(struct perf_event_header *hdr) 3081 { 3082 hdr->type = bswap_32(hdr->type); 3083 hdr->misc = bswap_16(hdr->misc); 3084 hdr->size = bswap_16(hdr->size); 3085 } 3086 3087 struct thread *perf_session__findnew(struct perf_session *session, pid_t pid) 3088 { 3089 return machine__findnew_thread(&session->machines.host, -1, pid); 3090 } 3091 3092 int perf_session__register_idle_thread(struct perf_session *session) 3093 { 3094 struct thread *thread = machine__idle_thread(&session->machines.host); 3095 3096 /* machine__idle_thread() got the thread, so put it */ 3097 thread__put(thread); 3098 return thread ? 0 : -1; 3099 } 3100 3101 static void 3102 perf_session__warn_order(const struct perf_session *session) 3103 { 3104 const struct ordered_events *oe = &session->ordered_events; 3105 struct evsel *evsel; 3106 bool should_warn = true; 3107 3108 evlist__for_each_entry(session->evlist, evsel) { 3109 if (evsel->core.attr.write_backward) 3110 should_warn = false; 3111 } 3112 3113 if (!should_warn) 3114 return; 3115 if (oe->nr_unordered_events != 0) 3116 ui__warning("%u out of order events recorded.\n", oe->nr_unordered_events); 3117 } 3118 3119 static void perf_session__warn_about_errors(const struct perf_session *session) 3120 { 3121 const struct events_stats *stats = evlist__stats(session->evlist); 3122 3123 if (session->tool->lost == perf_event__process_lost && 3124 stats->nr_events[PERF_RECORD_LOST] != 0) { 3125 ui__warning("Processed %d events and lost %d chunks!\n\n" 3126 "Check IO/CPU overload!\n\n", 3127 stats->nr_events[0], 3128 stats->nr_events[PERF_RECORD_LOST]); 3129 } 3130 3131 if (session->tool->lost_samples == perf_event__process_lost_samples) { 3132 double drop_rate; 3133 3134 drop_rate = (double)stats->total_lost_samples / 3135 (double) (stats->nr_events[PERF_RECORD_SAMPLE] + stats->total_lost_samples); 3136 if (drop_rate > 0.05) { 3137 ui__warning("Processed %" PRIu64 " samples and lost %3.2f%%!\n\n", 3138 stats->nr_events[PERF_RECORD_SAMPLE] + stats->total_lost_samples, 3139 drop_rate * 100.0); 3140 } 3141 } 3142 3143 if (session->tool->aux == perf_event__process_aux && 3144 stats->total_aux_lost != 0) { 3145 ui__warning("AUX data lost %" PRIu64 " times out of %u!\n\n", 3146 stats->total_aux_lost, 3147 stats->nr_events[PERF_RECORD_AUX]); 3148 } 3149 3150 if (session->tool->aux == perf_event__process_aux && 3151 stats->total_aux_partial != 0) { 3152 bool vmm_exclusive = false; 3153 3154 (void)sysfs__read_bool("module/kvm_intel/parameters/vmm_exclusive", 3155 &vmm_exclusive); 3156 3157 ui__warning("AUX data had gaps in it %" PRIu64 " times out of %u!\n\n" 3158 "Are you running a KVM guest in the background?%s\n\n", 3159 stats->total_aux_partial, 3160 stats->nr_events[PERF_RECORD_AUX], 3161 vmm_exclusive ? 3162 "\nReloading kvm_intel module with vmm_exclusive=0\n" 3163 "will reduce the gaps to only guest's timeslices." : 3164 ""); 3165 } 3166 3167 if (session->tool->aux == perf_event__process_aux && 3168 stats->total_aux_collision != 0) { 3169 ui__warning("AUX data detected collision %" PRIu64 " times out of %u!\n\n", 3170 stats->total_aux_collision, 3171 stats->nr_events[PERF_RECORD_AUX]); 3172 } 3173 3174 if (stats->nr_unknown_events != 0) { 3175 ui__warning("Found %u unknown events!\n\n" 3176 "Is this an older tool processing a perf.data " 3177 "file generated by a more recent tool?\n\n" 3178 "If that is not the case, consider " 3179 "reporting to linux-kernel@vger.kernel.org.\n\n", 3180 stats->nr_unknown_events); 3181 } 3182 3183 if (stats->nr_unknown_id != 0) { 3184 ui__warning("%u samples with id not present in the header\n", 3185 stats->nr_unknown_id); 3186 } 3187 3188 if (stats->nr_invalid_chains != 0) { 3189 ui__warning("Found invalid callchains!\n\n" 3190 "%u out of %u events were discarded for this reason.\n\n" 3191 "Consider reporting to linux-kernel@vger.kernel.org.\n\n", 3192 stats->nr_invalid_chains, 3193 stats->nr_events[PERF_RECORD_SAMPLE]); 3194 } 3195 3196 if (stats->nr_unprocessable_samples != 0) { 3197 ui__warning("%u unprocessable samples recorded.\n" 3198 "Do you have a KVM guest running and not using 'perf kvm'?\n", 3199 stats->nr_unprocessable_samples); 3200 } 3201 3202 perf_session__warn_order(session); 3203 3204 events_stats__auxtrace_error_warn(stats); 3205 3206 if (stats->nr_proc_map_timeout != 0) { 3207 ui__warning("%d map information files for pre-existing threads were\n" 3208 "not processed, if there are samples for addresses they\n" 3209 "will not be resolved, you may find out which are these\n" 3210 "threads by running with -v and redirecting the output\n" 3211 "to a file.\n" 3212 "The time limit to process proc map is too short?\n" 3213 "Increase it by --proc-map-timeout\n", 3214 stats->nr_proc_map_timeout); 3215 } 3216 } 3217 3218 static int perf_session__flush_thread_stack(struct thread *thread, 3219 void *p __maybe_unused) 3220 { 3221 return thread_stack__flush(thread); 3222 } 3223 3224 static int perf_session__flush_thread_stacks(struct perf_session *session) 3225 { 3226 return machines__for_each_thread(&session->machines, 3227 perf_session__flush_thread_stack, 3228 NULL); 3229 } 3230 3231 volatile sig_atomic_t session_done; 3232 3233 static int __perf_session__process_decomp_events(struct perf_session *session); 3234 3235 static int __perf_session__process_pipe_events(struct perf_session *session) 3236 { 3237 struct ordered_events *oe = &session->ordered_events; 3238 const struct perf_tool *tool = session->tool; 3239 struct ui_progress prog; 3240 union perf_event *event; 3241 uint32_t size, cur_size = 0; 3242 void *buf = NULL; 3243 s64 skip = 0; 3244 u64 head; 3245 ssize_t err; 3246 void *p; 3247 bool update_prog = false; 3248 3249 /* 3250 * If it's from a file saving pipe data (by redirection), it would have 3251 * a file name other than "-". Then we can get the total size and show 3252 * the progress. 3253 */ 3254 if (strcmp(session->data->path, "-") && session->data->file.size) { 3255 ui_progress__init_size(&prog, session->data->file.size, 3256 "Processing events..."); 3257 update_prog = true; 3258 } 3259 3260 head = 0; 3261 cur_size = sizeof(union perf_event); 3262 3263 buf = malloc(cur_size); 3264 if (!buf) { 3265 err = -errno; 3266 if (update_prog) 3267 ui_progress__finish(); 3268 return err; 3269 } 3270 ordered_events__set_copy_on_queue(oe, true); 3271 more: 3272 event = buf; 3273 err = perf_data__read(session->data, event, 3274 sizeof(struct perf_event_header)); 3275 if (err <= 0) { 3276 if (err == 0) 3277 goto done; 3278 3279 pr_err("failed to read event header\n"); 3280 goto out_err; 3281 } 3282 3283 if (session->header.needs_swap) 3284 perf_event_header__bswap(&event->header); 3285 3286 size = event->header.size; 3287 if (size < sizeof(struct perf_event_header)) { 3288 pr_err("bad event header size\n"); 3289 goto out_err; 3290 } 3291 3292 if (size > cur_size) { 3293 void *new = realloc(buf, size); 3294 if (!new) { 3295 pr_err("failed to allocate memory to read event\n"); 3296 goto out_err; 3297 } 3298 buf = new; 3299 cur_size = size; 3300 event = buf; 3301 } 3302 p = event; 3303 p += sizeof(struct perf_event_header); 3304 3305 if (size - sizeof(struct perf_event_header)) { 3306 err = perf_data__read(session->data, p, 3307 size - sizeof(struct perf_event_header)); 3308 if (err <= 0) { 3309 if (err == 0) { 3310 pr_err("unexpected end of event stream\n"); 3311 goto done; 3312 } 3313 3314 pr_err("failed to read event data\n"); 3315 goto out_err; 3316 } 3317 } 3318 3319 if ((skip = perf_session__process_event(session, event, head, "pipe")) < 0) { 3320 pr_err("%#" PRIx64 " [%#x]: piped event processing failed for event of type: %s (%d)\n", 3321 head, event->header.size, 3322 perf_event__name(event->header.type), 3323 event->header.type); 3324 err = -EINVAL; 3325 goto out_err; 3326 } 3327 3328 head += size; 3329 3330 if (skip > 0) 3331 head += skip; 3332 3333 err = __perf_session__process_decomp_events(session); 3334 if (err) 3335 goto out_err; 3336 3337 if (update_prog) 3338 ui_progress__update(&prog, size); 3339 3340 if (!session_done()) 3341 goto more; 3342 done: 3343 /* do the final flush for ordered samples */ 3344 err = ordered_events__flush(oe, OE_FLUSH__FINAL); 3345 if (err) 3346 goto out_err; 3347 err = session__flush_deferred_samples(session, tool); 3348 if (err) 3349 goto out_err; 3350 err = auxtrace__flush_events(session, tool); 3351 if (err) 3352 goto out_err; 3353 err = perf_session__flush_thread_stacks(session); 3354 out_err: 3355 free(buf); 3356 if (update_prog) 3357 ui_progress__finish(); 3358 if (!tool->no_warn) 3359 perf_session__warn_about_errors(session); 3360 ordered_events__free(&session->ordered_events); 3361 auxtrace__free_events(session); 3362 return err; 3363 } 3364 3365 static union perf_event * 3366 prefetch_event(char *buf, u64 head, size_t mmap_size, 3367 bool needs_swap, union perf_event *error) 3368 { 3369 union perf_event *event; 3370 u16 event_size; 3371 3372 /* 3373 * Ensure we have enough space remaining to read 3374 * the size of the event in the headers. 3375 */ 3376 if (head + sizeof(event->header) > mmap_size) 3377 return NULL; 3378 3379 event = (union perf_event *)(buf + head); 3380 if (needs_swap) 3381 perf_event_header__bswap(&event->header); 3382 3383 event_size = event->header.size; 3384 if (head + event_size <= mmap_size) 3385 return event; 3386 3387 /* We're not fetching the event so swap back again */ 3388 if (needs_swap) 3389 perf_event_header__bswap(&event->header); 3390 3391 /* Check if the event fits into the next mmapped buf. */ 3392 if (event_size <= mmap_size - head % page_size) { 3393 /* Remap buf and fetch again. */ 3394 return NULL; 3395 } 3396 3397 /* Invalid input. Event size should never exceed mmap_size. */ 3398 pr_debug("%s: head=%#" PRIx64 " event->header.size=%#x, mmap_size=%#zx:" 3399 " fuzzed or compressed perf.data?\n", __func__, head, event_size, mmap_size); 3400 3401 return error; 3402 } 3403 3404 static union perf_event * 3405 fetch_mmaped_event(u64 head, size_t mmap_size, char *buf, bool needs_swap) 3406 { 3407 return prefetch_event(buf, head, mmap_size, needs_swap, ERR_PTR(-EINVAL)); 3408 } 3409 3410 static union perf_event * 3411 fetch_decomp_event(u64 head, size_t mmap_size, char *buf, bool needs_swap) 3412 { 3413 return prefetch_event(buf, head, mmap_size, needs_swap, NULL); 3414 } 3415 3416 static int __perf_session__process_decomp_events(struct perf_session *session) 3417 { 3418 s64 skip; 3419 u64 size; 3420 struct decomp *decomp = session->active_decomp->decomp_last; 3421 3422 if (!decomp) 3423 return 0; 3424 3425 while (decomp->head < decomp->size && !session_done()) { 3426 union perf_event *event = fetch_decomp_event(decomp->head, decomp->size, decomp->data, 3427 session->header.needs_swap); 3428 3429 if (!event) 3430 break; 3431 3432 size = event->header.size; 3433 3434 if (size < sizeof(struct perf_event_header) || 3435 (skip = perf_session__process_event(session, event, decomp->file_pos, 3436 decomp->file_path)) < 0) { 3437 pr_err("%#" PRIx64 " [%#x]: decompress event processing failed for event of type: %s (%d)\n", 3438 decomp->file_pos + decomp->head, event->header.size, 3439 perf_event__name(event->header.type), 3440 event->header.type); 3441 return -EINVAL; 3442 } 3443 3444 if (skip) 3445 size += skip; 3446 3447 decomp->head += size; 3448 } 3449 3450 return 0; 3451 } 3452 3453 /* 3454 * On 64bit we can mmap the data file in one go. No need for tiny mmap 3455 * slices. On 32bit we use 32MB. 3456 */ 3457 #if BITS_PER_LONG == 64 3458 #define MMAP_SIZE ULLONG_MAX 3459 #define NUM_MMAPS 1 3460 #else 3461 #define MMAP_SIZE (32 * 1024 * 1024ULL) 3462 #define NUM_MMAPS 128 3463 #endif 3464 3465 struct reader; 3466 3467 typedef s64 (*reader_cb_t)(struct perf_session *session, 3468 union perf_event *event, 3469 u64 file_offset, 3470 const char *file_path); 3471 3472 struct reader { 3473 int fd; 3474 const char *path; 3475 u64 data_size; 3476 u64 data_offset; 3477 reader_cb_t process; 3478 bool in_place_update; 3479 char *mmaps[NUM_MMAPS]; 3480 size_t mmap_size; 3481 int mmap_idx; 3482 char *mmap_cur; 3483 u64 file_pos; 3484 u64 file_offset; 3485 u64 head; 3486 u64 size; 3487 bool done; 3488 struct zstd_data zstd_data; 3489 struct decomp_data decomp_data; 3490 }; 3491 3492 static int 3493 reader__init(struct reader *rd, bool *one_mmap) 3494 { 3495 u64 data_size = rd->data_size; 3496 char **mmaps = rd->mmaps; 3497 3498 rd->head = rd->data_offset; 3499 data_size += rd->data_offset; 3500 3501 rd->mmap_size = MMAP_SIZE; 3502 if (rd->mmap_size > data_size) { 3503 rd->mmap_size = data_size; 3504 if (one_mmap) 3505 *one_mmap = true; 3506 } 3507 3508 memset(mmaps, 0, sizeof(rd->mmaps)); 3509 3510 if (zstd_init(&rd->zstd_data, 0)) 3511 return -1; 3512 rd->decomp_data.zstd_decomp = &rd->zstd_data; 3513 3514 return 0; 3515 } 3516 3517 static void 3518 reader__release_decomp(struct reader *rd) 3519 { 3520 perf_decomp__release_events(rd->decomp_data.decomp); 3521 zstd_fini(&rd->zstd_data); 3522 } 3523 3524 static int 3525 reader__mmap(struct reader *rd, struct perf_session *session) 3526 { 3527 int mmap_prot, mmap_flags; 3528 char *buf, **mmaps = rd->mmaps; 3529 u64 page_offset; 3530 3531 /* 3532 * Native-endian: MAP_SHARED + PROT_READ — the kernel 3533 * guarantees page-level coherence but a concurrent writer 3534 * could modify the file between validation and use. This 3535 * is a theoretical TOCTOU that affects the entire perf.data 3536 * processing pipeline; fixing it would require copying each 3537 * event to a private buffer before processing. 3538 * 3539 * Cross-endian: MAP_PRIVATE + PROT_WRITE — swap handlers 3540 * get a copy-on-write snapshot immune to concurrent writes. 3541 */ 3542 mmap_prot = PROT_READ; 3543 mmap_flags = MAP_SHARED; 3544 3545 if (rd->in_place_update) { 3546 mmap_prot |= PROT_WRITE; 3547 } else if (session->header.needs_swap) { 3548 mmap_prot |= PROT_WRITE; 3549 mmap_flags = MAP_PRIVATE; 3550 } 3551 3552 if (mmaps[rd->mmap_idx]) { 3553 munmap(mmaps[rd->mmap_idx], rd->mmap_size); 3554 mmaps[rd->mmap_idx] = NULL; 3555 } 3556 3557 page_offset = page_size * (rd->head / page_size); 3558 rd->file_offset += page_offset; 3559 rd->head -= page_offset; 3560 3561 buf = mmap(NULL, rd->mmap_size, mmap_prot, mmap_flags, rd->fd, 3562 rd->file_offset); 3563 if (buf == MAP_FAILED) { 3564 pr_err("failed to mmap file\n"); 3565 return -errno; 3566 } 3567 mmaps[rd->mmap_idx] = rd->mmap_cur = buf; 3568 rd->mmap_idx = (rd->mmap_idx + 1) & (ARRAY_SIZE(rd->mmaps) - 1); 3569 rd->file_pos = rd->file_offset + rd->head; 3570 if (session->one_mmap) { 3571 session->one_mmap_addr = buf; 3572 session->one_mmap_offset = rd->file_offset; 3573 /* 3574 * mmap_size was set to the full file extent (data_offset + 3575 * data_size) but file_offset was shifted forward by 3576 * page_offset for page alignment. Reduce by page_offset 3577 * so the bounds check reflects the file-backed portion 3578 * of the mapping — pages beyond the file cause SIGBUS. 3579 */ 3580 session->one_mmap_size = rd->mmap_size - page_offset; 3581 } 3582 3583 return 0; 3584 } 3585 3586 enum { 3587 READER_OK, 3588 READER_NODATA, 3589 }; 3590 3591 static int 3592 reader__read_event(struct reader *rd, struct perf_session *session, 3593 struct ui_progress *prog) 3594 { 3595 u64 size; 3596 int err = READER_OK; 3597 union perf_event *event; 3598 s64 skip; 3599 3600 event = fetch_mmaped_event(rd->head, rd->mmap_size, rd->mmap_cur, 3601 session->header.needs_swap); 3602 if (IS_ERR(event)) 3603 return PTR_ERR(event); 3604 3605 if (!event) 3606 return READER_NODATA; 3607 3608 size = event->header.size; 3609 3610 skip = -EINVAL; 3611 3612 if (size < sizeof(struct perf_event_header) || 3613 (skip = rd->process(session, event, rd->file_pos, rd->path)) < 0) { 3614 errno = -skip; 3615 pr_err("%#" PRIx64 " [%#x]: processing failed for event of type: %s (%d) [%m]\n", 3616 rd->file_offset + rd->head, event->header.size, 3617 perf_event__name(event->header.type), 3618 event->header.type); 3619 err = skip; 3620 goto out; 3621 } 3622 3623 if (skip) 3624 size += skip; 3625 3626 rd->size += size; 3627 rd->head += size; 3628 rd->file_pos += size; 3629 3630 err = __perf_session__process_decomp_events(session); 3631 if (err) 3632 goto out; 3633 3634 ui_progress__update(prog, size); 3635 3636 out: 3637 return err; 3638 } 3639 3640 static inline bool 3641 reader__eof(struct reader *rd) 3642 { 3643 return (rd->file_pos >= rd->data_size + rd->data_offset); 3644 } 3645 3646 static int 3647 reader__process_events(struct reader *rd, struct perf_session *session, 3648 struct ui_progress *prog) 3649 { 3650 int err; 3651 3652 err = reader__init(rd, &session->one_mmap); 3653 if (err) 3654 goto out; 3655 3656 session->active_decomp = &rd->decomp_data; 3657 3658 remap: 3659 err = reader__mmap(rd, session); 3660 if (err) 3661 goto out; 3662 3663 more: 3664 err = reader__read_event(rd, session, prog); 3665 if (err < 0) 3666 goto out; 3667 else if (err == READER_NODATA) 3668 goto remap; 3669 3670 if (session_done()) 3671 goto out; 3672 3673 if (!reader__eof(rd)) 3674 goto more; 3675 3676 out: 3677 session->active_decomp = &session->decomp_data; 3678 return err; 3679 } 3680 3681 static s64 process_simple(struct perf_session *session, 3682 union perf_event *event, 3683 u64 file_offset, 3684 const char *file_path) 3685 { 3686 return perf_session__process_event(session, event, file_offset, file_path); 3687 } 3688 3689 static int __perf_session__process_events(struct perf_session *session) 3690 { 3691 struct reader rd = { 3692 .fd = perf_data__fd(session->data), 3693 .path = session->data->file.path, 3694 .data_size = session->header.data_size, 3695 .data_offset = session->header.data_offset, 3696 .process = process_simple, 3697 .in_place_update = session->data->in_place_update, 3698 }; 3699 struct ordered_events *oe = &session->ordered_events; 3700 const struct perf_tool *tool = session->tool; 3701 struct ui_progress prog; 3702 int err; 3703 3704 if (rd.data_size == 0) 3705 return -1; 3706 3707 ui_progress__init_size(&prog, rd.data_size, "Processing events..."); 3708 3709 err = reader__process_events(&rd, session, &prog); 3710 if (err) 3711 goto out_err; 3712 /* do the final flush for ordered samples */ 3713 err = ordered_events__flush(oe, OE_FLUSH__FINAL); 3714 if (err) 3715 goto out_err; 3716 err = auxtrace__flush_events(session, tool); 3717 if (err) 3718 goto out_err; 3719 err = session__flush_deferred_samples(session, tool); 3720 if (err) 3721 goto out_err; 3722 err = perf_session__flush_thread_stacks(session); 3723 out_err: 3724 ui_progress__finish(); 3725 if (!tool->no_warn) 3726 perf_session__warn_about_errors(session); 3727 /* 3728 * We may switching perf.data output, make ordered_events 3729 * reusable. 3730 */ 3731 ordered_events__reinit(&session->ordered_events); 3732 auxtrace__free_events(session); 3733 reader__release_decomp(&rd); 3734 session->one_mmap = false; 3735 return err; 3736 } 3737 3738 /* 3739 * Processing 2 MB of data from each reader in sequence, 3740 * because that's the way the ordered events sorting works 3741 * most efficiently. 3742 */ 3743 #define READER_MAX_SIZE (2 * 1024 * 1024) 3744 3745 /* 3746 * This function reads, merge and process directory data. 3747 * It assumens the version 1 of directory data, where each 3748 * data file holds per-cpu data, already sorted by kernel. 3749 */ 3750 static int __perf_session__process_dir_events(struct perf_session *session) 3751 { 3752 struct perf_data *data = session->data; 3753 const struct perf_tool *tool = session->tool; 3754 int i, ret, readers, nr_readers; 3755 struct ui_progress prog; 3756 u64 total_size = perf_data__size(session->data); 3757 struct reader *rd; 3758 3759 ui_progress__init_size(&prog, total_size, "Processing events..."); 3760 3761 nr_readers = 1; 3762 for (i = 0; i < data->dir.nr; i++) { 3763 if (data->dir.files[i].size) 3764 nr_readers++; 3765 } 3766 3767 rd = calloc(nr_readers, sizeof(struct reader)); 3768 if (!rd) { 3769 ui_progress__finish(); 3770 return -ENOMEM; 3771 } 3772 3773 rd[0] = (struct reader) { 3774 .fd = perf_data__fd(session->data), 3775 .path = session->data->file.path, 3776 .data_size = session->header.data_size, 3777 .data_offset = session->header.data_offset, 3778 .process = process_simple, 3779 .in_place_update = session->data->in_place_update, 3780 }; 3781 ret = reader__init(&rd[0], NULL); 3782 if (ret) 3783 goto out_err; 3784 ret = reader__mmap(&rd[0], session); 3785 if (ret) 3786 goto out_err; 3787 readers = 1; 3788 3789 for (i = 0; i < data->dir.nr; i++) { 3790 if (!data->dir.files[i].size) 3791 continue; 3792 rd[readers] = (struct reader) { 3793 .fd = perf_data_file__fd(&data->dir.files[i]), 3794 .path = data->dir.files[i].path, 3795 .data_size = data->dir.files[i].size, 3796 .data_offset = 0, 3797 .process = process_simple, 3798 .in_place_update = session->data->in_place_update, 3799 }; 3800 ret = reader__init(&rd[readers], NULL); 3801 if (ret) 3802 goto out_err; 3803 ret = reader__mmap(&rd[readers], session); 3804 if (ret) 3805 goto out_err; 3806 readers++; 3807 } 3808 3809 i = 0; 3810 while (readers) { 3811 if (session_done()) 3812 break; 3813 3814 if (rd[i].done) { 3815 i = (i + 1) % nr_readers; 3816 continue; 3817 } 3818 if (reader__eof(&rd[i])) { 3819 rd[i].done = true; 3820 readers--; 3821 continue; 3822 } 3823 3824 session->active_decomp = &rd[i].decomp_data; 3825 ret = reader__read_event(&rd[i], session, &prog); 3826 if (ret < 0) { 3827 goto out_err; 3828 } else if (ret == READER_NODATA) { 3829 ret = reader__mmap(&rd[i], session); 3830 if (ret) 3831 goto out_err; 3832 } 3833 3834 if (rd[i].size >= READER_MAX_SIZE) { 3835 rd[i].size = 0; 3836 i = (i + 1) % nr_readers; 3837 } 3838 } 3839 3840 ret = ordered_events__flush(&session->ordered_events, OE_FLUSH__FINAL); 3841 if (ret) 3842 goto out_err; 3843 3844 ret = session__flush_deferred_samples(session, tool); 3845 if (ret) 3846 goto out_err; 3847 3848 ret = perf_session__flush_thread_stacks(session); 3849 out_err: 3850 ui_progress__finish(); 3851 3852 if (!tool->no_warn) 3853 perf_session__warn_about_errors(session); 3854 3855 /* 3856 * We may switching perf.data output, make ordered_events 3857 * reusable. 3858 */ 3859 ordered_events__reinit(&session->ordered_events); 3860 3861 session->one_mmap = false; 3862 3863 session->active_decomp = &session->decomp_data; 3864 for (i = 0; i < nr_readers; i++) 3865 reader__release_decomp(&rd[i]); 3866 zfree(&rd); 3867 3868 return ret; 3869 } 3870 3871 int perf_session__process_events(struct perf_session *session) 3872 { 3873 if (perf_session__register_idle_thread(session) < 0) 3874 return -ENOMEM; 3875 3876 if (perf_data__is_pipe(session->data)) 3877 return __perf_session__process_pipe_events(session); 3878 3879 if (perf_data__is_dir(session->data) && session->data->dir.nr) 3880 return __perf_session__process_dir_events(session); 3881 3882 return __perf_session__process_events(session); 3883 } 3884 3885 bool perf_session__has_traces(struct perf_session *session, const char *msg) 3886 { 3887 struct evsel *evsel; 3888 3889 evlist__for_each_entry(session->evlist, evsel) { 3890 if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) 3891 return true; 3892 } 3893 3894 pr_err("No trace sample to read. Did you call 'perf %s'?\n", msg); 3895 return false; 3896 } 3897 3898 bool perf_session__has_switch_events(struct perf_session *session) 3899 { 3900 struct evsel *evsel; 3901 3902 evlist__for_each_entry(session->evlist, evsel) { 3903 if (evsel->core.attr.context_switch) 3904 return true; 3905 } 3906 3907 return false; 3908 } 3909 3910 int map__set_kallsyms_ref_reloc_sym(struct map *map, const char *symbol_name, u64 addr) 3911 { 3912 char *bracket, *name; 3913 struct ref_reloc_sym *ref; 3914 struct kmap *kmap; 3915 3916 ref = zalloc(sizeof(struct ref_reloc_sym)); 3917 if (ref == NULL) 3918 return -ENOMEM; 3919 3920 ref->name = name = strdup(symbol_name); 3921 if (ref->name == NULL) { 3922 free(ref); 3923 return -ENOMEM; 3924 } 3925 3926 bracket = strchr(name, ']'); 3927 if (bracket) 3928 *bracket = '\0'; 3929 3930 ref->addr = addr; 3931 3932 kmap = map__kmap(map); 3933 if (kmap) 3934 kmap->ref_reloc_sym = ref; 3935 3936 return 0; 3937 } 3938 3939 size_t perf_session__fprintf_dsos(struct perf_session *session, FILE *fp) 3940 { 3941 return machines__fprintf_dsos(&session->machines, fp); 3942 } 3943 3944 size_t perf_session__fprintf_dsos_buildid(struct perf_session *session, FILE *fp, 3945 bool (skip)(struct dso *dso, int parm), int parm) 3946 { 3947 return machines__fprintf_dsos_buildid(&session->machines, fp, skip, parm); 3948 } 3949 3950 size_t perf_session__fprintf_nr_events(struct perf_session *session, FILE *fp) 3951 { 3952 size_t ret; 3953 const char *msg = ""; 3954 3955 if (perf_header__has_feat(&session->header, HEADER_AUXTRACE)) 3956 msg = " (excludes AUX area (e.g. instruction trace) decoded / synthesized events)"; 3957 3958 ret = fprintf(fp, "\nAggregated stats:%s\n", msg); 3959 3960 ret += events_stats__fprintf(evlist__stats(session->evlist), fp); 3961 return ret; 3962 } 3963 3964 size_t perf_session__fprintf(struct perf_session *session, FILE *fp) 3965 { 3966 size_t ret = machine__fprintf(&session->machines.host, fp); 3967 3968 for (struct rb_node *nd = rb_first_cached(&session->machines.guests); nd; nd = rb_next(nd)) { 3969 struct machine *pos = rb_entry(nd, struct machine, rb_node); 3970 3971 ret += machine__fprintf(pos, fp); 3972 } 3973 return ret; 3974 } 3975 3976 void perf_session__dump_kmaps(struct perf_session *session) 3977 { 3978 int save_verbose = verbose; 3979 3980 fflush(stdout); 3981 fprintf(stderr, "Kernel and module maps:\n"); 3982 verbose = 0; /* Suppress verbose to print a summary only */ 3983 maps__fprintf(machine__kernel_maps(&session->machines.host), stderr); 3984 verbose = save_verbose; 3985 } 3986 3987 struct evsel *perf_session__find_first_evtype(struct perf_session *session, 3988 unsigned int type) 3989 { 3990 struct evsel *pos; 3991 3992 evlist__for_each_entry(session->evlist, pos) { 3993 if (pos->core.attr.type == type) 3994 return pos; 3995 } 3996 return NULL; 3997 } 3998 3999 int perf_session__cpu_bitmap(struct perf_session *session, 4000 const char *cpu_list, unsigned long *cpu_bitmap) 4001 { 4002 unsigned int i; 4003 int err = -1; 4004 struct perf_cpu_map *map; 4005 int nr_cpus = min(perf_session__env(session)->nr_cpus_avail, MAX_NR_CPUS); 4006 struct perf_cpu cpu; 4007 4008 for (i = 0; i < PERF_TYPE_MAX; ++i) { 4009 struct evsel *evsel; 4010 4011 evsel = perf_session__find_first_evtype(session, i); 4012 if (!evsel) 4013 continue; 4014 4015 if (!(evsel->core.attr.sample_type & PERF_SAMPLE_CPU)) { 4016 pr_err("File does not contain CPU events. " 4017 "Remove -C option to proceed.\n"); 4018 return -1; 4019 } 4020 } 4021 4022 map = perf_cpu_map__new(cpu_list); 4023 if (map == NULL) { 4024 pr_err("Invalid cpu_list\n"); 4025 return -1; 4026 } 4027 4028 perf_cpu_map__for_each_cpu(cpu, i, map) { 4029 if (cpu.cpu >= nr_cpus) { 4030 pr_err("Requested CPU %d too large. " 4031 "Consider raising MAX_NR_CPUS\n", cpu.cpu); 4032 goto out_delete_map; 4033 } 4034 4035 __set_bit(cpu.cpu, cpu_bitmap); 4036 } 4037 4038 err = 0; 4039 4040 out_delete_map: 4041 perf_cpu_map__put(map); 4042 return err; 4043 } 4044 4045 void perf_session__fprintf_info(struct perf_session *session, FILE *fp, 4046 bool full) 4047 { 4048 if (session == NULL || fp == NULL) 4049 return; 4050 4051 fprintf(fp, "# ========\n"); 4052 perf_header__fprintf_info(session, fp, full); 4053 fprintf(fp, "# ========\n#\n"); 4054 } 4055 4056 static int perf_session__register_guest(struct perf_session *session, pid_t machine_pid) 4057 { 4058 struct machine *machine = machines__findnew(&session->machines, machine_pid); 4059 struct thread *thread; 4060 4061 if (!machine) 4062 return -ENOMEM; 4063 4064 machine->single_address_space = session->machines.host.single_address_space; 4065 4066 thread = machine__idle_thread(machine); 4067 if (!thread) 4068 return -ENOMEM; 4069 thread__put(thread); 4070 4071 machine->kallsyms_filename = perf_data__guest_kallsyms_name(session->data, machine_pid); 4072 4073 return 0; 4074 } 4075 4076 static int perf_session__set_guest_cpu(struct perf_session *session, pid_t pid, 4077 pid_t tid, int guest_cpu) 4078 { 4079 struct machine *machine = &session->machines.host; 4080 struct thread *thread = machine__findnew_thread(machine, pid, tid); 4081 4082 if (!thread) 4083 return -ENOMEM; 4084 thread__set_guest_cpu(thread, guest_cpu); 4085 thread__put(thread); 4086 4087 return 0; 4088 } 4089 4090 int perf_event__process_id_index(const struct perf_tool *tool __maybe_unused, 4091 struct perf_session *session, 4092 union perf_event *event) 4093 { 4094 struct evlist *evlist = session->evlist; 4095 struct perf_record_id_index *ie = &event->id_index; 4096 size_t sz = ie->header.size - sizeof(*ie); 4097 size_t i, nr, max_nr; 4098 size_t e1_sz = sizeof(struct id_index_entry); 4099 size_t e2_sz = sizeof(struct id_index_entry_2); 4100 size_t etot_sz = e1_sz + e2_sz; 4101 struct id_index_entry_2 *e2; 4102 pid_t last_pid = 0; 4103 4104 max_nr = sz / e1_sz; 4105 nr = ie->nr; 4106 if (nr > max_nr) { 4107 printf("Too big: nr %zu max_nr %zu\n", nr, max_nr); 4108 return -EINVAL; 4109 } 4110 4111 if (sz >= nr * etot_sz) { 4112 max_nr = sz / etot_sz; 4113 if (nr > max_nr) { 4114 printf("Too big2: nr %zu max_nr %zu\n", nr, max_nr); 4115 return -EINVAL; 4116 } 4117 e2 = (void *)ie + sizeof(*ie) + nr * e1_sz; 4118 } else { 4119 e2 = NULL; 4120 } 4121 4122 if (dump_trace) 4123 fprintf(stdout, " nr: %zu\n", nr); 4124 4125 for (i = 0; i < nr; i++, (e2 ? e2++ : 0)) { 4126 struct id_index_entry *e = &ie->entries[i]; 4127 struct perf_sample_id *sid; 4128 int ret; 4129 4130 if (dump_trace) { 4131 fprintf(stdout, " ... id: %"PRI_lu64, e->id); 4132 fprintf(stdout, " idx: %"PRI_lu64, e->idx); 4133 fprintf(stdout, " cpu: %"PRI_ld64, e->cpu); 4134 fprintf(stdout, " tid: %"PRI_ld64, e->tid); 4135 if (e2) { 4136 fprintf(stdout, " machine_pid: %"PRI_ld64, e2->machine_pid); 4137 fprintf(stdout, " vcpu: %"PRI_lu64"\n", e2->vcpu); 4138 } else { 4139 fprintf(stdout, "\n"); 4140 } 4141 } 4142 4143 sid = evlist__id2sid(evlist, e->id); 4144 if (!sid) 4145 return -ENOENT; 4146 4147 sid->idx = e->idx; 4148 sid->cpu.cpu = e->cpu; 4149 sid->tid = e->tid; 4150 4151 if (!e2) 4152 continue; 4153 4154 sid->machine_pid = e2->machine_pid; 4155 sid->vcpu.cpu = e2->vcpu; 4156 4157 if (!sid->machine_pid) 4158 continue; 4159 4160 if (sid->machine_pid != last_pid) { 4161 ret = perf_session__register_guest(session, sid->machine_pid); 4162 if (ret) 4163 return ret; 4164 last_pid = sid->machine_pid; 4165 perf_guest = true; 4166 } 4167 4168 ret = perf_session__set_guest_cpu(session, sid->machine_pid, e->tid, e2->vcpu); 4169 if (ret) 4170 return ret; 4171 } 4172 return 0; 4173 } 4174 4175 int perf_session__dsos_hit_all(struct perf_session *session) 4176 { 4177 struct rb_node *nd; 4178 int err; 4179 4180 err = machine__hit_all_dsos(&session->machines.host); 4181 if (err) 4182 return err; 4183 4184 for (nd = rb_first_cached(&session->machines.guests); nd; 4185 nd = rb_next(nd)) { 4186 struct machine *pos = rb_entry(nd, struct machine, rb_node); 4187 4188 err = machine__hit_all_dsos(pos); 4189 if (err) 4190 return err; 4191 } 4192 4193 return 0; 4194 } 4195 4196 struct perf_env *perf_session__env(struct perf_session *session) 4197 { 4198 return &session->header.env; 4199 } 4200 4201 struct perf_session__e_machine_cb_args { 4202 uint32_t e_flags; 4203 uint16_t e_machine; 4204 }; 4205 4206 static int perf_session__e_machine_cb(struct thread *thread, void *_args) 4207 { 4208 struct perf_session__e_machine_cb_args *args = _args; 4209 4210 args->e_machine = thread__e_machine(thread, /*machine=*/NULL, &args->e_flags); 4211 return args->e_machine != EM_NONE ? 1 : 0; 4212 } 4213 4214 /* 4215 * Note, a machine may have mixed 32-bit and 64-bit processes and so mixed 4216 * e_machines. Use thread__e_machine when this matters. 4217 */ 4218 uint16_t perf_session__e_machine(struct perf_session *session, uint32_t *e_flags) 4219 { 4220 struct perf_session__e_machine_cb_args args = { 4221 .e_machine = EM_NONE, 4222 }; 4223 struct perf_env *env; 4224 4225 if (!session) { 4226 /* Default to assuming a host machine. */ 4227 if (e_flags) 4228 *e_flags = EF_HOST; 4229 4230 return EM_HOST; 4231 } 4232 4233 /* 4234 * Is the env caching an e_machine? If not we want to compute from the 4235 * more accurate threads. 4236 */ 4237 env = perf_session__env(session); 4238 if (env && env->e_machine != EM_NONE) 4239 return perf_env__e_machine(env, e_flags); 4240 4241 /* 4242 * Compute from threads, note this is more accurate than 4243 * perf_env__e_machine that falls back on EM_HOST and doesn't consider 4244 * mixed 32-bit and 64-bit threads. 4245 */ 4246 machines__for_each_thread(&session->machines, 4247 perf_session__e_machine_cb, 4248 &args); 4249 4250 if (args.e_machine != EM_NONE) { 4251 if (env) { 4252 env->e_machine = args.e_machine; 4253 env->e_flags = args.e_flags; 4254 } 4255 if (e_flags) 4256 *e_flags = args.e_flags; 4257 4258 return args.e_machine; 4259 } 4260 4261 /* 4262 * Couldn't determine from the perf_env or current set of 4263 * threads. Potentially use logic that uses the arch string otherwise 4264 * default to the host. Don't cache in the perf_env in case later 4265 * threads indicate a better ELF machine type. 4266 */ 4267 return perf_env__e_machine_nocache(env, e_flags); 4268 } 4269