Debian Codegraph @

third_party/rust/minidump-writer/src/mac/mach.rs

raw
1 //! Contains various helpers to improve and expand on the bindings provided
2 //! by `mach2`
3
4 // Just exports all of the mach functions we use into a flat list
5 pub use mach2::{
6 kern_return::{kern_return_t, KERN_SUCCESS},
7 port::mach_port_name_t,
8 task::{self, task_threads},
9 task_info,
10 thread_act::thread_get_state,
11 traps::mach_task_self,
12 vm::{mach_vm_deallocate, mach_vm_read, mach_vm_region_recurse},
13 vm_region::vm_region_submap_info_64,
14 };
15
16 /// A Mach kernel error.
17 ///
18 /// See <usr/include/mach/kern_return.h>.
19 #[derive(thiserror::Error, Debug)]
20 pub enum KernelError {
21 #[error("specified address is not currently valid")]
22 InvalidAddress = 1,
23 #[error("specified memory is valid, but does not permit the required forms of access")]
24 ProtectionFailure = 2,
25 #[error("the address range specified is already in use, or no address range of the size specified could be found")]
26 NoSpace = 3,
27 #[error("the function requested was not applicable to this type of argument, or an argument is invalid")]
28 InvalidArgument = 4,
29 #[error("the function could not be performed")]
30 Failure = 5,
31 #[error("system resource could not be allocated to fulfill this request")]
32 ResourceShortage = 6,
33 #[error("the task in question does not hold receive rights for the port argument")]
34 NotReceiver = 7,
35 #[error("bogus access restriction")]
36 NoAccess = 8,
37 #[error(
38 "during a page fault, the target address refers to a memory object that has been destroyed"
39 )]
40 MemoryFailure = 9,
41 #[error(
42 "during a page fault, the memory object indicated that the data could not be returned"
43 )]
44 MemoryError = 10,
45 #[error("the receive right is already a member of the portset")]
46 AlreadyInSet = 11,
47 #[error("the receive right is not a member of a port set")]
48 NotInSet = 12,
49 #[error("the name already denotes a right in the task")]
50 NameExists = 13,
51 #[error("the operation was aborted")]
52 Aborted = 14,
53 #[error("the name doesn't denote a right in the task")]
54 InvalidName = 15,
55 #[error("target task isn't an active task")]
56 InvalidTask = 16,
57 #[error("the name denotes a right, but not an appropriate right")]
58 InvalidRight = 17,
59 #[error("a blatant range error")]
60 InvalidValue = 18,
61 #[error("operation would overflow limit on user-references")]
62 UserRefsOverflow = 19,
63 #[error("the supplied port capability is improper")]
64 InvalidCapability = 20,
65 #[error("the task already has send or receive rights for the port under another name")]
66 RightExists = 21,
67 #[error("target host isn't actually a host")]
68 InvalidHost = 22,
69 #[error("an attempt was made to supply 'precious' data for memory that is already present in a memory object")]
70 MemoryPresent = 23,
71 // These 2 are errors which should only ever be seen by the kernel itself
72 //MemoryDataMoved = 24,
73 //MemoryRestartCopy = 25,
74 #[error("an argument applied to assert processor set privilege was not a processor set control port")]
75 InvalidProcessorSet = 26,
76 #[error("the specified scheduling attributes exceed the thread's limits")]
77 PolicyLimit = 27,
78 #[error("the specified scheduling policy is not currently enabled for the processor set")]
79 InvalidPolicy = 28,
80 #[error("the external memory manager failed to initialize the memory object")]
81 InvalidObject = 29,
82 #[error(
83 "a thread is attempting to wait for an event for which there is already a waiting thread"
84 )]
85 AlreadyWaiting = 30,
86 #[error("an attempt was made to destroy the default processor set")]
87 DefaultSet = 31,
88 #[error("an attempt was made to fetch an exception port that is protected, or to abort a thread while processing a protected exception")]
89 ExceptionProtected = 32,
90 #[error("a ledger was required but not supplied")]
91 InvalidLedger = 33,
92 #[error("the port was not a memory cache control port")]
93 InvalidMemoryControl = 34,
94 #[error("an argument supplied to assert security privilege was not a host security port")]
95 InvalidSecurity = 35,
96 #[error("thread_depress_abort was called on a thread which was not currently depressed")]
97 NotDepressed = 36,
98 #[error("object has been terminated and is no longer available")]
99 Terminated = 37,
100 #[error("lock set has been destroyed and is no longer available")]
101 LockSetDestroyed = 38,
102 #[error("the thread holding the lock terminated before releasing the lock")]
103 LockUnstable = 39,
104 #[error("the lock is already owned by another thread")]
105 LockOwned = 40,
106 #[error("the lock is already owned by the calling thread")]
107 LockOwnedSelf = 41,
108 #[error("semaphore has been destroyed and is no longer available")]
109 SemaphoreDestroyed = 42,
110 #[error("return from RPC indicating the target server was terminated before it successfully replied")]
111 RpcServerTerminated = 43,
112 #[error("terminate an orphaned activation")]
113 RpcTerminateOrphan = 44,
114 #[error("allow an orphaned activation to continue executing")]
115 RpcContinueOrphan = 45,
116 #[error("empty thread activation (No thread linked to it)")]
117 NotSupported = 46,
118 #[error("remote node down or inaccessible")]
119 NodeDown = 47,
120 #[error("a signalled thread was not actually waiting")]
121 NotWaiting = 48,
122 #[error("some thread-oriented operation (semaphore_wait) timed out")]
123 OperationTimedOut = 49,
124 #[error("during a page fault, indicates that the page was rejected as a result of a signature check")]
125 CodesignError = 50,
126 #[error("the requested property cannot be changed at this time")]
127 PoicyStatic = 51,
128 #[error("the provided buffer is of insufficient size for the requested data")]
129 InsufficientBufferSize = 52,
130 #[error("denied by security policy")]
131 Denied = 53,
132 #[error("the KC on which the function is operating is missing")]
133 MissingKC = 54,
134 #[error("the KC on which the function is operating is invalid")]
135 InvalidKC = 55,
136 #[error("a search or query operation did not return a result")]
137 NotFound = 56,
138 }
139
140 impl From<mach2::kern_return::kern_return_t> for KernelError {
141 fn from(kr: mach2::kern_return::kern_return_t) -> Self {
142 use mach2::kern_return::*;
143
144 match kr {
145 KERN_INVALID_ADDRESS => Self::InvalidAddress,
146 KERN_PROTECTION_FAILURE => Self::ProtectionFailure,
147 KERN_NO_SPACE => Self::NoSpace,
148 KERN_INVALID_ARGUMENT => Self::InvalidArgument,
149 KERN_FAILURE => Self::Failure,
150 KERN_RESOURCE_SHORTAGE => Self::ResourceShortage,
151 KERN_NOT_RECEIVER => Self::NotReceiver,
152 KERN_NO_ACCESS => Self::NoAccess,
153 KERN_MEMORY_FAILURE => Self::MemoryFailure,
154 KERN_MEMORY_ERROR => Self::MemoryError,
155 KERN_ALREADY_IN_SET => Self::AlreadyInSet,
156 KERN_NAME_EXISTS => Self::NameExists,
157 KERN_INVALID_NAME => Self::InvalidName,
158 KERN_INVALID_TASK => Self::InvalidTask,
159 KERN_INVALID_RIGHT => Self::InvalidRight,
160 KERN_INVALID_VALUE => Self::InvalidValue,
161 KERN_UREFS_OVERFLOW => Self::UserRefsOverflow,
162 KERN_INVALID_CAPABILITY => Self::InvalidCapability,
163 KERN_RIGHT_EXISTS => Self::RightExists,
164 KERN_INVALID_HOST => Self::InvalidHost,
165 KERN_MEMORY_PRESENT => Self::MemoryPresent,
166 KERN_INVALID_PROCESSOR_SET => Self::InvalidProcessorSet,
167 KERN_POLICY_LIMIT => Self::PolicyLimit,
168 KERN_INVALID_POLICY => Self::InvalidPolicy,
169 KERN_INVALID_OBJECT => Self::InvalidObject,
170 KERN_ALREADY_WAITING => Self::AlreadyWaiting,
171 KERN_DEFAULT_SET => Self::DefaultSet,
172 KERN_EXCEPTION_PROTECTED => Self::ExceptionProtected,
173 KERN_INVALID_LEDGER => Self::InvalidLedger,
174 KERN_INVALID_MEMORY_CONTROL => Self::InvalidMemoryControl,
175 KERN_INVALID_SECURITY => Self::InvalidSecurity,
176 KERN_NOT_DEPRESSED => Self::NotDepressed,
177 KERN_TERMINATED => Self::Terminated,
178 KERN_LOCK_SET_DESTROYED => Self::LockSetDestroyed,
179 KERN_LOCK_UNSTABLE => Self::LockUnstable,
180 KERN_LOCK_OWNED => Self::LockOwned,
181 KERN_LOCK_OWNED_SELF => Self::LockOwnedSelf,
182 KERN_SEMAPHORE_DESTROYED => Self::SemaphoreDestroyed,
183 KERN_RPC_SERVER_TERMINATED => Self::RpcServerTerminated,
184 KERN_RPC_TERMINATE_ORPHAN => Self::RpcTerminateOrphan,
185 KERN_RPC_CONTINUE_ORPHAN => Self::RpcContinueOrphan,
186 KERN_NOT_SUPPORTED => Self::NotSupported,
187 KERN_NODE_DOWN => Self::NodeDown,
188 KERN_NOT_WAITING => Self::NotWaiting,
189 KERN_OPERATION_TIMED_OUT => Self::OperationTimedOut,
190 KERN_CODESIGN_ERROR => Self::CodesignError,
191 KERN_POLICY_STATIC => Self::PoicyStatic,
192 52 => Self::InsufficientBufferSize,
193 53 => Self::Denied,
194 54 => Self::MissingKC,
195 55 => Self::InvalidKC,
196 56 => Self::NotFound,
197 // This should never happen given a result from a mach call, but
198 // in that case we just use `Failure` as the mach header itself
199 // describes it as a catch all
200 _ => Self::Failure,
201 }
202 }
203 }
204
205 // From /usr/include/mach/machine/thread_state.h
206 pub const THREAD_STATE_MAX: usize = 1296;
207
208 cfg_if::cfg_if! {
209 if #[cfg(target_arch = "x86_64")] {
210 /// x86_THREAD_STATE64 in /usr/include/mach/i386/thread_status.h
211 pub const THREAD_STATE_FLAVOR: u32 = 4;
212
213 pub type ArchThreadState = mach2::structs::x86_thread_state64_t;
214 } else if #[cfg(target_arch = "aarch64")] {
215 /// ARM_THREAD_STATE64 in /usr/include/mach/arm/thread_status.h
216 pub const THREAD_STATE_FLAVOR: u32 = 6;
217
218 // Missing from mach2 atm
219 // _STRUCT_ARM_THREAD_STATE64 from /usr/include/mach/arm/_structs.h
220 #[repr(C)]
221 pub struct Arm64ThreadState {
222 pub x: [u64; 29],
223 pub fp: u64,
224 pub lr: u64,
225 pub sp: u64,
226 pub pc: u64,
227 pub cpsr: u32,
228 __pad: u32,
229 }
230
231 pub type ArchThreadState = Arm64ThreadState;
232 } else {
233 compile_error!("unsupported target arch");
234 }
235 }
236
237 #[repr(C, align(8))]
238 pub struct ThreadState {
239 pub state: [u32; THREAD_STATE_MAX],
240 pub state_size: u32,
241 }
242
243 impl Default for ThreadState {
244 fn default() -> Self {
245 Self {
246 state: [0u32; THREAD_STATE_MAX],
247 state_size: (THREAD_STATE_MAX * std::mem::size_of::<u32>()) as u32,
248 }
249 }
250 }
251
252 impl ThreadState {
253 /// Gets the program counter
254 #[inline]
255 pub fn pc(&self) -> u64 {
256 cfg_if::cfg_if! {
257 if #[cfg(target_arch = "x86_64")] {
258 self.arch_state().__rip
259 } else if #[cfg(target_arch = "aarch64")] {
260 self.arch_state().pc
261 }
262 }
263 }
264
265 /// Gets the stack pointer
266 #[inline]
267 pub fn sp(&self) -> u64 {
268 cfg_if::cfg_if! {
269 if #[cfg(target_arch = "x86_64")] {
270 self.arch_state().__rsp
271 } else if #[cfg(target_arch = "aarch64")] {
272 self.arch_state().sp
273 }
274 }
275 }
276
277 /// Converts the raw binary blob into the architecture specific state
278 #[inline]
279 pub fn arch_state(&self) -> &ArchThreadState {
280 // SAFETY: hoping the kernel isn't lying
281 unsafe { &*(self.state.as_ptr().cast()) }
282 }
283 }
284
285 /// Minimal trait that just pairs a structure that can be filled out by
286 /// [`mach2::task::task_info`] with the "flavor" that tells it the info we
287 /// actually want to retrieve
288 pub trait TaskInfo {
289 /// One of the `MACH_*_TASK` integers. I assume it's very bad if you implement
290 /// this trait and provide the wrong flavor for the struct
291 const FLAVOR: u32;
292 }
293
294 /// Minimal trait that just pairs a structure that can be filled out by
295 /// [`thread_info`] with the "flavor" that tells it the info we
296 /// actually want to retrieve
297 pub trait ThreadInfo {
298 /// One of the `THREAD_*` integers. I assume it's very bad if you implement
299 /// this trait and provide the wrong flavor for the struct
300 const FLAVOR: u32;
301 }
302
303 /// <usr/include/mach-o/loader.h>, the file type for the main executable image
304 pub const MH_EXECUTE: u32 = 0x2;
305 /// <usr/include/mach-o/loader.h>, the file type dyld, the dynamic loader
306 pub const MH_DYLINKER: u32 = 0x7;
307 // usr/include/mach-o/loader.h, magic number for MachHeader
308 pub const MH_MAGIC_64: u32 = 0xfeedfacf;
309
310 /// Load command constants from usr/include/mach-o/loader.h
311 #[repr(u32)]
312 #[derive(Debug)]
313 pub enum LoadCommandKind {
314 /// Command to map a segment
315 Segment = 0x19,
316 /// Dynamically linked shared lib ident
317 IdDylib = 0xd,
318 /// Image uuid
319 Uuid = 0x1b,
320 /// Load a dynamic linker. Should only be on MH_EXECUTE (main executable)
321 /// images when the dynamic linker is overriden
322 LoadDylinker = 0xe,
323 /// Dynamic linker identification
324 IdDylinker = 0xf,
325 }
326
327 impl LoadCommandKind {
328 #[inline]
329 fn from_u32(kind: u32) -> Option<Self> {
330 Some(if kind == Self::Segment as u32 {
331 Self::Segment
332 } else if kind == Self::IdDylib as u32 {
333 Self::IdDylib
334 } else if kind == Self::Uuid as u32 {
335 Self::Uuid
336 } else if kind == Self::LoadDylinker as u32 {
337 Self::LoadDylinker
338 } else if kind == Self::IdDylinker as u32 {
339 Self::IdDylinker
340 } else {
341 return None;
342 })
343 }
344 }
345
346 /// The header at the beginning of every (valid) Mach image
347 ///
348 /// <usr/include/mach-o/loader.h>
349 #[repr(C)]
350 #[derive(Clone)]
351 pub struct MachHeader {
352 /// Mach magic number identifier, this is used to validate the header is valid
353 pub magic: u32,
354 /// `cpu_type_t` cpu specifier
355 pub cpu_type: i32,
356 /// `cpu_subtype_t` machine specifier
357 pub cpu_sub_type: i32,
358 /// Type of file, eg. [`MH_EXECUTE`] for the main executable
359 pub file_type: u32,
360 /// Number of load commands for the image
361 pub num_commands: u32,
362 /// Size in bytes of all of the load commands
363 pub size_commands: u32,
364 pub flags: u32,
365 __reserved: u32,
366 }
367
368 /// Every load command is a variable sized struct depending on its type, but
369 /// they all include the fields in this struct at the beginning
370 ///
371 /// <usr/include/mach-o/loader.h>
372 #[repr(C)]
373 pub struct LoadCommandBase {
374 /// Type of load command `LC_*`
375 pub cmd: u32,
376 /// Total size of the command in bytes
377 pub cmd_size: u32,
378 }
379
380 /// The 64-bit segment load command indicates that a part of this file is to be
381 /// mapped into a 64-bit task's address space. If the 64-bit segment has
382 /// sections then section_64 structures directly follow the 64-bit segment
383 /// command and their size is reflected in `cmdsize`.
384 #[repr(C)]
385 pub struct SegmentCommand64 {
386 cmd: u32,
387 pub cmd_size: u32,
388 /// String name of the section
389 pub segment_name: [u8; 16],
390 /// Memory address the segment is mapped to
391 pub vm_addr: u64,
392 /// Total size of the segment
393 pub vm_size: u64,
394 /// File offset of the segment
395 pub file_off: u64,
396 /// Amount mapped from the file
397 pub file_size: u64,
398 /// Maximum VM protection
399 pub max_prot: i32,
400 /// Initial VM protection
401 pub init_prot: i32,
402 /// Number of sections in the segment
403 pub num_sections: u32,
404 pub flags: u32,
405 }
406
407 /// Dynamically linked shared libraries are identified by two things. The
408 /// pathname (the name of the library as found for execution), and the
409 /// compatibility version number. The pathname must match and the compatibility
410 /// number in the user of the library must be greater than or equal to the
411 /// library being used. The time stamp is used to record the time a library was
412 /// built and copied into user so it can be use to determined if the library used
413 /// at runtime is exactly the same as used to built the program.
414 #[repr(C)]
415 #[derive(Debug)]
416 pub struct Dylib {
417 /// Offset from the load command start to the pathname
418 pub name: u32,
419 /// Library's build time stamp
420 pub timestamp: u32,
421 /// Library's current version number
422 pub current_version: u32,
423 /// Library's compatibility version number
424 pub compatibility_version: u32,
425 }
426
427 /// A dynamically linked shared library (filetype == MH_DYLIB in the mach header)
428 /// contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library.
429 /// An object that uses a dynamically linked shared library also contains a
430 /// dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or
431 /// LC_REEXPORT_DYLIB) for each library it uses.
432 #[repr(C)]
433 pub struct DylibCommand {
434 cmd: u32,
435 /// Total size of the command in bytes, including pathname string
436 pub cmd_size: u32,
437 /// Library identification
438 pub dylib: Dylib,
439 }
440
441 /// A program that uses a dynamic linker contains a dylinker_command to identify
442 /// the name of the dynamic linker (LC_LOAD_DYLINKER). And a dynamic linker
443 /// contains a dylinker_command to identify the dynamic linker (LC_ID_DYLINKER).
444 /// A file can have at most one of these.
445 /// This struct is also used for the LC_DYLD_ENVIRONMENT load command and
446 /// contains string for dyld to treat like environment variable.
447 #[repr(C)]
448 struct DylinkerCommandRepr {
449 /// LC_ID_DYLINKER, LC_LOAD_DYLINKER or LC_DYLD_ENVIRONMENT
450 cmd: u32,
451 /// includes pathname string
452 cmd_size: u32,
453 /// Dynamic linker's path name, an offset from the load command address
454 name: u32,
455 }
456
457 pub struct DylinkerCommand<'buf> {
458 /// LC_ID_DYLINKER, LC_LOAD_DYLINKER or LC_DYLD_ENVIRONMENT
459 pub cmd: u32,
460 /// includes pathname string
461 pub cmd_size: u32,
462 /// The offset from the load command where the path was read
463 pub name_offset: u32,
464 /// Dynamic linker's path name
465 pub name: &'buf str,
466 }
467
468 /// The uuid load command contains a single 128-bit unique random number that
469 /// identifies an object produced by the static link editor.
470 #[repr(C)]
471 pub struct UuidCommand {
472 cmd: u32,
473 pub cmd_size: u32,
474 /// The UUID. The components are in big-endian regardless of the host architecture
475 pub uuid: [u8; 16],
476 }
477
478 /// A block of load commands for a particular image
479 pub struct LoadCommands {
480 /// The block of memory containing all of the load commands
481 pub buffer: Vec<u8>,
482 /// The number of actual load commmands that _should_ be in the buffer
483 pub count: u32,
484 }
485
486 impl LoadCommands {
487 /// Retrieves an iterator over the load commands in the contained buffer
488 #[inline]
489 pub fn iter(&self) -> LoadCommandsIter<'_> {
490 LoadCommandsIter {
491 buffer: &self.buffer,
492 count: self.count,
493 }
494 }
495 }
496
497 /// A single load command
498 pub enum LoadCommand<'buf> {
499 Segment(&'buf SegmentCommand64),
500 Dylib(&'buf DylibCommand),
501 Uuid(&'buf UuidCommand),
502 DylinkerCommand(DylinkerCommand<'buf>),
503 }
504
505 pub struct LoadCommandsIter<'buf> {
506 buffer: &'buf [u8],
507 count: u32,
508 }
509
510 impl<'buf> Iterator for LoadCommandsIter<'buf> {
511 type Item = LoadCommand<'buf>;
512
513 fn next(&mut self) -> Option<Self::Item> {
514 // SAFETY: we're interpreting raw bytes as C structs, we try and be safe
515 unsafe {
516 loop {
517 if self.count == 0 || self.buffer.len() < std::mem::size_of::<LoadCommandBase>() {
518 return None;
519 }
520
521 let header = &*(self.buffer.as_ptr().cast::<LoadCommandBase>());
522
523 // This would mean we've been lied to by the MachHeader and either
524 // the size_commands field was too small, or the num_command was
525 // too large
526 if header.cmd_size as usize > self.buffer.len() {
527 return None;
528 }
529
530 let cmd = LoadCommandKind::from_u32(header.cmd).and_then(|kind| {
531 Some(match kind {
532 LoadCommandKind::Segment => LoadCommand::Segment(
533 &*(self.buffer.as_ptr().cast::<SegmentCommand64>()),
534 ),
535 LoadCommandKind::IdDylib => {
536 LoadCommand::Dylib(&*(self.buffer.as_ptr().cast::<DylibCommand>()))
537 }
538 LoadCommandKind::Uuid => {
539 LoadCommand::Uuid(&*(self.buffer.as_ptr().cast::<UuidCommand>()))
540 }
541 LoadCommandKind::LoadDylinker | LoadCommandKind::IdDylinker => {
542 let dcr = &*(self.buffer.as_ptr().cast::<DylinkerCommandRepr>());
543
544 let nul = self.buffer[dcr.name as usize..header.cmd_size as usize]
545 .iter()
546 .position(|c| *c == 0)?;
547
548 LoadCommand::DylinkerCommand(DylinkerCommand {
549 cmd: dcr.cmd,
550 cmd_size: dcr.cmd_size,
551 name_offset: dcr.name,
552 name: std::str::from_utf8(
553 &self.buffer[dcr.name as usize..dcr.name as usize + nul],
554 )
555 .ok()?,
556 })
557 }
558 })
559 });
560
561 self.count -= 1;
562 self.buffer = &self.buffer[header.cmd_size as usize..];
563
564 if let Some(cmd) = cmd {
565 return Some(cmd);
566 }
567 }
568 }
569 }
570
571 fn size_hint(&self) -> (usize, Option<usize>) {
572 let sz = self.count as usize;
573 (sz, Some(sz))
574 }
575 }
576
577 /// Retrieves an integer sysctl by name. Returns the default value if retrieval
578 /// fails.
579 pub fn sysctl_by_name<T: Sized + Default>(name: &[u8]) -> T {
580 let mut out = T::default();
581 let mut len = std::mem::size_of_val(&out);
582
583 // SAFETY: syscall
584 unsafe {
585 if libc::sysctlbyname(
586 name.as_ptr().cast(),
587 (&mut out as *mut T).cast(),
588 &mut len,
589 std::ptr::null_mut(),
590 0,
591 ) != 0
592 {
593 // TODO convert to ascii characters when logging?
594 log::warn!("failed to get sysctl for {name:?}");
595 T::default()
596 } else {
597 out
598 }
599 }
600 }
601
602 /// Retrieves an `i32` sysctl by name and casts it to the specified integer type.
603 /// Returns the default value if retrieval fails or the value is out of bounds of
604 /// the specified integer type.
605 pub fn int_sysctl_by_name<T: TryFrom<i32> + Default>(name: &[u8]) -> T {
606 let val = sysctl_by_name::<i32>(name);
607 T::try_from(val).unwrap_or_default()
608 }
609
610 /// Retrieves a string sysctl by name. Returns an empty string if the retrieval
611 /// fails or the string can't be converted to utf-8.
612 pub fn sysctl_string(name: &[u8]) -> String {
613 let mut buf_len = 0;
614
615 // SAFETY: syscalls
616 let string_buf = unsafe {
617 // Retrieve the size of the string (including null terminator)
618 if libc::sysctlbyname(
619 name.as_ptr().cast(),
620 std::ptr::null_mut(),
621 &mut buf_len,
622 std::ptr::null_mut(),
623 0,
624 ) != 0
625 || buf_len <= 1
626 {
627 return String::new();
628 }
629
630 let mut buff = Vec::new();
631 buff.resize(buf_len, 0);
632
633 if libc::sysctlbyname(
634 name.as_ptr().cast(),
635 buff.as_mut_ptr().cast(),
636 &mut buf_len,
637 std::ptr::null_mut(),
638 0,
639 ) != 0
640 {
641 return String::new();
642 }
643
644 buff.pop(); // remove null terminator
645 buff
646 };
647
648 String::from_utf8(string_buf).unwrap_or_default()
649 }
650
651 extern "C" {
652 /// From <usr/include/mach/mach_traps.h>, this retrieves the normal PID for
653 /// the specified task as the syscalls from BSD use PIDs, not mach ports.
654 ///
655 /// This seems to be marked as "obsolete" in the header, but of course being
656 /// Apple, there is no mention of a replacement function or when/if it might
657 /// eventually disappear.
658 pub fn pid_for_task(task: mach_port_name_t, pid: *mut i32) -> kern_return_t;
659
660 /// Fomr <user/include/mach/thread_act.h>, this retrieves thread info for the
661 /// for the specified thread.
662 ///
663 /// Note that the info_size parameter is actually the size of the thread_info / 4
664 /// as it is the number of words in the thread info
665 pub fn thread_info(
666 thread: u32,
667 flavor: u32,
668 thread_info: *mut i32,
669 info_size: *mut u32,
670 ) -> kern_return_t;
671 }