| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Use of this source code is governed by a MIT-style | |
| // license that can be found in the LICENSE file or at | |
| // https://opensource.org/licenses/MIT | |
| /// KTrace unit tests. | |
| #[unittest::suite(name = "ktrace")] | |
| mod ktrace_tests { | |
| use super::super::*; | |
| use crate::arch_rs::{InterruptDisableGuard, curr_cpu_num, max_num_cpus}; | |
| use crate::kernel::thread::{FxtRef, ThreadPtr}; | |
| use crate::percpu_writer::DroppedRecordDurationEvent; | |
| use crate::user_copy::UserOutPtr; | |
| use crate::user_memory::UserMemory; | |
| use core::mem::{size_of, size_of_val}; | |
| use core::ptr; | |
| use core::sync::atomic::{AtomicI64, AtomicU64}; | |
| use fxt_layout::SchedulerEventType; | |
| use kalloc::Box; | |
| use unittest::{ | |
| assert_eq, assert_err, assert_ge, assert_le, assert_ne, assert_ok, assert_true, expect_eq, | |
| expect_false, expect_ne, expect_true, unwrap_ok, unwrap_some, | |
| }; | |
| use zerocopy::{FromBytes, IntoBytes}; | |
| use zx_status::Status; | |
| fn make_record_header(record_type: RecordType, size_words: u16) -> u64 { | |
| let mut hdr = RecordHeader::new(); | |
| hdr.set_record_type(record_type).set_record_size(size_words); | |
| hdr.bits() | |
| } | |
| /// Reads up to `dst.len()` bytes from an isolated test-local `Buffer` into `dst`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// The caller must ensure single-consumer exclusivity on `buf` (no concurrent `read` or `drain` | |
| /// calls). | |
| unsafe fn read_test_buffer(buf: &Buffer, dst: &mut [u8]) -> Result<usize, Status> { | |
| let max_len = u32::try_from(dst.len()).map_err(|_| Status::INVALID_ARGS)?; | |
| // SAFETY: Discharged by caller's single-consumer guarantee; the closure only copies into | |
| // `dst` without reentrantly calling `read` or `drain` on `buf`. | |
| let read_len = unsafe { | |
| buf.read( | |
| |offset, src| { | |
| let off = offset as usize; | |
| let end = off.checked_add(src.len()).ok_or(Status::OUT_OF_RANGE)?; | |
| let slot = dst.get_mut(off..end).ok_or(Status::BUFFER_TOO_SMALL)?; | |
| slot.copy_from_slice(src); | |
| Ok(()) | |
| }, | |
| max_len, | |
| ) | |
| }?; | |
| Ok(read_len as usize) | |
| } | |
| /// Reads word-aligned FXT records from an isolated test-local `Buffer` into `dst`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// The caller must ensure single-consumer exclusivity on `buf` (no concurrent `read` or `drain` | |
| /// calls). | |
| unsafe fn read_test_words<'a>(buf: &Buffer, dst: &'a mut [u64]) -> Result<&'a [u64], Status> { | |
| // SAFETY: Discharged by caller's single-consumer guarantee. | |
| let bytes = unsafe { read_test_buffer(buf, dst.as_mut_bytes()) }?; | |
| if bytes % 8 != 0 { | |
| return Err(Status::BAD_STATE); | |
| } | |
| Ok(&dst[..bytes / 8]) | |
| } | |
| /// Iterates over word-aligned FXT records, yielding `(header, payload_words)` (excluding the | |
| /// header word itself). | |
| struct FxtRecordIter<'a>(&'a [u64]); | |
| impl<'a> FxtRecordIter<'a> { | |
| fn is_empty(&self) -> bool { | |
| self.0.is_empty() | |
| } | |
| } | |
| impl<'a> Iterator for FxtRecordIter<'a> { | |
| type Item = (RecordHeader, &'a [u64]); | |
| fn next(&mut self) -> Option<Self::Item> { | |
| let &raw = self.0.first()?; | |
| let hdr = RecordHeader::from(raw); | |
| let len = usize::from(hdr.record_size()); | |
| if len == 0 || len > self.0.len() { | |
| return None; | |
| } | |
| let (rec, rest) = self.0.split_at(len); | |
| self.0 = rest; | |
| Some((hdr, &rec[1..])) | |
| } | |
| } | |
| /// Iterates over FXT arguments in a record payload, yielding `(header, payload_words)` | |
| /// (excluding the argument header word itself). | |
| struct FxtArgIter<'a>(&'a [u64]); | |
| impl<'a> FxtArgIter<'a> { | |
| fn is_empty(&self) -> bool { | |
| self.0.is_empty() | |
| } | |
| } | |
| impl<'a> Iterator for FxtArgIter<'a> { | |
| type Item = (ArgumentHeader, &'a [u64]); | |
| fn next(&mut self) -> Option<Self::Item> { | |
| let &raw = self.0.first()?; | |
| let hdr = ArgumentHeader::from(raw); | |
| let len = usize::from(hdr.size_words()); | |
| if len == 0 || len > self.0.len() { | |
| return None; | |
| } | |
| let (arg, rest) = self.0.split_at(len); | |
| self.0 = rest; | |
| Some((hdr, &arg[1..])) | |
| } | |
| } | |
| fn assert_control_state( | |
| ktrace: &KTrace, | |
| buf_size: u32, | |
| allocated: bool, | |
| writes_enabled: bool, | |
| mask: u32, | |
| ) -> bool { | |
| (unittest::subtest!(|| { | |
| assert_eq!(buf_size, ktrace.buffer_size()); | |
| let expected_bufs = | |
| if buf_size != 0 && allocated { max_num_cpus() as usize } else { 0 }; | |
| assert_eq!(expected_bufs, ktrace.buffers().map_or(0, <[Buffer]>::len)); | |
| assert_eq!(writes_enabled, ktrace.writes_enabled()); | |
| assert_eq!(mask, ktrace.categories_bitmask()); | |
| }))() | |
| } | |
| fn on_all_cpus(f: impl Fn(usize) -> bool + Sync) -> bool { | |
| let ok = AtomicBool::new(true); | |
| let run = || { | |
| if !f(curr_cpu_num() as usize) { | |
| ok.store(false, Ordering::Relaxed); | |
| } | |
| }; | |
| // SAFETY: `MpIpiTarget::All` does not require caller interrupts to be disabled. | |
| unsafe { sync_exec(MpIpiTarget::All, 0, run) }; | |
| ok.load(Ordering::Relaxed) | |
| } | |
| /// Writes one page-sized `Metadata` record into each online CPU's buffer and returns the | |
| /// bitmask of visited online CPUs. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if `buffers.len() < max_num_cpus() as usize`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// The caller must ensure that: | |
| /// | |
| /// - Single-producer exclusivity holds across `buffers` for the duration of this call (no | |
| /// concurrent `reserve`, `emit_drop_stats`, `reset_drop_stats`, or control operations on | |
| /// `buffers`). | |
| /// - No uncommitted [`Reservation`] is live on `buffers`, and `payload_for_cpu` does not | |
| /// reentrantly access `buffers`. | |
| unsafe fn fill_online_cpu_buffers<'a>( | |
| buffers: &[Buffer], | |
| payload_for_cpu: impl Fn(usize) -> &'a [u8] + Sync, | |
| ) -> Option<u64> { | |
| let full_header = make_record_header(RecordType::Metadata, (page::SIZE / 8) as u16); | |
| let online_cpu_bits = AtomicU64::new(0); | |
| let ok = on_all_cpus(|cpu| { | |
| let payload = payload_for_cpu(cpu); | |
| if payload.len() != page::SIZE - 8 { | |
| return false; | |
| } | |
| let irqd = InterruptDisableGuard::new(); | |
| // SAFETY: By `# Safety`, single-producer exclusivity holds across `buffers` with no | |
| // uncommitted `Reservation` live and `payload_for_cpu` does not reentrantly access | |
| // `buffers`; `on_all_cpus` executes on `cpu` (the single CPU that owns `buffers[cpu]`) | |
| // with `irqd` locally disabling interrupts for the reservation lifetime. | |
| let res = unsafe { buffers[cpu].reserve(&irqd, full_header) }; | |
| let Ok(mut res) = res else { | |
| return false; | |
| }; | |
| res.write_bytes(payload); | |
| res.commit(); | |
| online_cpu_bits.fetch_or(1u64 << cpu, Ordering::Relaxed); | |
| true | |
| }); | |
| ok.then(|| online_cpu_bits.load(Ordering::Relaxed)) | |
| } | |
| #[derive(Clone, Copy)] | |
| enum Trailing { | |
| None, | |
| AutoTs, | |
| Exact(u64), | |
| } | |
| fn check_u32_args(words: &[u64], expected: &[u32]) -> bool { | |
| (unittest::subtest!(|| { | |
| let mut args = FxtArgIter(words); | |
| for &val in expected { | |
| let (arg, payload) = unwrap_some!(args.next()); | |
| assert_eq!(ArgumentType::Uint32, arg.arg_type()); | |
| assert_eq!(val, arg.value_bits()); | |
| assert_true!(payload.is_empty()); | |
| } | |
| assert_true!(args.next().is_none()); | |
| assert_true!(args.is_empty()); | |
| }))() | |
| } | |
| fn check_u32_event( | |
| iter: &mut FxtRecordIter<'_>, | |
| spec: (EventType, Option<u64>, Option<u64>, u32, Trailing), | |
| last_auto_ts: &mut u64, | |
| ts_upper: u64, | |
| ) -> bool { | |
| let (expected_type, expected_ts, expected_cpu_koid, expected_arg_val, trailing) = spec; | |
| (unittest::subtest!(|| { | |
| let (raw_hdr, payload) = unwrap_some!(iter.next()); | |
| let expected_words = if matches!(trailing, Trailing::None) { 5u16 } else { 6u16 }; | |
| let hdr = EventRecordHeader::from(raw_hdr.bits()); | |
| assert_eq!(RecordType::Event, hdr.record_type()); | |
| assert_eq!(expected_words, hdr.record_size()); | |
| assert_eq!(expected_type, hdr.event_type()); | |
| assert_eq!(1, hdr.arg_count()); | |
| if let Some(ts) = expected_ts { | |
| assert_eq!(ts, payload[0]); | |
| } else { | |
| assert_ge!(payload[0], *last_auto_ts); | |
| assert_le!(payload[0], ts_upper); | |
| *last_auto_ts = payload[0]; | |
| } | |
| if let Some(cpu_tid) = expected_cpu_koid { | |
| assert_eq!(NO_PROCESS_KOID, payload[1]); | |
| assert_eq!(cpu_tid, payload[2]); | |
| } | |
| assert_true!(check_u32_args(&payload[3..4], &[expected_arg_val])); | |
| if let Trailing::AutoTs = trailing { | |
| assert_ge!(payload[4], *last_auto_ts); | |
| assert_le!(payload[4], ts_upper); | |
| *last_auto_ts = payload[4]; | |
| } else if let Trailing::Exact(val) = trailing { | |
| assert_eq!(val, payload[4]); | |
| } | |
| }))() | |
| } | |
| fn emit_all_test_macros(complete_start_ts: InstantBootTicks) { | |
| instant!(CAT_META, "rust_instant", "val" => 101u32); | |
| cpu_instant!("kernel:sched", "rust_cpu_instant", "val" => 100u32); | |
| duration_begin!("kernel:meta", "rust_duration", "val" => 102u32); | |
| duration_end!("kernel:meta", "rust_duration", "val" => 103u32); | |
| flow_begin!("kernel:meta", "rust_flow", 106u64, "val" => 107u32); | |
| flow_step_timestamp!( | |
| "kernel:meta", | |
| "rust_flow_ts", | |
| InstantBootTicks(1080), | |
| 106u64, | |
| "val" => 1081u32 | |
| ); | |
| flow_end!("kernel:meta", "rust_flow", 106u64, "val" => 109u32); | |
| complete!("kernel:meta", "rust_complete", complete_start_ts, "val" => 111u32); | |
| complete_timestamp!( | |
| "kernel:meta", | |
| "rust_complete_ts", | |
| InstantBootTicks(1100), | |
| InstantBootTicks(1200), | |
| "val" => 1110u32, | |
| ); | |
| kernel_object!("kernel:meta", 112u64, 1u32, "rust_kernel_obj", "val" => 113u32); | |
| kernel_object_always!(114u64, 2u32, "rust_kernel_obj_always", "val" => 115u32); | |
| kernel_object!("kernel:meta", 116u64, 1u32, &b"dynamic_proc"[..], "job" => Koid(117u64)); | |
| let scope = cpu_begin_scope_cond!(true, "kernel:sched", "find_target", "cpu" => 0u32); | |
| end_scope!(scope, "last_cpu" => 1u32, "target_cpu" => 2u32); | |
| cpu_counter!("kernel:sched", "rust_cpu_counter", 133u64, "val" => 134u32); | |
| cpu_counter_timestamp!( | |
| "kernel:sched", | |
| "rust_cpu_counter_ts", | |
| InstantBootTicks(135), | |
| 136u64, | |
| "val" => 137u32 | |
| ); | |
| cpu_flow_begin!("kernel:sched", "rust_cpu_flow", 138u64, "val" => 139u32); | |
| cpu_flow_step!("kernel:sched", "rust_cpu_flow", 138u64, "val" => 140u32); | |
| cpu_flow_end!("kernel:sched", "rust_cpu_flow", 138u64, "val" => 141u32); | |
| { | |
| let _cpu_scope = cpu_begin_scope!("kernel:sched", "rust_cpu_scope", "val" => 142u32); | |
| } | |
| context_switch!( | |
| "kernel:sched", | |
| 2u16, | |
| 3u32, | |
| 120u64, | |
| 121u64, | |
| "outgoing_weight" => 122u32, | |
| "incoming_weight" => 123u32, | |
| ); | |
| thread_wakeup!("kernel:sched", 5u16, 124u64, "weight" => 125u32); | |
| } | |
| /// Tracing started by init and stopped by control stop. | |
| #[test] | |
| fn init_stop() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| let page_u32 = page::SIZE as u32; | |
| ktrace.init(page_u32 * max_num_cpus(), 0xff1); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, 0xff1)); | |
| assert_eq!(1, ktrace.report_metadata_count()); | |
| let grps = KTRACE_GRP_META | KTRACE_GRP_PROBE; | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, grps)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, grps)); | |
| assert_eq!(1, ktrace.report_metadata_count()); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_STOP, 0)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, false, 0)); | |
| } | |
| /// Init rounds uneven per-CPU buffer size down to power of two. | |
| #[test] | |
| fn init_with_uneven_buffer_size() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| let page_u32 = page::SIZE as u32; | |
| ktrace.init((page_u32 + 1723) * max_num_cpus(), 0xff1); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, 0xff1)); | |
| assert_eq!(1, ktrace.report_metadata_count()); | |
| } | |
| /// `ktrace.bufsize` MiB-to-bytes conversion clamps instead of wrapping on `u32` overflow. | |
| #[test] | |
| fn bufsize_mib_overflow() { | |
| assert_true!(bufsize_mib_to_bytes(0) == Ok(0)); | |
| assert_true!(bufsize_mib_to_bytes(32) == Ok(32 << 20)); | |
| assert_true!(bufsize_mib_to_bytes(4095) == Ok(4095 << 20)); | |
| assert_true!(bufsize_mib_to_bytes(4096) == Err(u32::MAX)); | |
| assert_true!(bufsize_mib_to_bytes(u32::MAX) == Err(u32::MAX)); | |
| } | |
| /// Delayed allocation on init followed by start and stop. | |
| #[test] | |
| fn start_stop() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| assert_true!(assert_control_state(&ktrace, 0, false, false, 0)); | |
| let page_u32 = page::SIZE as u32; | |
| ktrace.init(page_u32 * max_num_cpus(), 0); | |
| assert_true!(assert_control_state(&ktrace, page_u32, false, false, 0)); | |
| assert_eq!(0, ktrace.report_metadata_count()); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, 0x1f)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, 0x1f)); | |
| assert_eq!(1, ktrace.report_metadata_count()); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, 0x20)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, 0x20)); | |
| assert_eq!(1, ktrace.report_metadata_count()); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, 0)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, true, KTRACE_GRP_ALL)); | |
| assert_err!(ktrace.control_impl(999, 0), Status::INVALID_ARGS); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_STOP, 0)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, false, 0)); | |
| } | |
| /// Reservation, word writes, unaligned byte padding, and readback. | |
| #[test] | |
| fn write() { | |
| const NUM_WORDS: usize = 29; | |
| const NUM_BYTES: usize = 397; | |
| const { assert!(NUM_BYTES % 8 != 0) }; | |
| const PADDED_SIZE: usize = | |
| (size_of::<u64>() + (NUM_WORDS * 8) + NUM_BYTES).next_multiple_of(8); | |
| let words: [u64; NUM_WORDS] = | |
| core::array::from_fn(|i| 0x0102_0304_0506_0708u64.wrapping_mul((i + 1) as u64)); | |
| let bytes: [u8; NUM_BYTES] = | |
| core::array::from_fn(|i| (i.wrapping_mul(31).wrapping_add(7)) as u8); | |
| let fxt_header = make_record_header(RecordType::Blob, (PADDED_SIZE / 8) as u16); | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), 0); | |
| let disabled_res = { | |
| let irqd = InterruptDisableGuard::new(); | |
| // SAFETY: `ktrace` is local to this test (not installed via | |
| // `with_thread_local_override` and with no concurrent control or producer calls), | |
| // `irqd` disables interrupts, and no uncommitted `Reservation` is live on `ktrace`. | |
| unsafe { ktrace.reserve(&irqd, fxt_header).map(|res| res.commit()) } | |
| }; | |
| assert_err!(disabled_res, Status::BAD_STATE); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, KTRACE_GRP_META)); | |
| let target_cpu = unwrap_ok!({ | |
| let irqd = InterruptDisableGuard::new(); | |
| // SAFETY: `ktrace` is local to this test (not installed via | |
| // `with_thread_local_override` and with no concurrent control or producer calls), | |
| // `irqd` disables interrupts on the current CPU, and no uncommitted `Reservation` is | |
| // live on `ktrace`. | |
| let res = unsafe { ktrace.reserve(&irqd, fxt_header) }; | |
| res.map(|mut res| { | |
| for &word in &words { | |
| res.write_word(word); | |
| } | |
| res.write_bytes(&bytes); | |
| res.commit(); | |
| curr_cpu_num() as usize | |
| }) | |
| }); | |
| let buffers = unwrap_some!(ktrace.buffers()); | |
| let mut actual = [0u8; PADDED_SIZE]; | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let read_len = unwrap_ok!(unsafe { read_test_buffer(&buffers[target_cpu], &mut actual) }); | |
| assert_eq!(PADDED_SIZE, read_len); | |
| let mut expected = [0u8; PADDED_SIZE]; | |
| expected[..8].copy_from_slice(&fxt_header.to_ne_bytes()); | |
| let words_end = 8 + size_of_val(&words); | |
| expected[8..words_end].copy_from_slice(words.as_bytes()); | |
| expected[words_end..words_end + NUM_BYTES].copy_from_slice(&bytes); | |
| assert_true!(actual == expected); | |
| } | |
| /// Rewind drains all per-CPU buffers, clears categories, and disables writes. | |
| #[test] | |
| fn rewind() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| let page_u32 = page::SIZE as u32; | |
| ktrace.init(page_u32 * max_num_cpus(), 0); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_REWIND, 0)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, false, false, 0)); | |
| let mut page_buf = unwrap_some!(Box::<[u8]>::try_new_zeroed_slice(page::SIZE).ok()); | |
| page_buf.fill(0xff); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, KTRACE_GRP_META)); | |
| let buffers = unwrap_some!(ktrace.buffers()); | |
| // SAFETY: `ktrace` is local to this test (not installed via `with_thread_local_override` | |
| // and with no concurrent control or producer calls), no uncommitted `Reservation` is live, | |
| // and the payload closure only borrows `page_buf` without accessing `buffers`. | |
| let _visited = unwrap_some!(unsafe { | |
| fill_online_cpu_buffers(buffers, |_| &page_buf[..page::SIZE - 8]) | |
| }); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_REWIND, 0)); | |
| assert_true!(assert_control_state(&ktrace, page_u32, true, false, 0)); | |
| for buf in buffers { | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let read_len = unwrap_ok!(unsafe { read_test_buffer(buf, &mut page_buf) }); | |
| assert_eq!(0, read_len); | |
| } | |
| } | |
| /// ReadUser length validation and user-memory copy out across online CPUs. | |
| #[test] | |
| fn read_user() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| let num_cpus = max_num_cpus() as usize; | |
| let total_bufsize = page::SIZE * num_cpus; | |
| ktrace.init(total_bufsize as u32, 0); | |
| let user_mem = unwrap_some!(UserMemory::create(total_bufsize)); | |
| let call_read_user = |ptr: UserOutPtr<u8>, len: usize| { | |
| // SAFETY: Kernel unit tests run in blockable thread context on a dedicated kernel test | |
| // thread with a standalone non-unified `Type::User` `VmAspace` (`user_mem`) attached | |
| // and zero locks held across all calls in this test. | |
| unsafe { ktrace.read_user_impl(ptr, len) } | |
| }; | |
| assert_eq!( | |
| total_bufsize, | |
| unwrap_ok!(call_read_user(UserOutPtr::new(ptr::null_mut()), total_bufsize)) | |
| ); | |
| // Before delayed buffer allocation, valid `len <= u32::MAX` reads return `Ok(0)` even | |
| // when `len < total_bufsize`, while `len > u32::MAX` still fails with `INVALID_ARGS`. | |
| assert_eq!(0, unwrap_ok!(call_read_user(user_mem.user_out::<u8>(), 0))); | |
| assert_eq!(0, unwrap_ok!(call_read_user(user_mem.user_out::<u8>(), total_bufsize))); | |
| assert_err!( | |
| call_read_user(user_mem.user_out::<u8>(), 0x1_0000_0000usize), | |
| Status::INVALID_ARGS | |
| ); | |
| let mut src = unwrap_some!(Box::<[u8]>::try_new_zeroed_slice(total_bufsize).ok()); | |
| let full_header = make_record_header(RecordType::Metadata, (page::SIZE / 8) as u16); | |
| for cpu in 0..num_cpus { | |
| let base = cpu * page::SIZE; | |
| src[base..base + 8].copy_from_slice(&full_header.to_ne_bytes()); | |
| for (idx, b) in src[base + 8..base + page::SIZE].iter_mut().enumerate() { | |
| *b = (cpu.wrapping_mul(37).wrapping_add(idx)) as u8; | |
| } | |
| } | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, KTRACE_GRP_META)); | |
| let buffers = unwrap_some!(ktrace.buffers()); | |
| // SAFETY: `ktrace` is local to this test (not installed via `with_thread_local_override` | |
| // and with no concurrent control or producer calls), no uncommitted `Reservation` is live, | |
| // and the payload closure only borrows `src` without accessing `buffers`. | |
| let visited_mask = unwrap_some!(unsafe { | |
| fill_online_cpu_buffers(buffers, |cpu| { | |
| let base = cpu * page::SIZE; | |
| &src[base + 8..base + page::SIZE] | |
| }) | |
| }); | |
| let expected_read_bytes = (visited_mask.count_ones() as usize) * page::SIZE; | |
| for bad_len in | |
| [0, total_bufsize - 1, 0x1_0000_0000usize, 0x1_0000_0000usize + page::SIZE, usize::MAX] | |
| { | |
| assert_err!(call_read_user(user_mem.user_out::<u8>(), bad_len), Status::INVALID_ARGS); | |
| } | |
| assert_eq!( | |
| expected_read_bytes, | |
| unwrap_ok!(call_read_user(user_mem.user_out::<u8>(), total_bufsize)) | |
| ); | |
| // Reading again once allocated buffers are empty exercises the `initial_available == 0` | |
| // path (skipping `soft_fault_in_range`). | |
| assert_eq!(0, unwrap_ok!(call_read_user(user_mem.user_out::<u8>(), total_bufsize))); | |
| let mut dst_uninit = | |
| unwrap_some!(Box::<[u8]>::try_new_zeroed_uninit_slice(expected_read_bytes).ok()); | |
| let dst = unwrap_ok!(user_mem.vmo_read(&mut dst_uninit, 0)); | |
| let (pages, rem) = dst.as_chunks::<{ page::SIZE }>(); | |
| assert_true!(rem.is_empty()); | |
| let online_cpus = (0..num_cpus).filter(|&c| (visited_mask & (1u64 << c)) != 0); | |
| for (chunk, cpu) in pages.iter().zip(online_cpus) { | |
| assert_true!(chunk == &src[cpu * page::SIZE..(cpu + 1) * page::SIZE]); | |
| } | |
| } | |
| /// Dropped-record tracking across write, stop, and rewind transitions. | |
| #[test] | |
| fn dropped_records() { | |
| #[derive(Clone, Copy, PartialEq, Eq)] | |
| enum Action { | |
| Write, | |
| Stop, | |
| Rewind, | |
| } | |
| const DROPPED_PAYLOAD_LEN: usize = 101; | |
| const WRITE_PAYLOAD_LEN: usize = 253; | |
| const { assert!(DROPPED_PAYLOAD_LEN % 8 != 0 && WRITE_PAYLOAD_LEN % 8 != 0) }; | |
| const EXPECTED_DROPPED_BYTES: u32 = ((1 + DROPPED_PAYLOAD_LEN.div_ceil(8)) * 8) as u32; | |
| const EXPECTED_WRITE_BYTES: u32 = ((1 + WRITE_PAYLOAD_LEN.div_ceil(8)) * 8) as u32; | |
| const EVENT_SIZE: usize = size_of::<DroppedRecordDurationEvent>(); | |
| fn on_boot_cpu_i64(f: impl Fn(&InterruptDisableGuard) -> i64 + Sync) -> i64 { | |
| let out = AtomicI64::new(0); | |
| let run = || { | |
| let irqd = InterruptDisableGuard::new(); | |
| out.store(f(&irqd), Ordering::Relaxed); | |
| }; | |
| // SAFETY: `MpIpiTarget::Mask` does not require caller interrupts to be disabled. | |
| unsafe { sync_exec(MpIpiTarget::Mask, cpu_num_to_mask(BOOT_CPU_ID), run) }; | |
| out.load(Ordering::Relaxed) | |
| } | |
| fn on_boot_cpu_status( | |
| f: impl Fn(&InterruptDisableGuard) -> Result<(), Status> + Sync, | |
| ) -> Result<(), Status> { | |
| let raw = on_boot_cpu_i64(|irqd| match f(irqd) { | |
| Ok(()) => 0, | |
| Err(e) => i64::from(e.into_raw()), | |
| }); | |
| Status::ok(raw as i32) | |
| } | |
| let boot_ticks = || on_boot_cpu_i64(|_| KTrace::timestamp().0); | |
| let write_on_boot_cpu = |pcb: &Buffer, payload: &[u8]| { | |
| let hdr = | |
| make_record_header(RecordType::Metadata, 1 + payload.len().div_ceil(8) as u16); | |
| on_boot_cpu_status(|irqd| { | |
| // SAFETY: `ktrace` is local to this test (not installed via | |
| // `with_thread_local_override` and with no concurrent control or producer calls), | |
| // and `on_boot_cpu_status` executes on `BOOT_CPU_ID` (which owns `pcb`) with | |
| // `irqd` held and no uncommitted `Reservation` live. | |
| let res = unsafe { pcb.reserve(irqd, hdr) }; | |
| res.map(|mut res| { | |
| res.write_bytes(payload); | |
| res.commit(); | |
| }) | |
| }) | |
| }; | |
| let emit_drop_stats_on_boot_cpu = |pcb: &Buffer| { | |
| on_boot_cpu_status(|irqd| { | |
| // SAFETY: `ktrace` is local to this test (not installed via | |
| // `with_thread_local_override` and with no concurrent control or producer calls), | |
| // and `on_boot_cpu_status` executes on `BOOT_CPU_ID` (which owns `pcb`) with | |
| // `irqd` held and no uncommitted `Reservation` live. | |
| unsafe { pcb.emit_drop_stats(irqd) } | |
| }) | |
| }; | |
| let mut src = unwrap_some!(Box::<[u8]>::try_new_zeroed_slice(page::SIZE).ok()); | |
| for (i, b) in src.iter_mut().enumerate() { | |
| *b = (i.wrapping_mul(17) ^ 0xa5) as u8; | |
| } | |
| let mut dst = unwrap_some!(Box::<[u8]>::try_new_zeroed_slice(page::SIZE).ok()); | |
| for (action, drain) in [ | |
| (Action::Write, false), | |
| (Action::Write, true), | |
| (Action::Stop, false), | |
| (Action::Stop, true), | |
| (Action::Rewind, false), | |
| ] { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), KTRACE_GRP_META); | |
| let boot_cpu_koid = ktrace.cpu_koid_for_test(BOOT_CPU_ID); | |
| let pcb = &unwrap_some!(ktrace.buffers())[BOOT_CPU_ID as usize]; | |
| assert_ok!(write_on_boot_cpu(pcb, &src[..page::SIZE - 8])); | |
| let start_lower_bound = boot_ticks(); | |
| assert_err!(write_on_boot_cpu(pcb, &src[..DROPPED_PAYLOAD_LEN]), Status::NO_SPACE); | |
| if drain { | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers on `pcb`. | |
| let drained = unsafe { pcb.drain() }; | |
| assert_ok!(drained); | |
| } | |
| if action == Action::Write { | |
| let res = write_on_boot_cpu(pcb, &src[..WRITE_PAYLOAD_LEN]); | |
| if drain { | |
| assert_ok!(res); | |
| } else { | |
| assert_err!(res, Status::NO_SPACE); | |
| } | |
| } else { | |
| let ctl = | |
| if action == Action::Stop { KTRACE_ACTION_STOP } else { KTRACE_ACTION_REWIND }; | |
| assert_ok!(ktrace.control_impl(ctl, 0)); | |
| } | |
| let end_upper_bound = boot_ticks(); | |
| let assert_drop_event = |bytes: &[u8], exp_num: u32, exp_bytes: u32| -> bool { | |
| (unittest::subtest!(|| { | |
| let event = | |
| unwrap_some!(DroppedRecordDurationEvent::read_from_bytes(bytes).ok()); | |
| let hdr = EventRecordHeader::from(event.header); | |
| assert_eq!(RecordType::Event, hdr.record_type()); | |
| assert_eq!(EventType::DurationComplete, hdr.event_type()); | |
| assert_ne!(0, hdr.category_ref()); | |
| assert_le!(start_lower_bound, event.start); | |
| assert_ge!(end_upper_bound, event.end); | |
| assert_eq!(NO_PROCESS_KOID, event.process_id); | |
| assert_eq!(boot_cpu_koid, event.thread_id); | |
| let num_arg = ArgumentHeader::from(event.num_dropped_arg); | |
| let bytes_arg = ArgumentHeader::from(event.bytes_dropped_arg); | |
| assert_eq!(ArgumentType::Uint32, num_arg.arg_type()); | |
| assert_eq!(exp_num, num_arg.value_bits()); | |
| assert_eq!(ArgumentType::Uint32, bytes_arg.arg_type()); | |
| assert_eq!(exp_bytes, bytes_arg.value_bits()); | |
| }))() | |
| }; | |
| dst.fill(0); | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers on `pcb`. | |
| let read_len = unwrap_ok!(unsafe { read_test_buffer(pcb, &mut dst) }); | |
| match (action, drain) { | |
| (Action::Rewind, _) => { | |
| assert_eq!(0, read_len); | |
| assert_ok!(emit_drop_stats_on_boot_cpu(pcb)); | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers on `pcb`. | |
| let post_emit_len = unwrap_ok!(unsafe { read_test_buffer(pcb, &mut dst) }); | |
| assert_eq!(0, post_emit_len); | |
| } | |
| (_, false) => { | |
| assert_eq!(page::SIZE, read_len); | |
| assert_true!(dst[8..page::SIZE] == src[..page::SIZE - 8]); | |
| assert_ok!(emit_drop_stats_on_boot_cpu(pcb)); | |
| let mut stats_buf = [0u8; EVENT_SIZE]; | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers on `pcb`. | |
| let stats_len = unwrap_ok!(unsafe { read_test_buffer(pcb, &mut stats_buf) }); | |
| assert_eq!(EVENT_SIZE, stats_len); | |
| let (exp_num, exp_bytes) = if action == Action::Write { | |
| (2, EXPECTED_DROPPED_BYTES + EXPECTED_WRITE_BYTES) | |
| } else { | |
| (1, EXPECTED_DROPPED_BYTES) | |
| }; | |
| assert_true!(assert_drop_event(&stats_buf, exp_num, exp_bytes)); | |
| } | |
| (Action::Stop, true) => { | |
| assert_eq!(EVENT_SIZE, read_len); | |
| assert_true!(assert_drop_event(&dst[..EVENT_SIZE], 1, EXPECTED_DROPPED_BYTES)); | |
| } | |
| (Action::Write, true) => { | |
| assert_eq!(EVENT_SIZE + EXPECTED_WRITE_BYTES as usize, read_len); | |
| assert_true!(assert_drop_event(&dst[..EVENT_SIZE], 1, EXPECTED_DROPPED_BYTES)); | |
| let start = EVENT_SIZE + 8; | |
| assert_true!(dst[start..start + WRITE_PAYLOAD_LEN] == src[..WRITE_PAYLOAD_LEN]); | |
| } | |
| } | |
| } | |
| } | |
| /// Binary FXT encoding across all Rust ktrace macros. | |
| #[test] | |
| fn rust_macros() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), KTRACE_GRP_META | KTRACE_GRP_SCHEDULER); | |
| let t_before_ticks = KTrace::timestamp(); | |
| let t_before = t_before_ticks.0 as u64; | |
| let target_cpu = { | |
| let _irqd = InterruptDisableGuard::new(); | |
| // SAFETY: Kernel unit tests run in post-SMP kernel thread context with a valid current | |
| // `Thread` and no secondary CPU in early bringup before per-CPU thread-pointer setup; | |
| // `emit_all_test_macros` returns normally without terminating the current thread. | |
| unsafe { | |
| ktrace.with_thread_local_override(|| emit_all_test_macros(t_before_ticks)); | |
| } | |
| curr_cpu_num() | |
| }; | |
| let t_after = KTrace::timestamp().0 as u64; | |
| let buffers = unwrap_some!(ktrace.buffers()); | |
| let mut words_buf = [0u64; 256]; | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let words = | |
| unwrap_ok!(unsafe { read_test_words(&buffers[target_cpu as usize], &mut words_buf) }); | |
| let cpu_tid = ktrace.cpu_koid_for_test(target_cpu); | |
| let mut iter = FxtRecordIter(words); | |
| let mut last_auto_ts = t_before; | |
| for spec in [ | |
| (EventType::Instant, None, None, 101, Trailing::None), | |
| (EventType::Instant, None, Some(cpu_tid), 100, Trailing::None), | |
| (EventType::DurationBegin, None, None, 102, Trailing::None), | |
| (EventType::DurationEnd, None, None, 103, Trailing::None), | |
| (EventType::FlowBegin, None, None, 107, Trailing::Exact(106)), | |
| (EventType::FlowStep, Some(1080), None, 1081, Trailing::Exact(106)), | |
| (EventType::FlowEnd, None, None, 109, Trailing::Exact(106)), | |
| (EventType::DurationComplete, Some(t_before), None, 111, Trailing::AutoTs), | |
| (EventType::DurationComplete, Some(1100), None, 1110, Trailing::Exact(1200)), | |
| ] { | |
| assert_true!(check_u32_event(&mut iter, spec, &mut last_auto_ts, t_after)); | |
| } | |
| // KernelObject & KernelObjectAlways with interned names | |
| for (expected_obj_type, expected_koid, expected_val) in | |
| [(1u8, 112u64, 113u32), (2, 114, 115)] | |
| { | |
| let (raw_hdr, payload) = unwrap_some!(iter.next()); | |
| let hdr = KernelObjectRecordHeader::from(raw_hdr.bits()); | |
| assert_eq!(RecordType::KernelObject, hdr.record_type()); | |
| assert_eq!(3, hdr.record_size()); | |
| assert_eq!(expected_obj_type, hdr.obj_type()); | |
| assert_eq!(1, hdr.arg_count()); | |
| assert_eq!(expected_koid, payload[0]); | |
| assert_true!(check_u32_args(&payload[1..], &[expected_val])); | |
| } | |
| // KernelObject with dynamic inline name and Koid argument | |
| let (ko_raw, ko_payload) = unwrap_some!(iter.next()); | |
| let ko_hdr = KernelObjectRecordHeader::from(ko_raw.bits()); | |
| assert_eq!(RecordType::KernelObject, ko_hdr.record_type()); | |
| assert_eq!(6, ko_hdr.record_size()); | |
| assert_eq!(1, ko_hdr.obj_type()); | |
| assert_eq!(StringRefHeader::inline(12).bits(), ko_hdr.name_ref()); | |
| assert_eq!(1, ko_hdr.arg_count()); | |
| assert_eq!(116, ko_payload[0]); | |
| assert_true!(ko_payload[1..3].as_bytes() == b"dynamic_proc\0\0\0\0"); | |
| let mut ko_args = FxtArgIter(&ko_payload[3..]); | |
| let (ko_arg, ko_arg_payload) = unwrap_some!(ko_args.next()); | |
| assert_eq!(ArgumentType::Koid, ko_arg.arg_type()); | |
| assert_ne!(0, ko_arg.name_ref()); | |
| assert_eq!(117, ko_arg_payload[0]); | |
| assert_true!(ko_args.next().is_none()); | |
| assert_true!(ko_args.is_empty()); | |
| // Cpu DurationComplete with 1 initial + 2 completion arguments | |
| let (sc_raw, sc_payload) = unwrap_some!(iter.next()); | |
| let sc_hdr = EventRecordHeader::from(sc_raw.bits()); | |
| assert_eq!(RecordType::Event, sc_hdr.record_type()); | |
| assert_eq!(8, sc_hdr.record_size()); | |
| assert_eq!(EventType::DurationComplete, sc_hdr.event_type()); | |
| assert_eq!(3, sc_hdr.arg_count()); | |
| assert_eq!(NO_PROCESS_KOID, sc_payload[1]); | |
| assert_eq!(cpu_tid, sc_payload[2]); | |
| assert_ge!(sc_payload[0], last_auto_ts); | |
| assert_le!(sc_payload[0], t_after); | |
| last_auto_ts = sc_payload[0]; | |
| assert_true!(check_u32_args(&sc_payload[3..6], &[0, 1, 2])); | |
| assert_ge!(sc_payload[6], last_auto_ts); | |
| assert_le!(sc_payload[6], t_after); | |
| last_auto_ts = sc_payload[6]; | |
| for spec in [ | |
| (EventType::Counter, None, Some(cpu_tid), 134, Trailing::Exact(133)), | |
| (EventType::Counter, Some(135), Some(cpu_tid), 137, Trailing::Exact(136)), | |
| (EventType::FlowBegin, None, Some(cpu_tid), 139, Trailing::Exact(138)), | |
| (EventType::FlowStep, None, Some(cpu_tid), 140, Trailing::Exact(138)), | |
| (EventType::FlowEnd, None, Some(cpu_tid), 141, Trailing::Exact(138)), | |
| (EventType::DurationComplete, None, Some(cpu_tid), 142, Trailing::AutoTs), | |
| ] { | |
| assert_true!(check_u32_event(&mut iter, spec, &mut last_auto_ts, t_after)); | |
| } | |
| // ContextSwitch with 2 arguments | |
| let (cs_raw, cs_payload) = unwrap_some!(iter.next()); | |
| let cs_hdr = ContextSwitchRecordHeader::from(cs_raw.bits()); | |
| assert_eq!(RecordType::Scheduler, cs_hdr.record_type()); | |
| assert_eq!(6, cs_hdr.record_size()); | |
| assert_eq!(2, cs_hdr.arg_count()); | |
| assert_eq!(2, cs_hdr.cpu_number()); | |
| assert_eq!(3, cs_hdr.thread_state()); | |
| assert_eq!(SchedulerEventType::ContextSwitch, cs_hdr.event_type()); | |
| assert_eq!(120, cs_payload[1]); | |
| assert_eq!(121, cs_payload[2]); | |
| assert_true!(check_u32_args(&cs_payload[3..], &[122, 123])); | |
| // ThreadWakeup with 1 argument | |
| let (tw_raw, tw_payload) = unwrap_some!(iter.next()); | |
| let tw_hdr = ThreadWakeupRecordHeader::from(tw_raw.bits()); | |
| assert_eq!(RecordType::Scheduler, tw_hdr.record_type()); | |
| assert_eq!(4, tw_hdr.record_size()); | |
| assert_eq!(1, tw_hdr.arg_count()); | |
| assert_eq!(5, tw_hdr.cpu_number()); | |
| assert_eq!(SchedulerEventType::ThreadWakeup, tw_hdr.event_type()); | |
| assert_eq!(124, tw_payload[1]); | |
| assert_true!(check_u32_args(&tw_payload[2..], &[125])); | |
| assert_true!(iter.next().is_none()); | |
| assert_true!(iter.is_empty()); | |
| } | |
| /// Starting metadata records match FXT magic, init, string, and CPU records. | |
| #[test] | |
| fn report_metadata_records() { | |
| let percpu_size = 64 * 1024u32; | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init(percpu_size * max_num_cpus(), KTRACE_GRP_META); | |
| let cpu_koid_base = ktrace.cpu_koid_for_test(0); | |
| let target_cpu = { | |
| let _irqd = InterruptDisableGuard::new(); | |
| ktrace.emit_starting_records(cpu_koid_base); | |
| curr_cpu_num() as usize | |
| }; | |
| let mut words_buf = | |
| unwrap_some!(Box::<[u64]>::try_new_zeroed_slice((percpu_size as usize) / 8).ok()); | |
| let buffers = unwrap_some!(ktrace.buffers()); | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let words = unwrap_ok!(unsafe { read_test_words(&buffers[target_cpu], &mut words_buf) }); | |
| let mut iter = FxtRecordIter(words); | |
| let (magic_hdr, magic_payload) = unwrap_some!(iter.next()); | |
| assert_eq!(MAGIC_RECORD_HEADER, magic_hdr.bits()); | |
| assert_true!(magic_payload.is_empty()); | |
| let (init_hdr, init_payload) = unwrap_some!(iter.next()); | |
| assert_eq!(RecordType::Initialization, init_hdr.record_type()); | |
| assert_eq!(2, init_hdr.record_size()); | |
| assert_eq!(ticks_per_second() as u64, init_payload[0]); | |
| // SAFETY: `zircon/kernel/kernel.ld` aligns the table start with `ALIGN(8)`, retains all | |
| // entries via `KEEP(*(__fxt_interned_string_table))`, and places the table in | |
| // `.data.rel.ro` (`PT_GNU_RELRO`, relocated and hardware write-protected by `physboot`). | |
| // All contributors (`intern_string!`, `declare_interned_string!`, C++ | |
| // `FXT_INTERNED_STRING_SECTION`) emit initialized, immutable `'static` `InternedString`s | |
| // aligned to 8 bytes with no overaligned inputs, and `-asan-globals=0` / | |
| // `no_sanitize("address")` prevents sanitizer redzone padding. | |
| let expected_strings = unsafe { InternedString::iter_section() } | |
| .filter(|s| { | |
| let id = s.id(); | |
| id != InternedString::INVALID_ID && id <= InternedString::MAX_ID | |
| }) | |
| .count(); | |
| let (mut string_count, mut cpu_obj_count) = (0usize, 0u32); | |
| for (hdr, payload) in &mut iter { | |
| if hdr.record_type() == RecordType::String { | |
| assert_ne!(0, StringRecordHeader::from(hdr.bits()).string_index()); | |
| string_count += 1; | |
| } else if hdr.record_type() == RecordType::KernelObject { | |
| let ko = KernelObjectRecordHeader::from(hdr.bits()); | |
| assert_eq!(ZX_OBJ_TYPE_THREAD as u8, ko.obj_type()); | |
| assert_eq!(cpu_koid_from_base(cpu_koid_base, cpu_obj_count), payload[0]); | |
| cpu_obj_count += 1; | |
| } else { | |
| assert_true!(false, "unexpected starting metadata record type"); | |
| } | |
| } | |
| assert_true!(iter.is_empty()); | |
| assert_eq!(expected_strings, string_count); | |
| assert_eq!(max_num_cpus(), cpu_obj_count); | |
| } | |
| /// Validate full instance lifecycle, category filtering, and thread-local override routing. | |
| #[test] | |
| fn global_lifecycle() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), 0); | |
| expect_false!(ktrace.writes_enabled()); | |
| expect_eq!(ktrace.categories_bitmask(), 0); | |
| expect_false!(ktrace.is_category_enabled(&CAT_META)); | |
| expect_false!(ktrace.is_category_enabled(&CAT_IRQ)); | |
| assert_ok!( | |
| ktrace.control_impl(KTRACE_ACTION_START, KTRACE_GRP_MEMORY | KTRACE_GRP_CONTENTION) | |
| ); | |
| expect_true!(ktrace.writes_enabled()); | |
| expect_false!(ktrace.is_category_enabled(&CAT_META)); | |
| expect_true!(ktrace.is_category_enabled(&CAT_MEMORY)); | |
| expect_false!(ktrace.is_category_enabled(&CAT_SCHEDULER)); | |
| expect_true!(ktrace.is_category_enabled(&CAT_CONTENTION)); | |
| expect_false!(ktrace.is_category_enabled(&CAT_IPC)); | |
| expect_false!(KTrace::with_instance(|kt| ptr::eq(kt, &ktrace))); | |
| assert_ok!(ktrace.control_impl(KTRACE_ACTION_START, KTRACE_GRP_META | KTRACE_GRP_MEMORY)); | |
| let (override_ok, cpu) = { | |
| let _irqd = InterruptDisableGuard::new(); | |
| // SAFETY: Kernel unit tests run in post-SMP kernel thread context with a valid current | |
| // `Thread` and no secondary CPU in early bringup before per-CPU thread-pointer setup; | |
| // the test subtest returns normally without terminating the current thread. | |
| let ok = unsafe { | |
| ktrace.with_thread_local_override(unittest::subtest!(|| { | |
| expect_true!(KTrace::with_instance(|kt| ptr::eq(kt, &ktrace))); | |
| instant!(CAT_IRQ, "suppressed_event", "arg" => 99i32); | |
| instant!(CAT_META, "my_event", "arg1" => 42i32, "arg2" => "hello"); | |
| })) | |
| }; | |
| (ok, curr_cpu_num() as usize) | |
| }; | |
| assert_true!(override_ok); | |
| expect_false!(KTrace::with_instance(|kt| ptr::eq(kt, &ktrace))); | |
| let buf = &unwrap_some!(ktrace.buffers())[cpu]; | |
| let mut words_buf = [0u64; 16]; | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let words = unwrap_ok!(unsafe { read_test_words(buf, &mut words_buf) }); | |
| let mut iter = FxtRecordIter(words); | |
| let (raw_hdr, payload) = unwrap_some!(iter.next()); | |
| expect_true!(iter.next().is_none()); | |
| expect_true!(iter.is_empty()); | |
| let ev_hdr = EventRecordHeader::from(raw_hdr.bits()); | |
| expect_eq!(ev_hdr.record_type(), RecordType::Event); | |
| expect_eq!(ev_hdr.record_size(), 7); | |
| expect_eq!(ev_hdr.event_type(), EventType::Instant); | |
| expect_eq!(ev_hdr.arg_count(), 2); | |
| expect_eq!(ev_hdr.category_ref(), CAT_META.label().id()); | |
| expect_ne!(ev_hdr.name_ref(), 0); | |
| expect_ne!(payload[0], 0); | |
| // SAFETY: Kernel unit tests run after `LK_INIT_LEVEL_THREADING` on a live `Thread`. | |
| let current_thread = unsafe { ThreadPtr::current() }; | |
| // SAFETY: `current_thread` is the currently executing live `Thread`. | |
| let FxtRef { pid, tid } = unsafe { current_thread.fxt_ref() }; | |
| expect_eq!(payload[1], pid); | |
| expect_eq!(payload[2], tid); | |
| let mut args = FxtArgIter(&payload[3..]); | |
| let (arg1, arg1_payload) = unwrap_some!(args.next()); | |
| expect_eq!(arg1.arg_type(), ArgumentType::Int32); | |
| expect_eq!(arg1.value_bits(), 42); | |
| expect_ne!(arg1.name_ref(), 0); | |
| expect_true!(arg1_payload.is_empty()); | |
| let (arg2, arg2_payload) = unwrap_some!(args.next()); | |
| expect_eq!(arg2.arg_type(), ArgumentType::String); | |
| expect_eq!(arg2.value_bits(), u32::from(StringRefHeader::inline(5).bits())); | |
| expect_ne!(arg2.name_ref(), 0); | |
| expect_true!(arg2_payload.as_bytes() == b"hello\0\0\0"); | |
| expect_true!(args.next().is_none()); | |
| expect_true!(args.is_empty()); | |
| } | |
| /// Verifies `StringRef::into_parts` across interned, inline, `CStr`, and NUL-padded inputs. | |
| #[test] | |
| fn test_string_ref() { | |
| let inline = |n| StringRefHeader::inline(n).bits(); | |
| let cases: [(StringRef<'_>, u16, &[u8]); 7] = [ | |
| (StringRef::from(PROCESS_STR), StringRefHeader::indexed(PROCESS_STR.id()).bits(), b""), | |
| (StringRef::from(&b"foo"[..]), inline(3), b"foo"), | |
| (StringRef::from(&b"longer_test_string"[..]), inline(18), b"longer_test_string"), | |
| (StringRef::from("hello_world"), inline(11), b"hello_world"), | |
| (StringRef::from(c"cstr_proc"), inline(9), b"cstr_proc"), | |
| (StringRef::from(&b"proc\0\0\0\0\0\0"[..]), inline(4), b"proc"), | |
| (StringRef::from_bytes(&b"proc_name\0ignored"[..]), inline(9), b"proc_name"), | |
| ]; | |
| for (str_ref, expected_hdr, expected_bytes) in cases { | |
| let (hdr, bytes) = str_ref.into_parts(); | |
| expect_eq!(expected_hdr, hdr); | |
| expect_true!(expected_bytes == bytes); | |
| } | |
| } | |
| /// Verifies argument size and header encoding across all supported `ArgValue` variants. | |
| #[test] | |
| fn test_all_argument_types() { | |
| enum Expected<'a> { | |
| Inline(u32), | |
| Word(u64), | |
| Bytes(u32, &'a [u8]), | |
| } | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), KTRACE_GRP_META); | |
| let target_cpu = { | |
| let _irqd = InterruptDisableGuard::new(); | |
| // SAFETY: Kernel unit tests run in post-SMP kernel thread context with a valid current | |
| // `Thread` and no secondary CPU in early bringup before per-CPU thread-pointer setup; | |
| // the closure only emits one event and returns normally without terminating the thread. | |
| unsafe { | |
| ktrace.with_thread_local_override(|| { | |
| instant!( | |
| CAT_META, | |
| "all_args", | |
| PROCESS_STR => true, | |
| PROCESS_STR => -123i32, | |
| PROCESS_STR => 456u32, | |
| PROCESS_STR => -789i64, | |
| PROCESS_STR => 101_112u64, | |
| PROCESS_STR => "hello_world", | |
| PROCESS_STR => PROCESS_STR, | |
| PROCESS_STR => ArgValue::StringId(0x2345), | |
| PROCESS_STR => ArgValue::Pointer(0x1234_5678), | |
| PROCESS_STR => Koid(9999), | |
| PROCESS_STR => &b"blob_data"[..], | |
| ); | |
| }); | |
| } | |
| curr_cpu_num() as usize | |
| }; | |
| let buf = &unwrap_some!(ktrace.buffers())[target_cpu]; | |
| let mut words_buf = [0u64; 32]; | |
| // SAFETY: Test-local `ktrace` has no concurrent consumers. | |
| let words = unwrap_ok!(unsafe { read_test_words(buf, &mut words_buf) }); | |
| let mut rec_iter = FxtRecordIter(words); | |
| let (raw_hdr, rec_payload) = unwrap_some!(rec_iter.next()); | |
| expect_true!(rec_iter.next().is_none()); | |
| expect_true!(rec_iter.is_empty()); | |
| expect_eq!(11, EventRecordHeader::from(raw_hdr.bits()).arg_count()); | |
| let inline_str = |n| u32::from(StringRefHeader::inline(n).bits()); | |
| let indexed_str = |id| u32::from(StringRefHeader::indexed(id).bits()); | |
| let expected = [ | |
| (ArgumentType::Bool, Expected::Inline(1)), | |
| (ArgumentType::Int32, Expected::Inline(-123i32 as u32)), | |
| (ArgumentType::Uint32, Expected::Inline(456)), | |
| (ArgumentType::Int64, Expected::Word(-789i64 as u64)), | |
| (ArgumentType::Uint64, Expected::Word(101_112)), | |
| (ArgumentType::String, Expected::Bytes(inline_str(11), b"hello_world\0\0\0\0\0")), | |
| (ArgumentType::String, Expected::Inline(indexed_str(PROCESS_STR.id()))), | |
| (ArgumentType::String, Expected::Inline(indexed_str(0x2345))), | |
| (ArgumentType::Pointer, Expected::Word(0x1234_5678)), | |
| (ArgumentType::Koid, Expected::Word(9999)), | |
| (ArgumentType::Blob, Expected::Bytes(9, b"blob_data\0\0\0\0\0\0\0")), | |
| ]; | |
| let mut arg_iter = FxtArgIter(&rec_payload[3..]); | |
| for (expected_type, expected_payload) in expected { | |
| let (hdr, payload) = unwrap_some!(arg_iter.next()); | |
| expect_eq!(expected_type, hdr.arg_type()); | |
| expect_eq!(PROCESS_STR.id(), hdr.name_ref()); | |
| match expected_payload { | |
| Expected::Inline(bits) => { | |
| expect_eq!(1, hdr.size_words()); | |
| expect_eq!(bits, hdr.value_bits()); | |
| expect_true!(payload.is_empty()); | |
| } | |
| Expected::Word(word) => { | |
| expect_eq!(2, hdr.size_words()); | |
| expect_eq!(0, hdr.value_bits()); | |
| expect_eq!(word, payload[0]); | |
| } | |
| Expected::Bytes(bits, bytes) => { | |
| expect_eq!(1 + (bytes.len() / 8) as u16, hdr.size_words()); | |
| expect_eq!(bits, hdr.value_bits()); | |
| expect_true!(bytes == payload.as_bytes()); | |
| } | |
| } | |
| } | |
| expect_true!(arg_iter.next().is_none()); | |
| expect_true!(arg_iter.is_empty()); | |
| } | |
| /// A scope with arguments can be bound to a local variable. | |
| #[test] | |
| fn scope_owns_arguments() { | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), 0); | |
| // SAFETY: Kernel unit tests run in post-SMP kernel thread context with a valid current | |
| // `Thread` and no secondary CPU in early bringup before per-CPU thread-pointer setup; | |
| // the test subtest returns normally without terminating the current thread. | |
| assert_true!(unsafe { | |
| ktrace.with_thread_local_override(unittest::subtest!(|| { | |
| let value = KTrace::timestamp().0 as u64; | |
| expect_true!( | |
| begin_scope!(CAT_META, "scope_owns_arguments", "val" => value).is_none() | |
| ); | |
| ktrace.set_categories_bitmask(KTRACE_GRP_META); | |
| let scope = | |
| unwrap_some!(begin_scope!(CAT_META, "scope_owns_arguments", "val" => value)); | |
| expect_ne!(scope.timestamp.0, 0); | |
| expect_eq!(scope.args.len(), 1); | |
| expect_true!(scope.args[0].value == ArgValue::Uint64(value)); | |
| })) | |
| }); | |
| } | |
| /// Verifies disabled and enabled compile-time conditional trace scopes and `as_erased()`. | |
| #[test] | |
| fn disabled_cond_scope_is_zero_sized() { | |
| fn mark(flag: &mut bool, val: u64) -> u64 { | |
| *flag = true; | |
| val | |
| } | |
| let ktrace = unwrap_some!(KTrace::new_for_test()); | |
| ktrace.init((page::SIZE as u32) * max_num_cpus(), KTRACE_GRP_META); | |
| // SAFETY: Kernel unit tests run in post-SMP kernel thread context with a valid current | |
| // `Thread` and no secondary CPU in early bringup before per-CPU thread-pointer setup; | |
| // the test subtest returns normally without terminating the current thread. | |
| assert_true!(unsafe { | |
| ktrace.with_thread_local_override(unittest::subtest!(|| { | |
| expect_true!(KTrace::category_enabled(&CAT_META)); | |
| let (mut begin_evaluated, mut end_evaluated) = (false, false); | |
| let local_buf = *b"borrowed"; | |
| let local_str = unwrap_some!(core::str::from_utf8(&local_buf).ok()); | |
| let mut scope = begin_scope_cond!( | |
| false, | |
| CAT_META, | |
| "disabled_scope", | |
| "begin_arg" => mark(&mut begin_evaluated, 1), | |
| "borrowed" => local_str, | |
| ); | |
| expect_eq!(size_of_val(&scope), 0); | |
| expect_false!(begin_evaluated); | |
| expect_true!(scope.as_erased().is_none()); | |
| end_scope!(scope, "end_arg" => mark(&mut end_evaluated, 2)); | |
| expect_false!(end_evaluated); | |
| struct AssocConstCaller; | |
| impl AssocConstCaller { | |
| const DISABLED: bool = false; | |
| fn check() -> usize { | |
| let s = begin_scope_cond!(Self::DISABLED, CAT_META, "assoc_disabled"); | |
| size_of_val(&s) | |
| } | |
| } | |
| expect_eq!(AssocConstCaller::check(), 0); | |
| let cpu_scope = cpu_begin_scope_cond!(false, CAT_META, "disabled_cpu_scope"); | |
| expect_eq!(size_of_val(&cpu_scope), 0); | |
| drop(cpu_scope); | |
| let mut erased_scope = begin_scope_cond!(true, CAT_META, "erased_scope"); | |
| unwrap_some!(erased_scope.as_erased()).end(); | |
| expect_true!(erased_scope.is_none()); | |
| expect_true!(erased_scope.as_erased().is_none()); | |
| let mut enabled_scope = begin_scope_cond!( | |
| true, | |
| CAT_META, | |
| "enabled_scope", | |
| "begin_arg" => mark(&mut begin_evaluated, 1), | |
| ); | |
| expect_true!(size_of_val(&enabled_scope) > 0); | |
| expect_true!(begin_evaluated); | |
| expect_true!(enabled_scope.as_erased().is_some()); | |
| end_scope!(enabled_scope, "end_arg" => mark(&mut end_evaluated, 2)); | |
| expect_true!(end_evaluated); | |
| })) | |
| }); | |
| } | |
| } |