samply 0.13.1

A command line profiler for macOS and Linux.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use std::collections::HashMap;
use std::fs::File;
use std::ops::Deref;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::process::ExitStatus;
use std::thread;
use std::time::{Duration, SystemTime};

use crossbeam_channel::{Receiver, Sender};
use fxprof_processed_profile::ReferenceTimestamp;
use linux_perf_data::linux_perf_event_reader::{
    CpuMode, Endianness, EventRecord, Mmap2FileId, Mmap2InodeAndVersion, Mmap2Record, RawData,
};
use nix::sys::wait::WaitStatus;
use tokio::sync::oneshot;

use super::perf_event::EventSource;
use super::perf_group::{AttachMode, PerfGroup};
use super::proc_maps;
use super::process::SuspendedLaunchedProcess;
use crate::linux_shared::vdso::VdsoObject;
use crate::linux_shared::{
    ConvertRegs, Converter, EventInterpretation, MmapRangeOrVec, OffCpuIndicator,
};
use crate::server::{start_server_main, ServerProps};
use crate::shared::ctrl_c::CtrlC;
use crate::shared::recording_props::{
    ProcessLaunchProps, ProfileCreationProps, RecordingMode, RecordingProps,
};
use crate::shared::save_profile::save_profile_to_file;
use crate::shared::symbol_props::SymbolProps;

#[cfg(target_arch = "x86_64")]
pub type ConvertRegsNative = crate::linux_shared::ConvertRegsX86_64;

#[cfg(target_arch = "aarch64")]
pub type ConvertRegsNative = crate::linux_shared::ConvertRegsAarch64;

pub fn start_recording(
    recording_mode: RecordingMode,
    recording_props: RecordingProps,
    profile_creation_props: ProfileCreationProps,
    symbol_props: SymbolProps,
    server_props: Option<ServerProps>,
) -> Result<ExitStatus, ()> {
    let process_launch_props = match recording_mode {
        RecordingMode::All => {
            // TODO: Implement, by sudo launching a helper process which opens cpu-wide perf events
            eprintln!("Error: Profiling all processes is currently not supported on Linux.");
            eprintln!("You can profile processes which you launch via samply, or attach to a single process.");
            std::process::exit(1)
        }
        RecordingMode::Pid(pid) => {
            start_profiling_pid(
                pid,
                recording_props,
                profile_creation_props,
                symbol_props,
                server_props,
            );
            return Ok(ExitStatus::from_raw(0));
        }
        RecordingMode::Launch(process_launch_props) => process_launch_props,
    };

    // We want to profile a child process which we are about to launch.

    let ProcessLaunchProps {
        mut env_vars,
        command_name,
        args,
        iteration_count,
    } = process_launch_props;

    if profile_creation_props.coreclr.any_enabled() {
        // We need to set DOTNET_PerfMapEnabled=2 in the environment if it's not already set.
        // TODO: implement unlink_aux_files for linux
        if !env_vars.iter().any(|p| p.0 == "DOTNET_PerfMapEnabled") {
            env_vars.push(("DOTNET_PerfMapEnabled".into(), "2".into()));
        }
    }

    // Ignore Ctrl+C while the subcommand is running. The signal still reaches the process
    // under observation while we continue to record it. (ctrl+c will send the SIGINT signal
    // to all processes in the foreground process group).
    let mut ctrl_c_receiver = CtrlC::observe_oneshot();

    // Start a new process for the launched command and get its pid.
    // The command will not start running until we tell it to.
    let process =
        SuspendedLaunchedProcess::launch_in_suspended_state(&command_name, &args, &env_vars)
            .unwrap();
    let pid = process.pid();

    // Create a channel for the observer thread to notify the main thread once
    // profiling has been initialized and the launched process can start.
    let (profile_another_pid_request_sender, profile_another_pid_request_receiver) =
        crossbeam_channel::bounded(2);
    let (profile_another_pid_reply_sender, profile_another_pid_reply_receiver) =
        crossbeam_channel::bounded(2);

    // Launch the observer thread. This thread will manage the perf events.
    let output_file_copy = recording_props.output_file.clone();
    let interval = recording_props.interval;
    let time_limit = recording_props.time_limit;
    let initial_exec_name = command_name.to_string_lossy().to_string();
    let initial_cmdline: Vec<String> = std::iter::once(initial_exec_name.clone())
        .chain(args.iter().map(|arg| arg.to_string_lossy().to_string()))
        .collect();
    let initial_exec_name = match initial_exec_name.rfind('/') {
        Some(pos) => initial_exec_name[pos + 1..].to_string(),
        None => initial_exec_name,
    };
    let initial_exec_name_and_cmdline = (initial_exec_name, initial_cmdline);
    let observer_thread = thread::spawn(move || {
        let unstable_presymbolicate = profile_creation_props.unstable_presymbolicate;
        let mut converter = make_converter(interval, profile_creation_props);

        // Wait for the initial pid to profile.
        let SamplerRequest::StartProfilingAnotherProcess(pid, attach_mode) =
            profile_another_pid_request_receiver.recv().unwrap()
        else {
            panic!("The first message should be a StartProfilingAnotherProcess")
        };

        // Create the perf events, setting ENABLE_ON_EXEC.
        let perf_group = init_profiler(interval, pid, attach_mode, &mut converter);

        // Tell the main thread to tell the child process to begin executing.
        profile_another_pid_reply_sender.send(true).unwrap();

        // Create a stop receiver which is never notified. We won't stop profiling until the
        // child process is done.
        // If Ctrl+C is pressed, it will reach the child process, and the child process
        // will act on it and maybe terminate. If it does, profiling stops too because
        // the main thread's wait() call below will exit.
        let (_stop_sender, stop_receiver) = oneshot::channel();

        // Start profiling the process.
        run_profiler(
            perf_group,
            converter,
            &output_file_copy,
            time_limit,
            profile_another_pid_request_receiver,
            profile_another_pid_reply_sender,
            stop_receiver,
            unstable_presymbolicate,
            Some(initial_exec_name_and_cmdline),
        );
    });

    // We're on the main thread here and the observer thread has just been launched.

    // Request profiling of our process and wait for profiler initialization.
    profile_another_pid_request_sender
        .send(SamplerRequest::StartProfilingAnotherProcess(
            pid,
            AttachMode::AttachWithEnableOnExec,
        ))
        .unwrap();
    let _ = profile_another_pid_reply_receiver.recv().unwrap();

    // Now tell the child process to start executing.
    let process = match process.unsuspend_and_run() {
        Ok(process) => process,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            let command_name = command_name.to_string_lossy();
            if command_name.starts_with('-') {
                eprintln!("error: unexpected argument '{command_name}' found");
            } else {
                eprintln!("Error: Could not find an executable with the name {command_name}.");
            }
            std::process::exit(1)
        }
        Err(run_err) => {
            eprintln!("Could not launch child process: {run_err}");
            std::process::exit(1)
        }
    };

    // Phew, we're profiling!

    // Wait for the child process to quit.
    // This is where the main thread spends all its time during profiling.
    let mut wait_status = process.wait().unwrap();

    for i in 2..=iteration_count {
        let previous_run_exited_with_success = match &wait_status {
            WaitStatus::Exited(_pid, exit_code) => ExitStatus::from_raw(*exit_code).success(),
            _ => false,
        };
        if !previous_run_exited_with_success {
            eprintln!(
                "Skipping remaining iterations due to non-success exit status: {wait_status:?}"
            );
            break;
        }
        eprintln!("Running iteration {i} of {iteration_count}...");
        let process =
            SuspendedLaunchedProcess::launch_in_suspended_state(&command_name, &args, &env_vars)
                .unwrap();
        let pid = process.pid();

        // Tell the sampler to start profiling another pid, and wait for it to signal us to go ahead.
        profile_another_pid_request_sender
            .send(SamplerRequest::StartProfilingAnotherProcess(
                pid,
                AttachMode::AttachWithEnableOnExec,
            ))
            .unwrap();
        let succeeded = profile_another_pid_reply_receiver.recv().unwrap();
        if !succeeded {
            break;
        }

        // Now tell the child process to start executing.
        let process = match process.unsuspend_and_run() {
            Ok(process) => process,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                let command_name = command_name.to_string_lossy();
                eprintln!("Error: Could not find an executable with the name {command_name}.");
                std::process::exit(1)
            }
            Err(run_err) => {
                eprintln!("Could not launch child process: {run_err}");
                break;
            }
        };

        wait_status = process.wait().expect("couldn't wait for child");
    }

    profile_another_pid_request_sender
        .send(SamplerRequest::StopProfilingOncePerfEventsExhausted)
        .unwrap();

    // The launched subprocess is done. From now on, we want to terminate if the user presses Ctrl+C.
    ctrl_c_receiver.close();

    // Now wait for the observer thread to quit. It will keep running until all
    // perf events are closed, which happens if all processes which the events
    // are attached to have quit.
    observer_thread
        .join()
        .expect("couldn't join observer thread");

    if let Some(server_props) = server_props {
        let profile_filename = &recording_props.output_file;
        let libinfo_map = crate::profile_json_preparse::parse_libinfo_map_from_profile_file(
            File::open(profile_filename).expect("Couldn't open file we just wrote"),
            profile_filename,
        )
        .expect("Couldn't parse libinfo map from profile file");

        start_server_main(profile_filename, server_props, symbol_props, libinfo_map);
    }

    let exit_status = match wait_status {
        WaitStatus::Exited(_pid, exit_code) => ExitStatus::from_raw(exit_code),
        _ => ExitStatus::default(),
    };
    Ok(exit_status)
}

fn start_profiling_pid(
    pid: u32,
    recording_props: RecordingProps,
    profile_creation_props: ProfileCreationProps,
    symbol_props: SymbolProps,
    server_props: Option<ServerProps>,
) {
    // When the first Ctrl+C is received, stop recording.
    let ctrl_c_receiver = CtrlC::observe_oneshot();

    // Create a channel for the observer thread to notify the main thread once
    // profiling has been initialized.
    let (profile_another_pid_request_sender, profile_another_pid_request_receiver) =
        crossbeam_channel::bounded(2);
    let (profile_another_pid_reply_sender, profile_another_pid_reply_receiver) =
        crossbeam_channel::bounded(2);

    let output_file = recording_props.output_file.clone();
    let observer_thread = thread::spawn({
        move || {
            let interval = recording_props.interval;
            let time_limit = recording_props.time_limit;
            let unstable_presymbolicate = profile_creation_props.unstable_presymbolicate;
            let mut converter = make_converter(interval, profile_creation_props);
            let SamplerRequest::StartProfilingAnotherProcess(pid, attach_mode) =
                profile_another_pid_request_receiver.recv().unwrap()
            else {
                panic!("The first message should be a StartProfilingAnotherProcess")
            };
            let perf_group = init_profiler(interval, pid, attach_mode, &mut converter);

            // Tell the main thread that we are now executing.
            profile_another_pid_reply_sender.send(true).unwrap();

            let output_file = recording_props.output_file;
            run_profiler(
                perf_group,
                converter,
                &output_file,
                time_limit,
                profile_another_pid_request_receiver,
                profile_another_pid_reply_sender,
                ctrl_c_receiver,
                unstable_presymbolicate,
                None,
            )
        }
    });

    // We're on the main thread here and the observer thread has just been launched.

    // Request profiling of our process and wait for profiler initialization.
    profile_another_pid_request_sender
        .send(SamplerRequest::StartProfilingAnotherProcess(
            pid,
            AttachMode::StopAttachEnableResume,
        ))
        .unwrap();
    let _ = profile_another_pid_reply_receiver.recv().unwrap();

    // Now that we know that profiler initialization has succeeded, tell the user about it.
    eprintln!("Recording process with PID {pid} until Ctrl+C...");

    profile_another_pid_request_sender
        .send(SamplerRequest::StopProfilingOncePerfEventsExhausted)
        .unwrap();

    // Now wait for the observer thread to quit. It will keep running until the
    // CtrlC receiver has been notified, or until all perf events are closed,
    // which happens if all processes which the events are attached to have quit.
    observer_thread
        .join()
        .expect("couldn't join observer thread");

    // From now on, pressing Ctrl+C will kill our process, because the observer will have
    // dropped its CtrlC receiver by now.

    if let Some(server_props) = server_props {
        let libinfo_map = crate::profile_json_preparse::parse_libinfo_map_from_profile_file(
            File::open(&output_file).expect("Couldn't open file we just wrote"),
            &output_file,
        )
        .expect("Couldn't parse libinfo map from profile file");

        start_server_main(&output_file, server_props, symbol_props, libinfo_map);
    }
}

fn paranoia_level() -> Option<u32> {
    let level = read_string_lossy("/proc/sys/kernel/perf_event_paranoid").ok()?;
    let level = level.trim().parse::<u32>().ok()?;
    Some(level)
}

fn make_converter(
    interval: Duration,
    profile_creation_props: ProfileCreationProps,
) -> Converter<framehop::UnwinderNative<MmapRangeOrVec, framehop::MayAllocateDuringUnwind>> {
    let interval_nanos = if interval.as_nanos() > 0 {
        interval.as_nanos() as u64
    } else {
        1_000_000 // 1 million nano seconds = 1 milli second
    };

    let first_sample_time = 0;

    let endian = if cfg!(target_endian = "little") {
        Endianness::LittleEndian
    } else {
        Endianness::BigEndian
    };
    let machine_info = uname::uname().ok();
    let interpretation = EventInterpretation {
        main_event_attr_index: 0,
        main_event_name: "cycles".to_string(),
        sampling_is_time_based: Some(interval_nanos),
        off_cpu_indicator: Some(OffCpuIndicator::ContextSwitches),
        sched_switch_attr_index: None,
        known_event_indices: HashMap::new(),
        event_names: vec!["cycles".to_string()],
    };

    let mut converter = Converter::<
        framehop::UnwinderNative<MmapRangeOrVec, framehop::MayAllocateDuringUnwind>,
    >::new(
        &profile_creation_props,
        ReferenceTimestamp::from_system_time(SystemTime::now()),
        profile_creation_props.profile_name(),
        HashMap::new(),
        machine_info.as_ref().map(|info| info.release.as_str()),
        first_sample_time,
        endian,
        framehop::CacheNative::new(),
        Vec::new(),
        Vec::new(),
        interpretation,
        None,
        false,
    );
    if let Ok(os_release) = os_release::OsRelease::new() {
        converter.set_os_name(&os_release.pretty_name);
    }
    converter
}

fn init_profiler(
    interval: Duration,
    pid: u32,
    attach_mode: AttachMode,
    converter: &mut Converter<
        framehop::UnwinderNative<MmapRangeOrVec, framehop::MayAllocateDuringUnwind>,
    >,
) -> PerfGroup {
    let interval_nanos = if interval.as_nanos() > 0 {
        interval.as_nanos() as u64
    } else {
        1_000_000 // 1 million nano seconds = 1 milli second
    };

    let frequency = (1_000_000_000 / interval_nanos) as u32;
    let stack_size = 32000;
    let regs_mask = ConvertRegsNative::regs_mask();

    let perf = PerfGroup::open(
        pid,
        frequency,
        stack_size,
        EventSource::HwCpuCycles,
        regs_mask,
        attach_mode,
    );

    if let Err(error) = &perf {
        if error.kind() == std::io::ErrorKind::PermissionDenied {
            if let Some(level) = paranoia_level() {
                if level > 1 {
                    eprintln!();
                    eprintln!(
                        "'/proc/sys/kernel/perf_event_paranoid' is currently set to {level}."
                    );
                    eprintln!("In order for samply to work with a non-root user, this level needs");
                    eprintln!("to be set to 1 or lower.");
                    eprintln!("You can execute the following command and then try again:");
                    eprintln!("    echo '1' | sudo tee /proc/sys/kernel/perf_event_paranoid");
                    eprintln!();
                    std::process::exit(1);
                }
            }
        }
    }

    let mut perf = match perf {
        Ok(perf) => perf,
        Err(_) => {
            // We've already checked for permission denied due to paranoia
            // level, and exited with a warning in that case.

            // Another reason for the error could be the type of perf event:
            // The "Hardware CPU cycles" event is not supported in some contexts, for example in VMs.
            // Try a different event type.
            let perf = PerfGroup::open(
                pid,
                frequency,
                stack_size,
                EventSource::SwCpuClock,
                regs_mask,
                attach_mode,
            );
            match perf {
                Ok(perf) => perf, // Success!
                Err(error) => {
                    eprintln!("Failed to start profiling: {error}");
                    std::process::exit(1);
                }
            }
        }
    };

    let (exe_name, cmdline) = get_process_cmdline(pid).expect("Couldn't read process cmdline");
    let comm_data = std::fs::read(format!("/proc/{pid}/comm")).expect("Couldn't read process comm");
    let length = memchr::memchr(b'\0', &comm_data).unwrap_or(comm_data.len());
    let comm_name = std::str::from_utf8(&comm_data[..length])
        .unwrap()
        .trim_end();
    converter.register_existing_process(pid as i32, comm_name, &exe_name, cmdline);

    // TODO: Gather threads / processes recursively, here and in PerfGroup setup.
    for thread_entry in std::fs::read_dir(format!("/proc/{pid}/task"))
        .unwrap()
        .flatten()
    {
        let tid: u32 = thread_entry.file_name().to_string_lossy().parse().unwrap();
        let comm_path = format!("/proc/{pid}/task/{tid}/comm");
        if let Ok(buffer) = std::fs::read(comm_path) {
            let length = memchr::memchr(b'\0', &buffer).unwrap_or(buffer.len());
            let name = std::str::from_utf8(&buffer[..length]).unwrap().trim_end();
            converter.register_existing_thread(pid as i32, tid as i32, name);
        }
    }

    let maps = read_string_lossy(format!("/proc/{pid}/maps")).expect("couldn't read proc maps");
    let maps = proc_maps::parse(&maps);

    let vdso_file_id = VdsoObject::shared_instance_for_this_process()
        .map(|vdso| Mmap2FileId::BuildId(vdso.build_id().to_owned()));

    for region in maps {
        let mut protection = 0;
        if region.is_read {
            protection |= libc::PROT_READ;
        }
        if region.is_write {
            protection |= libc::PROT_WRITE;
        }
        if region.is_executable {
            protection |= libc::PROT_EXEC;
        }

        let mut flags = 0;
        if region.is_shared {
            flags |= libc::MAP_SHARED;
        } else {
            flags |= libc::MAP_PRIVATE;
        }

        let file_id = match (region.name.deref(), vdso_file_id.as_ref()) {
            ("[vdso]", Some(vdso_file_id)) => vdso_file_id.clone(),
            _ => Mmap2FileId::InodeAndVersion(Mmap2InodeAndVersion {
                major: region.major,
                minor: region.minor,
                inode: region.inode,
                inode_generation: 0,
            }),
        };

        converter.handle_mmap2(
            Mmap2Record {
                pid: pid as i32,
                tid: pid as i32,
                address: region.start,
                length: region.end - region.start,
                page_offset: region.file_offset,
                file_id,
                protection: protection as _,
                flags: flags as _,
                path: RawData::Single(&region.name.into_bytes()),
                cpu_mode: CpuMode::User,
            },
            0,
        );
    }

    // eprintln!("Enabling perf events...");
    match attach_mode {
        AttachMode::StopAttachEnableResume => perf.enable(),
        AttachMode::AttachWithEnableOnExec => {
            // The perf event will get enabled automatically once the forked child process execs.
        }
    }

    perf
}

enum SamplerRequest {
    StartProfilingAnotherProcess(u32, AttachMode),
    StopProfilingOncePerfEventsExhausted,
}

#[allow(clippy::too_many_arguments)]
fn run_profiler(
    mut perf: PerfGroup,
    mut converter: Converter<
        framehop::UnwinderNative<MmapRangeOrVec, framehop::MayAllocateDuringUnwind>,
    >,
    output_filename: &Path,
    _time_limit: Option<Duration>,
    more_processes_request_receiver: Receiver<SamplerRequest>,
    more_processes_reply_sender: Sender<bool>,
    mut stop_receiver: oneshot::Receiver<()>,
    unstable_presymbolicate: bool,
    mut initial_exec_name_and_cmdline: Option<(String, Vec<String>)>,
) {
    // eprintln!("Running...");

    let mut should_stop_profiling_once_perf_events_exhausted = false;
    let mut pending_lost_events = 0;
    let mut total_lost_events = 0;
    let mut last_timestamp = 0;
    loop {
        if stop_receiver.try_recv().is_ok() {
            break;
        }

        match more_processes_request_receiver.try_recv() {
            Ok(SamplerRequest::StartProfilingAnotherProcess(another_pid, attach_mode)) => {
                match perf.open_process(another_pid, attach_mode) {
                    Ok(_) => {
                        more_processes_reply_sender.send(true).unwrap();
                    }
                    Err(error) => {
                        eprintln!("Failed to start profiling on subsequent process: {error}");
                        more_processes_reply_sender.send(false).unwrap();
                    }
                }
            }
            Ok(SamplerRequest::StopProfilingOncePerfEventsExhausted) => {
                should_stop_profiling_once_perf_events_exhausted = true;
            }
            Err(_) => {
                // No requests pending at the moment.
            }
        }

        if perf.is_empty() && !should_stop_profiling_once_perf_events_exhausted {
            match more_processes_request_receiver.recv() {
                Ok(SamplerRequest::StartProfilingAnotherProcess(another_pid, attach_mode)) => {
                    match perf.open_process(another_pid, attach_mode) {
                        Ok(_) => {
                            more_processes_reply_sender.send(true).unwrap();
                        }
                        Err(error) => {
                            eprintln!("Failed to start profiling on subsequent process: {error}");
                            more_processes_reply_sender.send(false).unwrap();
                        }
                    }
                }
                Ok(SamplerRequest::StopProfilingOncePerfEventsExhausted) => {
                    should_stop_profiling_once_perf_events_exhausted = true;
                }
                Err(_) => {
                    // No requests pending at the moment.
                }
            }
        }

        if perf.is_empty() && should_stop_profiling_once_perf_events_exhausted {
            break;
        }

        perf.consume_events(&mut |event_ref| {
            let record = event_ref.get();
            let parsed_record = record.parse().unwrap();
            // debug!("Recording parsed_record: {:#?}", parsed_record);

            if let Some(timestamp) = record.timestamp() {
                if timestamp < last_timestamp {
                    // eprintln!(
                    //     "bad timestamp ordering; {timestamp} is earlier but arrived after {last_timestamp}"
                    // );
                }
                last_timestamp = timestamp;
            }

            match parsed_record {
                EventRecord::Sample(e) => {
                    converter.handle_main_event_sample::<ConvertRegsNative>(&e);
                    /*
                    } else if interpretation.sched_switch_attr_index == Some(attr_index) {
                        converter.handle_sched_switch_sample::<C>(e);
                    }*/
                }
                EventRecord::Fork(e) => {
                    converter.handle_fork(e);
                }
                EventRecord::Comm(e) => {
                    if e.is_execve {
                        // Try to get the command line arguments for this process.
                        let exec_name_and_cmdline =
                            if let Some(initial) = initial_exec_name_and_cmdline.take() {
                                // This COMM event is the first exec that we're processing. If we get
                                // here, it means we're in the "launch process" case and we're seeing
                                // the exec for that initial launched process.
                                Some(initial)
                            } else {
                                // Attempt to get the process cmdline from /proc/{pid}/cmdline.
                                // This isn't very reliable because we're processing the perf event records
                                // in batches, with a delay, so the COMM record may be old enough that the
                                // pid no longer exists, or the pid may even refer to a different process now.
                                // Unfortunately there are no perf event records that give us the process
                                // command line.
                                get_process_cmdline(e.pid as u32).ok()
                            };
                        converter.handle_exec(e, record.timestamp(), exec_name_and_cmdline);
                    } else {
                        converter.handle_thread_rename(e, record.timestamp());
                    }
                }
                EventRecord::Exit(e) => {
                    converter.handle_exit(e);
                }
                EventRecord::Mmap(e) => {
                    converter.handle_mmap(e, last_timestamp);
                }
                EventRecord::Mmap2(e) => {
                    converter.handle_mmap2(e, last_timestamp);
                }
                EventRecord::ContextSwitch(e) => {
                    let common = match record.common_data() {
                        Ok(common) => common,
                        Err(_) => return,
                    };
                    converter.handle_context_switch(e, common);
                }
                EventRecord::Lost(event) => {
                    pending_lost_events += event.count;
                    total_lost_events += event.count;
                    return;
                }
                _ => {}
            }

            if pending_lost_events > 0 {
                // eprintln!("Pending lost events: {pending_lost_events}");
                pending_lost_events = 0;
            }
        });

        perf.wait();
    }

    if total_lost_events > 0 {
        eprintln!("Lost {total_lost_events} events.");
    }

    let profile = converter.finish();

    save_profile_to_file(&profile, output_filename).expect("Couldn't write JSON");

    if unstable_presymbolicate {
        crate::shared::symbol_precog::presymbolicate(
            &profile,
            &output_filename.with_extension("syms.json"),
        );
    }
}

pub fn read_string_lossy<P: AsRef<Path>>(path: P) -> std::io::Result<String> {
    let data = std::fs::read(path)?;
    Ok(String::from_utf8_lossy(&data).into_owned())
}

fn get_process_cmdline(pid: u32) -> std::io::Result<(String, Vec<String>)> {
    let path = format!("/proc/{pid}/cmdline");
    let cmdline_bytes = std::fs::read(&path)?;
    let mut remaining_bytes = &cmdline_bytes[..];
    let mut cmdline = Vec::new();
    while let Some(nul_byte_pos) = memchr::memchr(b'\0', remaining_bytes) {
        let arg_slice = &remaining_bytes[..nul_byte_pos];
        remaining_bytes = &remaining_bytes[nul_byte_pos + 1..];
        cmdline.push(String::from_utf8_lossy(arg_slice).to_string());
    }

    let exe_arg = cmdline.first().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::Other,
            format!("Empty cmdline at {path}"),
        )
    })?;

    let exe_name = match exe_arg.rfind('/') {
        Some(pos) => exe_arg[pos + 1..].to_string(),
        None => exe_arg.to_string(),
    };

    Ok((exe_name, cmdline))
}