2 * Copyright (c) 2013-2020 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 #include <mach/mach_types.h>
30 #include <mach/vm_param.h>
31 #include <mach/mach_vm.h>
32 #include <mach/clock_types.h>
33 #include <sys/errno.h>
34 #include <sys/stackshot.h>
35 #ifdef IMPORTANCE_INHERITANCE
36 #include <ipc/ipc_importance.h>
38 #include <sys/appleapiopts.h>
39 #include <kern/debug.h>
40 #include <kern/block_hint.h>
41 #include <uuid/uuid.h>
43 #include <kdp/kdp_dyld.h>
44 #include <kdp/kdp_en_debugger.h>
46 #include <libsa/types.h>
47 #include <libkern/version.h>
48 #include <libkern/section_keywords.h>
50 #include <string.h> /* bcopy */
52 #include <kern/cambria_layout.h>
53 #include <kern/coalition.h>
54 #include <kern/processor.h>
55 #include <kern/host_statistics.h>
56 #include <kern/thread.h>
57 #include <kern/thread_group.h>
58 #include <kern/task.h>
59 #include <kern/telemetry.h>
60 #include <kern/clock.h>
61 #include <kern/policy_internal.h>
62 #include <vm/vm_map.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_pageout.h>
65 #include <vm/vm_fault.h>
66 #include <vm/vm_shared_region.h>
67 #include <vm/vm_compressor.h>
68 #include <libkern/OSKextLibPrivate.h>
71 #if defined(__x86_64__)
73 #include <i386/cpu_threads.h>
76 #include <pexpert/pexpert.h>
79 #include <kern/monotonic.h>
80 #endif /* MONOTONIC */
82 #include <san/kasan.h>
84 #if DEBUG || DEVELOPMENT
85 # define STACKSHOT_COLLECTS_LATENCY_INFO 1
87 # define STACKSHOT_COLLECTS_LATENCY_INFO 0
88 #endif /* DEBUG || DEVELOPMENT */
90 extern unsigned int not_in_kdp
;
93 /* indicate to the compiler that some accesses are unaligned */
94 typedef uint64_t unaligned_u64
__attribute__((aligned(1)));
96 extern addr64_t
kdp_vtophys(pmap_t pmap
, addr64_t va
);
99 static kern_return_t stack_snapshot_ret
= 0;
100 static uint32_t stack_snapshot_bytes_traced
= 0;
101 static uint32_t stack_snapshot_bytes_uncompressed
= 0;
103 #if STACKSHOT_COLLECTS_LATENCY_INFO
104 static bool collect_latency_info
= true;
106 static kcdata_descriptor_t stackshot_kcdata_p
= NULL
;
107 static void *stack_snapshot_buf
;
108 static uint32_t stack_snapshot_bufsize
;
109 int stack_snapshot_pid
;
110 static uint64_t stack_snapshot_flags
;
111 static uint64_t stack_snapshot_delta_since_timestamp
;
112 static uint32_t stack_snapshot_pagetable_mask
;
113 static boolean_t panic_stackshot
;
115 static boolean_t stack_enable_faulting
= FALSE
;
116 static struct stackshot_fault_stats fault_stats
;
118 static unaligned_u64
* stackshot_duration_outer
;
119 static uint64_t stackshot_microsecs
;
121 void * kernel_stackshot_buf
= NULL
; /* Pointer to buffer for stackshots triggered from the kernel and retrieved later */
122 int kernel_stackshot_buf_size
= 0;
124 void * stackshot_snapbuf
= NULL
; /* Used by stack_snapshot2 (to be removed) */
126 #if INTERRUPT_MASKED_DEBUG
127 extern boolean_t interrupt_masked_debug
;
130 __private_extern__
void stackshot_init( void );
131 static boolean_t
memory_iszero(void *addr
, size_t size
);
132 uint32_t get_stackshot_estsize(uint32_t prev_size_hint
);
133 kern_return_t
kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
,
134 size_t stackshot_config_size
, boolean_t stackshot_from_user
);
135 kern_return_t
do_stackshot(void *);
136 void kdp_snapshot_preflight(int pid
, void * tracebuf
, uint32_t tracebuf_size
, uint64_t flags
, kcdata_descriptor_t data_p
, uint64_t since_timestamp
, uint32_t pagetable_mask
);
137 boolean_t
stackshot_thread_is_idle_worker_unsafe(thread_t thread
);
138 static int kdp_stackshot_kcdata_format(int pid
, uint64_t trace_flags
, uint32_t *pBytesTraced
, uint32_t *pBytesUncompressed
);
139 uint32_t kdp_stack_snapshot_bytes_traced(void);
140 uint32_t kdp_stack_snapshot_bytes_uncompressed(void);
141 static void kdp_mem_and_io_snapshot(struct mem_and_io_snapshot
*memio_snap
);
142 static boolean_t
kdp_copyin(vm_map_t map
, uint64_t uaddr
, void *dest
, size_t size
, boolean_t try_fault
, uint32_t *kdp_fault_result
);
143 static int kdp_copyin_string(task_t task
, uint64_t addr
, char *buf
, int buf_sz
, boolean_t try_fault
, uint32_t *kdp_fault_results
);
144 static boolean_t
kdp_copyin_word(task_t task
, uint64_t addr
, uint64_t *result
, boolean_t try_fault
, uint32_t *kdp_fault_results
);
145 static uint64_t proc_was_throttled_from_task(task_t task
);
146 static void stackshot_thread_wait_owner_info(thread_t thread
, thread_waitinfo_t
* waitinfo
);
147 static int stackshot_thread_has_valid_waitinfo(thread_t thread
);
148 static void stackshot_thread_turnstileinfo(thread_t thread
, thread_turnstileinfo_t
*tsinfo
);
149 static int stackshot_thread_has_valid_turnstileinfo(thread_t thread
);
151 #if CONFIG_COALITIONS
152 static void stackshot_coalition_jetsam_count(void *arg
, int i
, coalition_t coal
);
153 static void stackshot_coalition_jetsam_snapshot(void *arg
, int i
, coalition_t coal
);
154 #endif /* CONFIG_COALITIONS */
156 #if CONFIG_THREAD_GROUPS
157 static void stackshot_thread_group_count(void *arg
, int i
, struct thread_group
*tg
);
158 static void stackshot_thread_group_snapshot(void *arg
, int i
, struct thread_group
*tg
);
159 #endif /* CONFIG_THREAD_GROUPS */
161 extern uint32_t workqueue_get_pwq_state_kdp(void *proc
);
164 extern int proc_pid(struct proc
*p
);
165 extern uint64_t proc_uniqueid(void *p
);
166 extern uint64_t proc_was_throttled(void *p
);
167 extern uint64_t proc_did_throttle(void *p
);
168 extern int proc_exiting(void *p
);
169 extern int proc_in_teardown(void *p
);
170 static uint64_t proc_did_throttle_from_task(task_t task
);
171 extern void proc_name_kdp(task_t task
, char * buf
, int size
);
172 extern int proc_threadname_kdp(void * uth
, char * buf
, size_t size
);
173 extern void proc_starttime_kdp(void * p
, uint64_t * tv_sec
, uint64_t * tv_usec
, uint64_t * abstime
);
174 extern void proc_archinfo_kdp(void* p
, cpu_type_t
* cputype
, cpu_subtype_t
* cpusubtype
);
175 extern boolean_t
proc_binary_uuid_kdp(task_t task
, uuid_t uuid
);
176 extern int memorystatus_get_pressure_status_kdp(void);
177 extern void memorystatus_proc_flags_unsafe(void * v
, boolean_t
*is_dirty
, boolean_t
*is_dirty_tracked
, boolean_t
*allow_idle_exit
);
179 extern int count_busy_buffers(void); /* must track with declaration in bsd/sys/buf_internal.h */
180 extern void bcopy_phys(addr64_t
, addr64_t
, vm_size_t
);
183 extern kern_return_t
stack_microstackshot(user_addr_t tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, int32_t *retval
);
184 #endif /* CONFIG_TELEMETRY */
186 extern kern_return_t
kern_stack_snapshot_with_reason(char* reason
);
187 extern kern_return_t
kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
, size_t stackshot_config_size
, boolean_t stackshot_from_user
);
190 * Validates that the given address is both a valid page and has
191 * default caching attributes for the current map. Returns
192 * 0 if the address is invalid, and a kernel virtual address for
193 * the given address if it is valid.
195 vm_offset_t
machine_trace_thread_get_kva(vm_offset_t cur_target_addr
, vm_map_t map
, uint32_t *thread_trace_flags
);
197 #define KDP_FAULT_RESULT_PAGED_OUT 0x1 /* some data was unable to be retrieved */
198 #define KDP_FAULT_RESULT_TRIED_FAULT 0x2 /* tried to fault in data */
199 #define KDP_FAULT_RESULT_FAULTED_IN 0x4 /* successfully faulted in data */
202 * Looks up the physical translation for the given address in the target map, attempting
203 * to fault data in if requested and it is not resident. Populates thread_trace_flags if requested
206 vm_offset_t
kdp_find_phys(vm_map_t map
, vm_offset_t target_addr
, boolean_t try_fault
, uint32_t *kdp_fault_results
);
208 static size_t stackshot_strlcpy(char *dst
, const char *src
, size_t maxlen
);
209 void stackshot_memcpy(void *dst
, const void *src
, size_t len
);
211 /* Clears caching information used by the above validation routine
212 * (in case the current map has been changed or cleared).
214 void machine_trace_thread_clear_validation_cache(void);
216 #define MAX_FRAMES 1000
217 #define MAX_LOADINFOS 500
218 #define TASK_IMP_WALK_LIMIT 20
220 typedef struct thread_snapshot
*thread_snapshot_t
;
221 typedef struct task_snapshot
*task_snapshot_t
;
223 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
224 extern kdp_send_t kdp_en_send_pkt
;
228 * Globals to support machine_trace_thread_get_kva.
230 static vm_offset_t prev_target_page
= 0;
231 static vm_offset_t prev_target_kva
= 0;
232 static boolean_t validate_next_addr
= TRUE
;
235 * Stackshot locking and other defines.
237 static LCK_GRP_DECLARE(stackshot_subsys_lck_grp
, "stackshot_subsys_lock");
238 static LCK_MTX_DECLARE(stackshot_subsys_mutex
, &stackshot_subsys_lck_grp
);
240 #define STACKSHOT_SUBSYS_LOCK() lck_mtx_lock(&stackshot_subsys_mutex)
241 #define STACKSHOT_SUBSYS_TRY_LOCK() lck_mtx_try_lock(&stackshot_subsys_mutex)
242 #define STACKSHOT_SUBSYS_UNLOCK() lck_mtx_unlock(&stackshot_subsys_mutex)
244 #define SANE_BOOTPROFILE_TRACEBUF_SIZE (64ULL * 1024ULL * 1024ULL)
245 #define SANE_TRACEBUF_SIZE (8ULL * 1024ULL * 1024ULL)
247 #define TRACEBUF_SIZE_PER_GB (1024ULL * 1024ULL)
248 #define GIGABYTES (1024ULL * 1024ULL * 1024ULL)
250 SECURITY_READ_ONLY_LATE(static uint32_t) max_tracebuf_size
= SANE_TRACEBUF_SIZE
;
253 * We currently set a ceiling of 3 milliseconds spent in the kdp fault path
254 * for non-panic stackshots where faulting is requested.
256 #define KDP_FAULT_PATH_MAX_TIME_PER_STACKSHOT_NSECS (3 * NSEC_PER_MSEC)
258 #define STACKSHOT_SUPP_SIZE (16 * 1024) /* Minimum stackshot size */
259 #define TASK_UUID_AVG_SIZE (16 * sizeof(uuid_t)) /* Average space consumed by UUIDs/task */
262 #define ROUNDUP(x, y) ((((x)+(y)-1)/(y))*(y))
265 #define STACKSHOT_QUEUE_LABEL_MAXSIZE 64
268 * Initialize the mutex governing access to the stack snapshot subsystem
269 * and other stackshot related bits.
271 __private_extern__
void
272 stackshot_init( void )
274 mach_timebase_info_data_t timebase
;
276 clock_timebase_info(&timebase
);
277 fault_stats
.sfs_system_max_fault_time
= ((KDP_FAULT_PATH_MAX_TIME_PER_STACKSHOT_NSECS
* timebase
.denom
) / timebase
.numer
);
279 max_tracebuf_size
= MAX(max_tracebuf_size
, ((ROUNDUP(max_mem
, GIGABYTES
) / GIGABYTES
) * TRACEBUF_SIZE_PER_GB
));
281 PE_parse_boot_argn("stackshot_maxsz", &max_tracebuf_size
, sizeof(max_tracebuf_size
));
285 * Method for grabbing timer values safely, in the sense that no infinite loop will occur
286 * Certain flavors of the timer_grab function, which would seem to be the thing to use,
287 * can loop infinitely if called while the timer is in the process of being updated.
288 * Unfortunately, it is (rarely) possible to get inconsistent top and bottom halves of
289 * the timer using this method. This seems insoluble, since stackshot runs in a context
290 * where the timer might be half-updated, and has no way of yielding control just long
291 * enough to finish the update.
295 safe_grab_timer_value(struct timer
*t
)
297 #if defined(__LP64__)
300 uint64_t time
= t
->high_bits
; /* endian independent grab */
301 time
= (time
<< 32) | t
->low_bits
;
307 * Called with interrupts disabled after stackshot context has been
308 * initialized. Updates stack_snapshot_ret.
315 #if defined(__x86_64__)
317 * Since mp_rendezvous and stackshot both attempt to capture cpus then perform an
318 * operation, it's essential to apply mutual exclusion to the other when one
319 * mechanism is in operation, lest there be a deadlock as the mechanisms race to
322 * Further, we assert that invoking stackshot from mp_rendezvous*() is not
323 * allowed, so we check to ensure there there is no rendezvous in progress before
324 * trying to grab the lock (if there is, a deadlock will occur when we try to
325 * grab the lock). This is accomplished by setting cpu_rendezvous_in_progress to
326 * TRUE in the mp rendezvous action function. If stackshot_trap() is called by
327 * a subordinate of the call chain within the mp rendezvous action, this flag will
328 * be set and can be used to detect the inevitable deadlock that would occur
329 * if this thread tried to grab the rendezvous lock.
332 if (current_cpu_datap()->cpu_rendezvous_in_progress
== TRUE
) {
333 panic("Calling stackshot from a rendezvous is not allowed!");
336 mp_rendezvous_lock();
339 rv
= DebuggerTrapWithState(DBOP_STACKSHOT
, NULL
, NULL
, NULL
, 0, NULL
, FALSE
, 0);
341 #if defined(__x86_64__)
342 mp_rendezvous_unlock();
349 stack_snapshot_from_kernel(int pid
, void *buf
, uint32_t size
, uint64_t flags
, uint64_t delta_since_timestamp
, uint32_t pagetable_mask
, unsigned *bytes_traced
)
351 kern_return_t error
= KERN_SUCCESS
;
354 #if DEVELOPMENT || DEBUG
355 if (kern_feature_override(KF_STACKSHOT_OVRD
) == TRUE
) {
356 error
= KERN_NOT_SUPPORTED
;
360 if ((buf
== NULL
) || (size
<= 0) || (bytes_traced
== NULL
)) {
361 return KERN_INVALID_ARGUMENT
;
364 /* cap in individual stackshot to max_tracebuf_size */
365 if (size
> max_tracebuf_size
) {
366 size
= max_tracebuf_size
;
369 /* Serialize tracing */
370 if (flags
& STACKSHOT_TRYLOCK
) {
371 if (!STACKSHOT_SUBSYS_TRY_LOCK()) {
372 return KERN_LOCK_OWNED
;
375 STACKSHOT_SUBSYS_LOCK();
378 struct kcdata_descriptor kcdata
;
379 uint32_t hdr_tag
= (flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) ?
380 KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT
: KCDATA_BUFFER_BEGIN_STACKSHOT
;
382 error
= kcdata_memory_static_init(&kcdata
, (mach_vm_address_t
)buf
, hdr_tag
, size
,
383 KCFLAG_USE_MEMCOPY
| KCFLAG_NO_AUTO_ENDBUFFER
);
388 istate
= ml_set_interrupts_enabled(FALSE
);
390 /* Preload trace parameters*/
391 kdp_snapshot_preflight(pid
, buf
, size
, flags
, &kcdata
,
392 delta_since_timestamp
, pagetable_mask
);
395 * Trap to the debugger to obtain a coherent stack snapshot; this populates
398 error
= stackshot_trap();
400 ml_set_interrupts_enabled(istate
);
402 *bytes_traced
= kdp_stack_snapshot_bytes_traced();
405 stackshot_kcdata_p
= NULL
;
406 STACKSHOT_SUBSYS_UNLOCK();
412 stack_microstackshot(user_addr_t tracebuf
, uint32_t tracebuf_size
, uint32_t flags
, int32_t *retval
)
414 int error
= KERN_SUCCESS
;
415 uint32_t bytes_traced
= 0;
420 * Control related operations
422 if (flags
& STACKSHOT_GLOBAL_MICROSTACKSHOT_ENABLE
) {
423 telemetry_global_ctl(1);
426 } else if (flags
& STACKSHOT_GLOBAL_MICROSTACKSHOT_DISABLE
) {
427 telemetry_global_ctl(0);
433 * Data related operations
437 if ((((void*)tracebuf
) == NULL
) || (tracebuf_size
== 0)) {
438 error
= KERN_INVALID_ARGUMENT
;
442 STACKSHOT_SUBSYS_LOCK();
444 if (flags
& STACKSHOT_GET_MICROSTACKSHOT
) {
445 if (tracebuf_size
> max_tracebuf_size
) {
446 error
= KERN_INVALID_ARGUMENT
;
450 bytes_traced
= tracebuf_size
;
451 error
= telemetry_gather(tracebuf
, &bytes_traced
,
452 (flags
& STACKSHOT_SET_MICROSTACKSHOT_MARK
) ? TRUE
: FALSE
);
453 *retval
= (int)bytes_traced
;
458 STACKSHOT_SUBSYS_UNLOCK();
462 #endif /* CONFIG_TELEMETRY */
465 * Return the estimated size of a stackshot based on the
466 * number of currently running threads and tasks.
469 get_stackshot_estsize(uint32_t prev_size_hint
)
471 vm_size_t thread_total
;
472 vm_size_t task_total
;
473 uint32_t estimated_size
;
474 size_t est_thread_size
= sizeof(struct thread_snapshot
);
475 size_t est_task_size
= sizeof(struct task_snapshot
) + TASK_UUID_AVG_SIZE
;
477 #if STACKSHOT_COLLECTS_LATENCY_INFO
478 if (collect_latency_info
) {
479 est_thread_size
+= sizeof(struct stackshot_latency_thread
);
480 est_task_size
+= sizeof(struct stackshot_latency_task
);
484 thread_total
= (threads_count
* est_thread_size
);
485 task_total
= (tasks_count
* est_task_size
);
487 estimated_size
= (uint32_t) VM_MAP_ROUND_PAGE((thread_total
+ task_total
+ STACKSHOT_SUPP_SIZE
), PAGE_MASK
);
488 if (estimated_size
< prev_size_hint
) {
489 estimated_size
= (uint32_t) VM_MAP_ROUND_PAGE(prev_size_hint
, PAGE_MASK
);
492 return estimated_size
;
496 * stackshot_remap_buffer: Utility function to remap bytes_traced bytes starting at stackshotbuf
497 * into the current task's user space and subsequently copy out the address
498 * at which the buffer has been mapped in user space to out_buffer_addr.
500 * Inputs: stackshotbuf - pointer to the original buffer in the kernel's address space
501 * bytes_traced - length of the buffer to remap starting from stackshotbuf
502 * out_buffer_addr - pointer to placeholder where newly mapped buffer will be mapped.
503 * out_size_addr - pointer to be filled in with the size of the buffer
505 * Outputs: ENOSPC if there is not enough free space in the task's address space to remap the buffer
506 * EINVAL for all other errors returned by task_remap_buffer/mach_vm_remap
507 * an error from copyout
510 stackshot_remap_buffer(void *stackshotbuf
, uint32_t bytes_traced
, uint64_t out_buffer_addr
, uint64_t out_size_addr
)
513 mach_vm_offset_t stackshotbuf_user_addr
= (mach_vm_offset_t
)NULL
;
514 vm_prot_t cur_prot
, max_prot
;
516 error
= mach_vm_remap_kernel(get_task_map(current_task()), &stackshotbuf_user_addr
, bytes_traced
, 0,
517 VM_FLAGS_ANYWHERE
, VM_KERN_MEMORY_NONE
, kernel_map
, (mach_vm_offset_t
)stackshotbuf
, FALSE
, &cur_prot
, &max_prot
, VM_INHERIT_DEFAULT
);
519 * If the call to mach_vm_remap fails, we return the appropriate converted error
521 if (error
== KERN_SUCCESS
) {
523 * If we fail to copy out the address or size of the new buffer, we remove the buffer mapping that
524 * we just made in the task's user space.
526 error
= copyout(CAST_DOWN(void *, &stackshotbuf_user_addr
), (user_addr_t
)out_buffer_addr
, sizeof(stackshotbuf_user_addr
));
527 if (error
!= KERN_SUCCESS
) {
528 mach_vm_deallocate(get_task_map(current_task()), stackshotbuf_user_addr
, (mach_vm_size_t
)bytes_traced
);
531 error
= copyout(&bytes_traced
, (user_addr_t
)out_size_addr
, sizeof(bytes_traced
));
532 if (error
!= KERN_SUCCESS
) {
533 mach_vm_deallocate(get_task_map(current_task()), stackshotbuf_user_addr
, (mach_vm_size_t
)bytes_traced
);
541 kern_stack_snapshot_internal(int stackshot_config_version
, void *stackshot_config
, size_t stackshot_config_size
, boolean_t stackshot_from_user
)
544 boolean_t prev_interrupt_state
;
545 uint32_t bytes_traced
= 0;
546 uint32_t stackshotbuf_size
= 0;
547 void * stackshotbuf
= NULL
;
548 kcdata_descriptor_t kcdata_p
= NULL
;
550 void * buf_to_free
= NULL
;
551 int size_to_free
= 0;
553 /* Parsed arguments */
554 uint64_t out_buffer_addr
;
555 uint64_t out_size_addr
;
558 uint64_t since_timestamp
;
559 uint32_t size_hint
= 0;
560 uint32_t pagetable_mask
= STACKSHOT_PAGETABLES_MASK_ALL
;
562 if (stackshot_config
== NULL
) {
563 return KERN_INVALID_ARGUMENT
;
565 #if DEVELOPMENT || DEBUG
566 /* TBD: ask stackshot clients to avoid issuing stackshots in this
567 * configuration in lieu of the kernel feature override.
569 if (kern_feature_override(KF_STACKSHOT_OVRD
) == TRUE
) {
570 return KERN_NOT_SUPPORTED
;
574 switch (stackshot_config_version
) {
575 case STACKSHOT_CONFIG_TYPE
:
576 if (stackshot_config_size
!= sizeof(stackshot_config_t
)) {
577 return KERN_INVALID_ARGUMENT
;
579 stackshot_config_t
*config
= (stackshot_config_t
*) stackshot_config
;
580 out_buffer_addr
= config
->sc_out_buffer_addr
;
581 out_size_addr
= config
->sc_out_size_addr
;
582 pid
= config
->sc_pid
;
583 flags
= config
->sc_flags
;
584 since_timestamp
= config
->sc_delta_timestamp
;
585 if (config
->sc_size
<= max_tracebuf_size
) {
586 size_hint
= config
->sc_size
;
589 * Retain the pre-sc_pagetable_mask behavior of STACKSHOT_PAGE_TABLES,
590 * dump every level if the pagetable_mask is not set
592 if (flags
& STACKSHOT_PAGE_TABLES
&& config
->sc_pagetable_mask
) {
593 pagetable_mask
= config
->sc_pagetable_mask
;
597 return KERN_NOT_SUPPORTED
;
601 * Currently saving a kernel buffer and trylock are only supported from the
604 if (stackshot_from_user
) {
605 if (flags
& (STACKSHOT_TRYLOCK
| STACKSHOT_SAVE_IN_KERNEL_BUFFER
| STACKSHOT_FROM_PANIC
)) {
606 return KERN_NO_ACCESS
;
608 #if !DEVELOPMENT && !DEBUG
609 if (flags
& (STACKSHOT_DO_COMPRESS
)) {
610 return KERN_NO_ACCESS
;
614 if (!(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
615 return KERN_NOT_SUPPORTED
;
619 if (!((flags
& STACKSHOT_KCDATA_FORMAT
) || (flags
& STACKSHOT_RETRIEVE_EXISTING_BUFFER
))) {
620 return KERN_NOT_SUPPORTED
;
623 /* Compresssed delta stackshots or page dumps are not yet supported */
624 if (((flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) || (flags
& STACKSHOT_PAGE_TABLES
))
625 && (flags
& STACKSHOT_DO_COMPRESS
)) {
626 return KERN_NOT_SUPPORTED
;
630 * If we're not saving the buffer in the kernel pointer, we need a place to copy into.
632 if ((!out_buffer_addr
|| !out_size_addr
) && !(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
633 return KERN_INVALID_ARGUMENT
;
636 if (since_timestamp
!= 0 && ((flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) == 0)) {
637 return KERN_INVALID_ARGUMENT
;
641 if (!mt_core_supported
) {
642 flags
&= ~STACKSHOT_INSTRS_CYCLES
;
644 #else /* MONOTONIC */
645 flags
&= ~STACKSHOT_INSTRS_CYCLES
;
646 #endif /* !MONOTONIC */
648 STACKSHOT_SUBSYS_LOCK();
650 if (flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
) {
652 * Don't overwrite an existing stackshot
654 if (kernel_stackshot_buf
!= NULL
) {
655 error
= KERN_MEMORY_PRESENT
;
658 } else if (flags
& STACKSHOT_RETRIEVE_EXISTING_BUFFER
) {
659 if ((kernel_stackshot_buf
== NULL
) || (kernel_stackshot_buf_size
<= 0)) {
660 error
= KERN_NOT_IN_SET
;
663 error
= stackshot_remap_buffer(kernel_stackshot_buf
, kernel_stackshot_buf_size
,
664 out_buffer_addr
, out_size_addr
);
666 * If we successfully remapped the buffer into the user's address space, we
667 * set buf_to_free and size_to_free so the prior kernel mapping will be removed
668 * and then clear the kernel stackshot pointer and associated size.
670 if (error
== KERN_SUCCESS
) {
671 buf_to_free
= kernel_stackshot_buf
;
672 size_to_free
= (int) VM_MAP_ROUND_PAGE(kernel_stackshot_buf_size
, PAGE_MASK
);
673 kernel_stackshot_buf
= NULL
;
674 kernel_stackshot_buf_size
= 0;
680 if (flags
& STACKSHOT_GET_BOOT_PROFILE
) {
681 void *bootprofile
= NULL
;
684 bootprofile_get(&bootprofile
, &len
);
686 if (!bootprofile
|| !len
) {
687 error
= KERN_NOT_IN_SET
;
690 error
= stackshot_remap_buffer(bootprofile
, len
, out_buffer_addr
, out_size_addr
);
694 stackshotbuf_size
= get_stackshot_estsize(size_hint
);
696 for (; stackshotbuf_size
<= max_tracebuf_size
; stackshotbuf_size
<<= 1) {
697 if (kmem_alloc_flags(kernel_map
, (vm_offset_t
*)&stackshotbuf
, stackshotbuf_size
, VM_KERN_MEMORY_DIAG
, KMA_ZERO
) != KERN_SUCCESS
) {
698 error
= KERN_RESOURCE_SHORTAGE
;
703 uint32_t hdr_tag
= (flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) ? KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT
704 : (flags
& STACKSHOT_DO_COMPRESS
) ? KCDATA_BUFFER_BEGIN_COMPRESSED
705 : KCDATA_BUFFER_BEGIN_STACKSHOT
;
706 kcdata_p
= kcdata_memory_alloc_init((mach_vm_address_t
)stackshotbuf
, hdr_tag
, stackshotbuf_size
,
707 KCFLAG_USE_MEMCOPY
| KCFLAG_NO_AUTO_ENDBUFFER
);
709 stackshot_duration_outer
= NULL
;
710 uint64_t time_start
= mach_absolute_time();
712 /* if compression was requested, allocate the extra zlib scratch area */
713 if (flags
& STACKSHOT_DO_COMPRESS
) {
714 hdr_tag
= (flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) ? KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT
715 : KCDATA_BUFFER_BEGIN_STACKSHOT
;
716 error
= kcdata_init_compress(kcdata_p
, hdr_tag
, stackshot_memcpy
, KCDCT_ZLIB
);
717 if (error
!= KERN_SUCCESS
) {
718 os_log(OS_LOG_DEFAULT
, "failed to initialize compression: %d!\n",
725 * Disable interrupts and save the current interrupt state.
727 prev_interrupt_state
= ml_set_interrupts_enabled(FALSE
);
730 * Load stackshot parameters.
732 kdp_snapshot_preflight(pid
, stackshotbuf
, stackshotbuf_size
, flags
, kcdata_p
, since_timestamp
,
735 error
= stackshot_trap();
737 ml_set_interrupts_enabled(prev_interrupt_state
);
739 /* record the duration that interupts were disabled */
741 uint64_t time_end
= mach_absolute_time();
742 if (stackshot_duration_outer
) {
743 *stackshot_duration_outer
= time_end
- time_start
;
746 if (error
!= KERN_SUCCESS
) {
747 if (kcdata_p
!= NULL
) {
748 kcdata_memory_destroy(kcdata_p
);
750 stackshot_kcdata_p
= NULL
;
752 kmem_free(kernel_map
, (vm_offset_t
)stackshotbuf
, stackshotbuf_size
);
754 if (error
== KERN_INSUFFICIENT_BUFFER_SIZE
) {
756 * If we didn't allocate a big enough buffer, deallocate and try again.
764 bytes_traced
= kdp_stack_snapshot_bytes_traced();
766 if (bytes_traced
<= 0) {
767 error
= KERN_ABORTED
;
771 assert(bytes_traced
<= stackshotbuf_size
);
772 if (!(flags
& STACKSHOT_SAVE_IN_KERNEL_BUFFER
)) {
773 error
= stackshot_remap_buffer(stackshotbuf
, bytes_traced
, out_buffer_addr
, out_size_addr
);
778 * Save the stackshot in the kernel buffer.
780 kernel_stackshot_buf
= stackshotbuf
;
781 kernel_stackshot_buf_size
= bytes_traced
;
783 * Figure out if we didn't use all the pages in the buffer. If so, we set buf_to_free to the beginning of
784 * the next page after the end of the stackshot in the buffer so that the kmem_free clips the buffer and
785 * update size_to_free for kmem_free accordingly.
787 size_to_free
= stackshotbuf_size
- (int) VM_MAP_ROUND_PAGE(bytes_traced
, PAGE_MASK
);
789 assert(size_to_free
>= 0);
791 if (size_to_free
!= 0) {
792 buf_to_free
= (void *)((uint64_t)stackshotbuf
+ stackshotbuf_size
- size_to_free
);
796 stackshotbuf_size
= 0;
800 if (stackshotbuf_size
> max_tracebuf_size
) {
801 error
= KERN_RESOURCE_SHORTAGE
;
805 if (kcdata_p
!= NULL
) {
806 kcdata_memory_destroy(kcdata_p
);
808 stackshot_kcdata_p
= NULL
;
811 if (stackshotbuf
!= NULL
) {
812 kmem_free(kernel_map
, (vm_offset_t
)stackshotbuf
, stackshotbuf_size
);
814 if (buf_to_free
!= NULL
) {
815 kmem_free(kernel_map
, (vm_offset_t
)buf_to_free
, size_to_free
);
817 STACKSHOT_SUBSYS_UNLOCK();
822 * Cache stack snapshot parameters in preparation for a trace.
825 kdp_snapshot_preflight(int pid
, void * tracebuf
, uint32_t tracebuf_size
, uint64_t flags
,
826 kcdata_descriptor_t data_p
, uint64_t since_timestamp
, uint32_t pagetable_mask
)
828 uint64_t microsecs
= 0, secs
= 0;
829 clock_get_calendar_microtime((clock_sec_t
*)&secs
, (clock_usec_t
*)µsecs
);
831 stackshot_microsecs
= microsecs
+ (secs
* USEC_PER_SEC
);
832 stack_snapshot_pid
= pid
;
833 stack_snapshot_buf
= tracebuf
;
834 stack_snapshot_bufsize
= tracebuf_size
;
835 stack_snapshot_flags
= flags
;
836 stack_snapshot_delta_since_timestamp
= since_timestamp
;
837 stack_snapshot_pagetable_mask
= pagetable_mask
;
839 panic_stackshot
= ((flags
& STACKSHOT_FROM_PANIC
) != 0);
841 assert(data_p
!= NULL
);
842 assert(stackshot_kcdata_p
== NULL
);
843 stackshot_kcdata_p
= data_p
;
845 stack_snapshot_bytes_traced
= 0;
846 stack_snapshot_bytes_uncompressed
= 0;
850 panic_stackshot_reset_state()
852 stackshot_kcdata_p
= NULL
;
858 return stackshot_kcdata_p
!= NULL
;
862 kdp_stack_snapshot_bytes_traced(void)
864 return stack_snapshot_bytes_traced
;
868 kdp_stack_snapshot_bytes_uncompressed(void)
870 return stack_snapshot_bytes_uncompressed
;
874 memory_iszero(void *addr
, size_t size
)
876 char *data
= (char *)addr
;
877 for (size_t i
= 0; i
< size
; i
++) {
885 #define kcd_end_address(kcd) ((void *)((uint64_t)((kcd)->kcd_addr_begin) + kcdata_memory_get_used_bytes((kcd))))
886 #define kcd_max_address(kcd) ((void *)((kcd)->kcd_addr_begin + (kcd)->kcd_length))
888 * Use of the kcd_exit_on_error(action) macro requires a local
889 * 'kern_return_t error' variable and 'error_exit' label.
891 #define kcd_exit_on_error(action) \
893 if (KERN_SUCCESS != (error = (action))) { \
894 if (error == KERN_RESOURCE_SHORTAGE) { \
895 error = KERN_INSUFFICIENT_BUFFER_SIZE; \
899 } while (0); /* end kcd_exit_on_error */
902 kcdata_get_task_ss_flags(task_t task
)
904 uint64_t ss_flags
= 0;
905 boolean_t task_64bit_addr
= task_has_64Bit_addr(task
);
907 if (task_64bit_addr
) {
908 ss_flags
|= kUser64_p
;
910 if (!task
->active
|| task_is_a_corpse(task
) || proc_exiting(task
->bsd_info
)) {
911 ss_flags
|= kTerminatedSnapshot
;
913 if (task
->pidsuspended
) {
914 ss_flags
|= kPidSuspended
;
919 if (task
->effective_policy
.tep_darwinbg
== 1) {
920 ss_flags
|= kTaskDarwinBG
;
922 if (task
->requested_policy
.trp_role
== TASK_FOREGROUND_APPLICATION
) {
923 ss_flags
|= kTaskIsForeground
;
925 if (task
->requested_policy
.trp_boosted
== 1) {
926 ss_flags
|= kTaskIsBoosted
;
928 if (task
->effective_policy
.tep_sup_active
== 1) {
929 ss_flags
|= kTaskIsSuppressed
;
931 #if CONFIG_MEMORYSTATUS
933 boolean_t dirty
= FALSE
, dirty_tracked
= FALSE
, allow_idle_exit
= FALSE
;
934 memorystatus_proc_flags_unsafe(task
->bsd_info
, &dirty
, &dirty_tracked
, &allow_idle_exit
);
936 ss_flags
|= kTaskIsDirty
;
939 ss_flags
|= kTaskIsDirtyTracked
;
941 if (allow_idle_exit
) {
942 ss_flags
|= kTaskAllowIdleExit
;
946 if (task
->effective_policy
.tep_tal_engaged
) {
947 ss_flags
|= kTaskTALEngaged
;
950 ss_flags
|= (0x7 & workqueue_get_pwq_state_kdp(task
->bsd_info
)) << 17;
952 #if IMPORTANCE_INHERITANCE
953 if (task
->task_imp_base
) {
954 if (task
->task_imp_base
->iit_donor
) {
955 ss_flags
|= kTaskIsImpDonor
;
957 if (task
->task_imp_base
->iit_live_donor
) {
958 ss_flags
|= kTaskIsLiveImpDonor
;
966 kcdata_record_shared_cache_info(kcdata_descriptor_t kcd
, task_t task
, unaligned_u64
*task_snap_ss_flags
)
968 kern_return_t error
= KERN_SUCCESS
;
970 uint64_t shared_cache_slide
= 0;
971 uint64_t shared_cache_base_address
= 0;
972 uint32_t kdp_fault_results
= 0;
973 struct dyld_uuid_info_64_v2 shared_cache_data
= {0};
976 assert(task_snap_ss_flags
!= NULL
);
978 if (task
->shared_region
&& ml_validate_nofault((vm_offset_t
)task
->shared_region
, sizeof(struct vm_shared_region
))) {
979 struct vm_shared_region
*sr
= task
->shared_region
;
980 shared_cache_base_address
= sr
->sr_base_address
+ sr
->sr_first_mapping
;
983 *task_snap_ss_flags
|= kTaskSharedRegionInfoUnavailable
;
987 /* We haven't copied in the shared region UUID yet as part of setup */
988 if (!shared_cache_base_address
|| !task
->shared_region
->sr_uuid_copied
) {
994 * No refcounting here, but we are in debugger context, so that should be safe.
996 shared_cache_slide
= task
->shared_region
->sr_slide
;
998 if (task
->shared_region
== init_task_shared_region
) {
999 /* skip adding shared cache info -- it's the same as the system level one */
1003 shared_cache_data
.imageLoadAddress
= shared_cache_slide
;
1004 stackshot_memcpy(&shared_cache_data
.imageUUID
, task
->shared_region
->sr_uuid
, sizeof(task
->shared_region
->sr_uuid
));
1005 shared_cache_data
.imageSlidBaseAddress
= shared_cache_base_address
;
1006 kcd_exit_on_error(kcdata_push_data(kcd
, STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO
, sizeof(struct dyld_uuid_info_64_v2
), &shared_cache_data
));
1009 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
1010 *task_snap_ss_flags
|= kTaskUUIDInfoMissing
;
1013 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
1014 *task_snap_ss_flags
|= kTaskUUIDInfoTriedFault
;
1017 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
1018 *task_snap_ss_flags
|= kTaskUUIDInfoFaultedIn
;
1024 static kern_return_t
1025 kcdata_record_uuid_info(kcdata_descriptor_t kcd
, task_t task
, uint64_t trace_flags
, boolean_t have_pmap
, unaligned_u64
*task_snap_ss_flags
)
1027 boolean_t save_loadinfo_p
= ((trace_flags
& STACKSHOT_SAVE_LOADINFO
) != 0);
1028 boolean_t save_kextloadinfo_p
= ((trace_flags
& STACKSHOT_SAVE_KEXT_LOADINFO
) != 0);
1029 boolean_t should_fault
= (trace_flags
& STACKSHOT_ENABLE_UUID_FAULTING
);
1031 kern_return_t error
= KERN_SUCCESS
;
1032 mach_vm_address_t out_addr
= 0;
1034 uint32_t uuid_info_count
= 0;
1035 mach_vm_address_t uuid_info_addr
= 0;
1036 uint64_t uuid_info_timestamp
= 0;
1037 uint32_t kdp_fault_results
= 0;
1040 assert(task_snap_ss_flags
!= NULL
);
1042 int task_pid
= pid_from_task(task
);
1043 boolean_t task_64bit_addr
= task_has_64Bit_addr(task
);
1045 if (save_loadinfo_p
&& have_pmap
&& task
->active
&& task_pid
> 0) {
1046 /* Read the dyld_all_image_infos struct from the task memory to get UUID array count and location */
1047 if (task_64bit_addr
) {
1048 struct user64_dyld_all_image_infos task_image_infos
;
1049 if (kdp_copyin(task
->map
, task
->all_image_info_addr
, &task_image_infos
,
1050 sizeof(struct user64_dyld_all_image_infos
), should_fault
, &kdp_fault_results
)) {
1051 uuid_info_count
= (uint32_t)task_image_infos
.uuidArrayCount
;
1052 uuid_info_addr
= task_image_infos
.uuidArray
;
1053 if (task_image_infos
.version
>= DYLD_ALL_IMAGE_INFOS_TIMESTAMP_MINIMUM_VERSION
) {
1054 uuid_info_timestamp
= task_image_infos
.timestamp
;
1059 struct user32_dyld_all_image_infos task_image_infos
;
1060 if (kdp_copyin(task
->map
, task
->all_image_info_addr
, &task_image_infos
,
1061 sizeof(struct user32_dyld_all_image_infos
), should_fault
, &kdp_fault_results
)) {
1062 uuid_info_count
= task_image_infos
.uuidArrayCount
;
1063 uuid_info_addr
= task_image_infos
.uuidArray
;
1064 if (task_image_infos
.version
>= DYLD_ALL_IMAGE_INFOS_TIMESTAMP_MINIMUM_VERSION
) {
1065 uuid_info_timestamp
= task_image_infos
.timestamp
;
1071 * If we get a NULL uuid_info_addr (which can happen when we catch dyld in the middle of updating
1072 * this data structure), we zero the uuid_info_count so that we won't even try to save load info
1075 if (!uuid_info_addr
) {
1076 uuid_info_count
= 0;
1082 if (have_pmap
&& task_pid
== 0) {
1083 if (save_kextloadinfo_p
&& ml_validate_nofault((vm_offset_t
)(gLoadedKextSummaries
), sizeof(OSKextLoadedKextSummaryHeader
))) {
1084 uuid_info_count
= gLoadedKextSummaries
->numSummaries
+ 1; /* include main kernel UUID */
1086 uuid_info_count
= 1; /* include kernelcache UUID (embedded) or kernel UUID (desktop) */
1090 if (save_loadinfo_p
&& task_pid
> 0 && (uuid_info_count
< MAX_LOADINFOS
)) {
1091 uint32_t copied_uuid_count
= 0;
1092 uint32_t uuid_info_size
= (uint32_t)(task_64bit_addr
? sizeof(struct user64_dyld_uuid_info
) : sizeof(struct user32_dyld_uuid_info
));
1093 uint32_t uuid_info_array_size
= 0;
1095 /* Open a compression window to avoid overflowing the stack */
1096 kcdata_compression_window_open(kcd
);
1098 /* If we found some UUID information, first try to copy it in -- this will only be non-zero if we had a pmap above */
1099 if (uuid_info_count
> 0) {
1100 uuid_info_array_size
= uuid_info_count
* uuid_info_size
;
1102 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, (task_64bit_addr
? KCDATA_TYPE_LIBRARY_LOADINFO64
: KCDATA_TYPE_LIBRARY_LOADINFO
),
1103 uuid_info_size
, uuid_info_count
, &out_addr
));
1105 if (!kdp_copyin(task
->map
, uuid_info_addr
, (void *)out_addr
, uuid_info_array_size
, should_fault
, &kdp_fault_results
)) {
1106 bzero((void *)out_addr
, uuid_info_array_size
);
1108 copied_uuid_count
= uuid_info_count
;
1113 if (!copied_uuid_count
&& proc_binary_uuid_kdp(task
, binary_uuid
)) {
1114 /* We failed to copyin the UUID information, try to store the UUID of the main binary we have in the proc */
1115 if (uuid_info_array_size
== 0) {
1116 /* We just need to store one UUID */
1117 uuid_info_array_size
= uuid_info_size
;
1118 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, (task_64bit_addr
? KCDATA_TYPE_LIBRARY_LOADINFO64
: KCDATA_TYPE_LIBRARY_LOADINFO
),
1119 uuid_info_size
, 1, &out_addr
));
1122 if (task_64bit_addr
) {
1123 struct user64_dyld_uuid_info
*uuid_info
= (struct user64_dyld_uuid_info
*)out_addr
;
1124 uint64_t image_load_address
= task
->mach_header_vm_address
;
1126 stackshot_memcpy(&uuid_info
->imageUUID
, binary_uuid
, sizeof(uuid_t
));
1127 stackshot_memcpy(&uuid_info
->imageLoadAddress
, &image_load_address
, sizeof(image_load_address
));
1129 struct user32_dyld_uuid_info
*uuid_info
= (struct user32_dyld_uuid_info
*)out_addr
;
1130 uint32_t image_load_address
= (uint32_t) task
->mach_header_vm_address
;
1132 stackshot_memcpy(&uuid_info
->imageUUID
, binary_uuid
, sizeof(uuid_t
));
1133 stackshot_memcpy(&uuid_info
->imageLoadAddress
, &image_load_address
, sizeof(image_load_address
));
1137 kcd_exit_on_error(kcdata_compression_window_close(kcd
));
1138 } else if (task_pid
== 0 && uuid_info_count
> 0 && uuid_info_count
< MAX_LOADINFOS
) {
1139 uintptr_t image_load_address
;
1142 #if defined(__arm__) || defined(__arm64__)
1143 if (kernelcache_uuid_valid
&& !save_kextloadinfo_p
) {
1144 struct dyld_uuid_info_64 kc_uuid
= {0};
1145 kc_uuid
.imageLoadAddress
= VM_MIN_KERNEL_AND_KEXT_ADDRESS
;
1146 stackshot_memcpy(&kc_uuid
.imageUUID
, &kernelcache_uuid
, sizeof(uuid_t
));
1147 kcd_exit_on_error(kcdata_push_data(kcd
, STACKSHOT_KCTYPE_KERNELCACHE_LOADINFO
, sizeof(struct dyld_uuid_info_64
), &kc_uuid
));
1150 #endif /* defined(__arm__) || defined(__arm64__) */
1152 if (!kernel_uuid
|| !ml_validate_nofault((vm_offset_t
)kernel_uuid
, sizeof(uuid_t
))) {
1153 /* Kernel UUID not found or inaccessible */
1157 uint32_t uuid_type
= KCDATA_TYPE_LIBRARY_LOADINFO
;
1158 if ((sizeof(kernel_uuid_info
) == sizeof(struct user64_dyld_uuid_info
))) {
1159 uuid_type
= KCDATA_TYPE_LIBRARY_LOADINFO64
;
1160 #if defined(__arm64__)
1161 kc_format_t primary_kc_type
= KCFormatUnknown
;
1162 if (PE_get_primary_kc_format(&primary_kc_type
) && (primary_kc_type
== KCFormatFileset
)) {
1163 /* return TEXT_EXEC based load information on arm devices running with fileset kernelcaches */
1164 uuid_type
= STACKSHOT_KCTYPE_LOADINFO64_TEXT_EXEC
;
1170 * The element count of the array can vary - avoid overflowing the
1171 * stack by opening a window.
1173 kcdata_compression_window_open(kcd
);
1174 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, uuid_type
,
1175 sizeof(kernel_uuid_info
), uuid_info_count
, &out_addr
));
1176 kernel_uuid_info
*uuid_info_array
= (kernel_uuid_info
*)out_addr
;
1178 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(vm_kernel_stext
);
1179 #if defined(__arm64__)
1180 if (uuid_type
== STACKSHOT_KCTYPE_LOADINFO64_TEXT_EXEC
) {
1181 /* If we're reporting TEXT_EXEC load info, populate the TEXT_EXEC base instead */
1182 extern vm_offset_t segTEXTEXECB
;
1183 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(segTEXTEXECB
);
1186 uuid_info_array
[0].imageLoadAddress
= image_load_address
;
1187 stackshot_memcpy(&uuid_info_array
[0].imageUUID
, kernel_uuid
, sizeof(uuid_t
));
1189 if (save_kextloadinfo_p
&&
1190 ml_validate_nofault((vm_offset_t
)(gLoadedKextSummaries
), sizeof(OSKextLoadedKextSummaryHeader
)) &&
1191 ml_validate_nofault((vm_offset_t
)(&gLoadedKextSummaries
->summaries
[0]),
1192 gLoadedKextSummaries
->entry_size
* gLoadedKextSummaries
->numSummaries
)) {
1194 for (kexti
= 0; kexti
< gLoadedKextSummaries
->numSummaries
; kexti
++) {
1195 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(gLoadedKextSummaries
->summaries
[kexti
].address
);
1196 #if defined(__arm64__)
1197 if (uuid_type
== STACKSHOT_KCTYPE_LOADINFO64_TEXT_EXEC
) {
1198 /* If we're reporting TEXT_EXEC load info, populate the TEXT_EXEC base instead */
1199 image_load_address
= (uintptr_t)VM_KERNEL_UNSLIDE(gLoadedKextSummaries
->summaries
[kexti
].text_exec_address
);
1202 uuid_info_array
[kexti
+ 1].imageLoadAddress
= image_load_address
;
1203 stackshot_memcpy(&uuid_info_array
[kexti
+ 1].imageUUID
, &gLoadedKextSummaries
->summaries
[kexti
].uuid
, sizeof(uuid_t
));
1206 kcd_exit_on_error(kcdata_compression_window_close(kcd
));
1211 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
1212 *task_snap_ss_flags
|= kTaskUUIDInfoMissing
;
1215 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
1216 *task_snap_ss_flags
|= kTaskUUIDInfoTriedFault
;
1219 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
1220 *task_snap_ss_flags
|= kTaskUUIDInfoFaultedIn
;
1226 static kern_return_t
1227 kcdata_record_task_iostats(kcdata_descriptor_t kcd
, task_t task
)
1229 kern_return_t error
= KERN_SUCCESS
;
1230 mach_vm_address_t out_addr
= 0;
1232 /* I/O Statistics if any counters are non zero */
1233 assert(IO_NUM_PRIORITIES
== STACKSHOT_IO_NUM_PRIORITIES
);
1234 if (task
->task_io_stats
&& !memory_iszero(task
->task_io_stats
, sizeof(struct io_stat_info
))) {
1235 /* struct io_stats_snapshot is quite large - avoid overflowing the stack. */
1236 kcdata_compression_window_open(kcd
);
1237 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_IOSTATS
, sizeof(struct io_stats_snapshot
), &out_addr
));
1238 struct io_stats_snapshot
*_iostat
= (struct io_stats_snapshot
*)out_addr
;
1239 _iostat
->ss_disk_reads_count
= task
->task_io_stats
->disk_reads
.count
;
1240 _iostat
->ss_disk_reads_size
= task
->task_io_stats
->disk_reads
.size
;
1241 _iostat
->ss_disk_writes_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->disk_reads
.count
);
1242 _iostat
->ss_disk_writes_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->disk_reads
.size
);
1243 _iostat
->ss_paging_count
= task
->task_io_stats
->paging
.count
;
1244 _iostat
->ss_paging_size
= task
->task_io_stats
->paging
.size
;
1245 _iostat
->ss_non_paging_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->paging
.count
);
1246 _iostat
->ss_non_paging_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->paging
.size
);
1247 _iostat
->ss_metadata_count
= task
->task_io_stats
->metadata
.count
;
1248 _iostat
->ss_metadata_size
= task
->task_io_stats
->metadata
.size
;
1249 _iostat
->ss_data_count
= (task
->task_io_stats
->total_io
.count
- task
->task_io_stats
->metadata
.count
);
1250 _iostat
->ss_data_size
= (task
->task_io_stats
->total_io
.size
- task
->task_io_stats
->metadata
.size
);
1251 for (int i
= 0; i
< IO_NUM_PRIORITIES
; i
++) {
1252 _iostat
->ss_io_priority_count
[i
] = task
->task_io_stats
->io_priority
[i
].count
;
1253 _iostat
->ss_io_priority_size
[i
] = task
->task_io_stats
->io_priority
[i
].size
;
1255 kcd_exit_on_error(kcdata_compression_window_close(kcd
));
1264 static kern_return_t
1265 kcdata_record_task_instrs_cycles(kcdata_descriptor_t kcd
, task_t task
)
1267 struct instrs_cycles_snapshot instrs_cycles
= {0};
1268 uint64_t ics_instructions
;
1269 uint64_t ics_cycles
;
1271 mt_stackshot_task(task
, &ics_instructions
, &ics_cycles
);
1272 instrs_cycles
.ics_instructions
= ics_instructions
;
1273 instrs_cycles
.ics_cycles
= ics_cycles
;
1275 return kcdata_push_data(kcd
, STACKSHOT_KCTYPE_INSTRS_CYCLES
, sizeof(instrs_cycles
), &instrs_cycles
);
1277 #endif /* MONOTONIC */
1279 static kern_return_t
1280 kcdata_record_task_cpu_architecture(kcdata_descriptor_t kcd
, task_t task
)
1282 struct stackshot_cpu_architecture cpu_architecture
= {0};
1286 proc_archinfo_kdp(task
->bsd_info
, &cputype
, &cpusubtype
);
1287 cpu_architecture
.cputype
= cputype
;
1288 cpu_architecture
.cpusubtype
= cpusubtype
;
1290 return kcdata_push_data(kcd
, STACKSHOT_KCTYPE_TASK_CPU_ARCHITECTURE
, sizeof(struct stackshot_cpu_architecture
), &cpu_architecture
);
1293 static kern_return_t
1294 #if STACKSHOT_COLLECTS_LATENCY_INFO
1295 kcdata_record_task_snapshot(kcdata_descriptor_t kcd
, task_t task
, uint64_t trace_flags
, boolean_t have_pmap
, unaligned_u64 task_snap_ss_flags
, struct stackshot_latency_task
*latency_info
)
1297 kcdata_record_task_snapshot(kcdata_descriptor_t kcd
, task_t task
, uint64_t trace_flags
, boolean_t have_pmap
, unaligned_u64 task_snap_ss_flags
)
1298 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1300 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1301 boolean_t collect_iostats
= !collect_delta_stackshot
&& !(trace_flags
& STACKSHOT_NO_IO_STATS
);
1303 boolean_t collect_instrs_cycles
= ((trace_flags
& STACKSHOT_INSTRS_CYCLES
) != 0);
1304 #endif /* MONOTONIC */
1305 #if __arm__ || __arm64__
1306 boolean_t collect_asid
= ((trace_flags
& STACKSHOT_ASID
) != 0);
1308 boolean_t collect_pagetables
= ((trace_flags
& STACKSHOT_PAGE_TABLES
) != 0);
1311 kern_return_t error
= KERN_SUCCESS
;
1312 mach_vm_address_t out_addr
= 0;
1313 struct task_snapshot_v2
* cur_tsnap
= NULL
;
1314 #if STACKSHOT_COLLECTS_LATENCY_INFO
1315 latency_info
->cur_tsnap_latency
= mach_absolute_time();
1316 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1318 int task_pid
= pid_from_task(task
);
1319 uint64_t task_uniqueid
= get_task_uniqueid(task
);
1320 uint64_t proc_starttime_secs
= 0;
1322 if (task_pid
&& (task_did_exec_internal(task
) || task_is_exec_copy_internal(task
))) {
1324 * if this task is a transit task from another one, show the pid as
1327 task_pid
= 0 - task_pid
;
1330 /* the task_snapshot_v2 struct is large - avoid overflowing the stack */
1331 kcdata_compression_window_open(kcd
);
1332 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_TASK_SNAPSHOT
, sizeof(struct task_snapshot_v2
), &out_addr
));
1333 cur_tsnap
= (struct task_snapshot_v2
*)out_addr
;
1334 bzero(cur_tsnap
, sizeof(*cur_tsnap
));
1336 cur_tsnap
->ts_unique_pid
= task_uniqueid
;
1337 cur_tsnap
->ts_ss_flags
= kcdata_get_task_ss_flags(task
);
1338 cur_tsnap
->ts_ss_flags
|= task_snap_ss_flags
;
1339 cur_tsnap
->ts_user_time_in_terminated_threads
= task
->total_user_time
;
1340 cur_tsnap
->ts_system_time_in_terminated_threads
= task
->total_system_time
;
1342 proc_starttime_kdp(task
->bsd_info
, &proc_starttime_secs
, NULL
, NULL
);
1343 cur_tsnap
->ts_p_start_sec
= proc_starttime_secs
;
1344 cur_tsnap
->ts_task_size
= have_pmap
? get_task_phys_footprint(task
) : 0;
1345 cur_tsnap
->ts_max_resident_size
= get_task_resident_max(task
);
1346 cur_tsnap
->ts_was_throttled
= (uint32_t) proc_was_throttled_from_task(task
);
1347 cur_tsnap
->ts_did_throttle
= (uint32_t) proc_did_throttle_from_task(task
);
1349 cur_tsnap
->ts_suspend_count
= task
->suspend_count
;
1350 cur_tsnap
->ts_faults
= task
->faults
;
1351 cur_tsnap
->ts_pageins
= task
->pageins
;
1352 cur_tsnap
->ts_cow_faults
= task
->cow_faults
;
1353 cur_tsnap
->ts_latency_qos
= (task
->effective_policy
.tep_latency_qos
== LATENCY_QOS_TIER_UNSPECIFIED
) ?
1354 LATENCY_QOS_TIER_UNSPECIFIED
: ((0xFF << 16) | task
->effective_policy
.tep_latency_qos
);
1355 cur_tsnap
->ts_pid
= task_pid
;
1357 /* Add the BSD process identifiers */
1358 if (task_pid
!= -1 && task
->bsd_info
!= NULL
) {
1359 proc_name_kdp(task
, cur_tsnap
->ts_p_comm
, sizeof(cur_tsnap
->ts_p_comm
));
1361 cur_tsnap
->ts_p_comm
[0] = '\0';
1362 #if IMPORTANCE_INHERITANCE && (DEVELOPMENT || DEBUG)
1363 if (task
->task_imp_base
!= NULL
) {
1364 stackshot_strlcpy(cur_tsnap
->ts_p_comm
, &task
->task_imp_base
->iit_procname
[0],
1365 MIN((int)sizeof(task
->task_imp_base
->iit_procname
), (int)sizeof(cur_tsnap
->ts_p_comm
)));
1367 #endif /* IMPORTANCE_INHERITANCE && (DEVELOPMENT || DEBUG) */
1370 kcd_exit_on_error(kcdata_compression_window_close(kcd
));
1372 #if CONFIG_COALITIONS
1373 if (task_pid
!= -1 && task
->bsd_info
!= NULL
&&
1374 ((trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) && (task
->coalition
[COALITION_TYPE_JETSAM
] != NULL
))) {
1375 uint64_t jetsam_coal_id
= coalition_id(task
->coalition
[COALITION_TYPE_JETSAM
]);
1376 kcd_exit_on_error(kcdata_push_data(kcd
, STACKSHOT_KCTYPE_JETSAM_COALITION
, sizeof(jetsam_coal_id
), &jetsam_coal_id
));
1378 #endif /* CONFIG_COALITIONS */
1380 #if __arm__ || __arm64__
1381 if (collect_asid
&& have_pmap
) {
1382 uint32_t asid
= PMAP_VASID(task
->map
->pmap
);
1383 kcd_exit_on_error(kcdata_push_data(kcd
, STACKSHOT_KCTYPE_ASID
, sizeof(asid
), &asid
));
1387 #if STACKSHOT_COLLECTS_LATENCY_INFO
1388 latency_info
->cur_tsnap_latency
= mach_absolute_time() - latency_info
->cur_tsnap_latency
;
1389 latency_info
->pmap_latency
= mach_absolute_time();
1390 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1392 if (collect_pagetables
&& have_pmap
) {
1393 #if INTERRUPT_MASKED_DEBUG
1394 // pagetable dumps can be large; reset the interrupt timeout to avoid a panic
1395 ml_spin_debug_clear_self();
1397 size_t bytes_dumped
= 0;
1398 error
= pmap_dump_page_tables(task
->map
->pmap
, kcd_end_address(kcd
), kcd_max_address(kcd
), stack_snapshot_pagetable_mask
, &bytes_dumped
);
1399 if (error
!= KERN_SUCCESS
) {
1402 /* Variable size array - better not have it on the stack. */
1403 kcdata_compression_window_open(kcd
);
1404 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, STACKSHOT_KCTYPE_PAGE_TABLES
,
1405 sizeof(uint64_t), (uint32_t)(bytes_dumped
/ sizeof(uint64_t)), &out_addr
));
1406 kcd_exit_on_error(kcdata_compression_window_close(kcd
));
1410 #if STACKSHOT_COLLECTS_LATENCY_INFO
1411 latency_info
->pmap_latency
= mach_absolute_time() - latency_info
->pmap_latency
;
1412 latency_info
->bsd_proc_ids_latency
= mach_absolute_time();
1413 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1415 #if STACKSHOT_COLLECTS_LATENCY_INFO
1416 latency_info
->bsd_proc_ids_latency
= mach_absolute_time() - latency_info
->bsd_proc_ids_latency
;
1417 latency_info
->end_latency
= mach_absolute_time();
1418 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1420 if (collect_iostats
) {
1421 kcd_exit_on_error(kcdata_record_task_iostats(kcd
, task
));
1425 if (collect_instrs_cycles
) {
1426 kcd_exit_on_error(kcdata_record_task_instrs_cycles(kcd
, task
));
1428 #endif /* MONOTONIC */
1430 kcd_exit_on_error(kcdata_record_task_cpu_architecture(kcd
, task
));
1432 #if STACKSHOT_COLLECTS_LATENCY_INFO
1433 latency_info
->end_latency
= mach_absolute_time() - latency_info
->end_latency
;
1434 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1440 static kern_return_t
1441 kcdata_record_task_delta_snapshot(kcdata_descriptor_t kcd
, task_t task
, uint64_t trace_flags
, boolean_t have_pmap
, unaligned_u64 task_snap_ss_flags
)
1444 #pragma unused(trace_flags)
1445 #endif /* !MONOTONIC */
1446 kern_return_t error
= KERN_SUCCESS
;
1447 struct task_delta_snapshot_v2
* cur_tsnap
= NULL
;
1448 mach_vm_address_t out_addr
= 0;
1450 #if __arm__ || __arm64__
1451 boolean_t collect_asid
= ((trace_flags
& STACKSHOT_ASID
) != 0);
1454 boolean_t collect_instrs_cycles
= ((trace_flags
& STACKSHOT_INSTRS_CYCLES
) != 0);
1455 #endif /* MONOTONIC */
1457 uint64_t task_uniqueid
= get_task_uniqueid(task
);
1459 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_TASK_DELTA_SNAPSHOT
, sizeof(struct task_delta_snapshot_v2
), &out_addr
));
1461 cur_tsnap
= (struct task_delta_snapshot_v2
*)out_addr
;
1463 cur_tsnap
->tds_unique_pid
= task_uniqueid
;
1464 cur_tsnap
->tds_ss_flags
= kcdata_get_task_ss_flags(task
);
1465 cur_tsnap
->tds_ss_flags
|= task_snap_ss_flags
;
1467 cur_tsnap
->tds_user_time_in_terminated_threads
= task
->total_user_time
;
1468 cur_tsnap
->tds_system_time_in_terminated_threads
= task
->total_system_time
;
1470 cur_tsnap
->tds_task_size
= have_pmap
? get_task_phys_footprint(task
) : 0;
1472 cur_tsnap
->tds_max_resident_size
= get_task_resident_max(task
);
1473 cur_tsnap
->tds_suspend_count
= task
->suspend_count
;
1474 cur_tsnap
->tds_faults
= task
->faults
;
1475 cur_tsnap
->tds_pageins
= task
->pageins
;
1476 cur_tsnap
->tds_cow_faults
= task
->cow_faults
;
1477 cur_tsnap
->tds_was_throttled
= (uint32_t)proc_was_throttled_from_task(task
);
1478 cur_tsnap
->tds_did_throttle
= (uint32_t)proc_did_throttle_from_task(task
);
1479 cur_tsnap
->tds_latency_qos
= (task
->effective_policy
.tep_latency_qos
== LATENCY_QOS_TIER_UNSPECIFIED
)
1480 ? LATENCY_QOS_TIER_UNSPECIFIED
1481 : ((0xFF << 16) | task
->effective_policy
.tep_latency_qos
);
1483 #if __arm__ || __arm64__
1484 if (collect_asid
&& have_pmap
) {
1485 uint32_t asid
= PMAP_VASID(task
->map
->pmap
);
1486 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_ASID
, sizeof(uint32_t), &out_addr
));
1487 stackshot_memcpy((void*)out_addr
, &asid
, sizeof(asid
));
1492 if (collect_instrs_cycles
) {
1493 kcd_exit_on_error(kcdata_record_task_instrs_cycles(kcd
, task
));
1495 #endif /* MONOTONIC */
1501 static kern_return_t
1502 kcdata_record_thread_iostats(kcdata_descriptor_t kcd
, thread_t thread
)
1504 kern_return_t error
= KERN_SUCCESS
;
1505 mach_vm_address_t out_addr
= 0;
1507 /* I/O Statistics */
1508 assert(IO_NUM_PRIORITIES
== STACKSHOT_IO_NUM_PRIORITIES
);
1509 if (thread
->thread_io_stats
&& !memory_iszero(thread
->thread_io_stats
, sizeof(struct io_stat_info
))) {
1510 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_IOSTATS
, sizeof(struct io_stats_snapshot
), &out_addr
));
1511 struct io_stats_snapshot
*_iostat
= (struct io_stats_snapshot
*)out_addr
;
1512 _iostat
->ss_disk_reads_count
= thread
->thread_io_stats
->disk_reads
.count
;
1513 _iostat
->ss_disk_reads_size
= thread
->thread_io_stats
->disk_reads
.size
;
1514 _iostat
->ss_disk_writes_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->disk_reads
.count
);
1515 _iostat
->ss_disk_writes_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->disk_reads
.size
);
1516 _iostat
->ss_paging_count
= thread
->thread_io_stats
->paging
.count
;
1517 _iostat
->ss_paging_size
= thread
->thread_io_stats
->paging
.size
;
1518 _iostat
->ss_non_paging_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->paging
.count
);
1519 _iostat
->ss_non_paging_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->paging
.size
);
1520 _iostat
->ss_metadata_count
= thread
->thread_io_stats
->metadata
.count
;
1521 _iostat
->ss_metadata_size
= thread
->thread_io_stats
->metadata
.size
;
1522 _iostat
->ss_data_count
= (thread
->thread_io_stats
->total_io
.count
- thread
->thread_io_stats
->metadata
.count
);
1523 _iostat
->ss_data_size
= (thread
->thread_io_stats
->total_io
.size
- thread
->thread_io_stats
->metadata
.size
);
1524 for (int i
= 0; i
< IO_NUM_PRIORITIES
; i
++) {
1525 _iostat
->ss_io_priority_count
[i
] = thread
->thread_io_stats
->io_priority
[i
].count
;
1526 _iostat
->ss_io_priority_size
[i
] = thread
->thread_io_stats
->io_priority
[i
].size
;
1534 static kern_return_t
1535 kcdata_record_thread_snapshot(
1536 kcdata_descriptor_t kcd
, thread_t thread
, task_t task
, uint64_t trace_flags
, boolean_t have_pmap
, boolean_t thread_on_core
)
1538 boolean_t dispatch_p
= ((trace_flags
& STACKSHOT_GET_DQ
) != 0);
1539 boolean_t active_kthreads_only_p
= ((trace_flags
& STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY
) != 0);
1540 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1541 boolean_t collect_iostats
= !collect_delta_stackshot
&& !(trace_flags
& STACKSHOT_NO_IO_STATS
);
1543 boolean_t collect_instrs_cycles
= ((trace_flags
& STACKSHOT_INSTRS_CYCLES
) != 0);
1544 #endif /* MONOTONIC */
1545 kern_return_t error
= KERN_SUCCESS
;
1547 #if STACKSHOT_COLLECTS_LATENCY_INFO
1548 struct stackshot_latency_thread latency_info
;
1549 latency_info
.cur_thsnap1_latency
= mach_absolute_time();
1550 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1552 mach_vm_address_t out_addr
= 0;
1553 int saved_count
= 0;
1555 struct thread_snapshot_v4
* cur_thread_snap
= NULL
;
1556 char cur_thread_name
[STACKSHOT_MAX_THREAD_NAME_SIZE
];
1558 const boolean_t is_64bit_data
= task_has_64Bit_data(task
);
1560 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_SNAPSHOT
, sizeof(struct thread_snapshot_v4
), &out_addr
));
1561 cur_thread_snap
= (struct thread_snapshot_v4
*)out_addr
;
1563 /* Populate the thread snapshot header */
1564 cur_thread_snap
->ths_ss_flags
= 0;
1565 cur_thread_snap
->ths_thread_id
= thread_tid(thread
);
1566 cur_thread_snap
->ths_wait_event
= VM_KERNEL_UNSLIDE_OR_PERM(thread
->wait_event
);
1567 cur_thread_snap
->ths_continuation
= VM_KERNEL_UNSLIDE(thread
->continuation
);
1568 cur_thread_snap
->ths_total_syscalls
= thread
->syscalls_mach
+ thread
->syscalls_unix
;
1570 if (IPC_VOUCHER_NULL
!= thread
->ith_voucher
) {
1571 cur_thread_snap
->ths_voucher_identifier
= VM_KERNEL_ADDRPERM(thread
->ith_voucher
);
1573 cur_thread_snap
->ths_voucher_identifier
= 0;
1576 #if STACKSHOT_COLLECTS_LATENCY_INFO
1577 latency_info
.cur_thsnap1_latency
= mach_absolute_time() - latency_info
.cur_thsnap1_latency
;
1578 latency_info
.dispatch_serial_latency
= mach_absolute_time();
1579 latency_info
.dispatch_label_latency
= 0;
1580 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1582 cur_thread_snap
->ths_dqserialnum
= 0;
1583 if (dispatch_p
&& (task
!= kernel_task
) && (task
->active
) && have_pmap
) {
1584 uint64_t dqkeyaddr
= thread_dispatchqaddr(thread
);
1585 if (dqkeyaddr
!= 0) {
1586 uint64_t dqaddr
= 0;
1587 boolean_t copyin_ok
= kdp_copyin_word(task
, dqkeyaddr
, &dqaddr
, FALSE
, NULL
);
1588 if (copyin_ok
&& dqaddr
!= 0) {
1589 uint64_t dqserialnumaddr
= dqaddr
+ get_task_dispatchqueue_serialno_offset(task
);
1590 uint64_t dqserialnum
= 0;
1591 copyin_ok
= kdp_copyin_word(task
, dqserialnumaddr
, &dqserialnum
, FALSE
, NULL
);
1593 cur_thread_snap
->ths_ss_flags
|= kHasDispatchSerial
;
1594 cur_thread_snap
->ths_dqserialnum
= dqserialnum
;
1597 #if STACKSHOT_COLLECTS_LATENCY_INFO
1598 latency_info
.dispatch_serial_latency
= mach_absolute_time() - latency_info
.dispatch_serial_latency
;
1599 latency_info
.dispatch_label_latency
= mach_absolute_time();
1600 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1602 /* try copying in the queue label */
1603 uint64_t label_offs
= get_task_dispatchqueue_label_offset(task
);
1605 uint64_t dqlabeladdr
= dqaddr
+ label_offs
;
1606 uint64_t actual_dqlabeladdr
= 0;
1608 copyin_ok
= kdp_copyin_word(task
, dqlabeladdr
, &actual_dqlabeladdr
, FALSE
, NULL
);
1609 if (copyin_ok
&& actual_dqlabeladdr
!= 0) {
1610 char label_buf
[STACKSHOT_QUEUE_LABEL_MAXSIZE
];
1613 bzero(label_buf
, STACKSHOT_QUEUE_LABEL_MAXSIZE
* sizeof(char));
1614 len
= kdp_copyin_string(task
, actual_dqlabeladdr
, label_buf
, STACKSHOT_QUEUE_LABEL_MAXSIZE
, FALSE
, NULL
);
1616 mach_vm_address_t label_addr
= 0;
1617 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_DISPATCH_QUEUE_LABEL
, len
, &label_addr
));
1618 stackshot_strlcpy((char*)label_addr
, &label_buf
[0], len
);
1622 #if STACKSHOT_COLLECTS_LATENCY_INFO
1623 latency_info
.dispatch_label_latency
= mach_absolute_time() - latency_info
.dispatch_label_latency
;
1624 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1629 #if STACKSHOT_COLLECTS_LATENCY_INFO
1630 if ((cur_thread_snap
->ths_ss_flags
& kHasDispatchSerial
) == 0) {
1631 latency_info
.dispatch_serial_latency
= 0;
1633 latency_info
.cur_thsnap2_latency
= mach_absolute_time();
1634 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1636 tval
= safe_grab_timer_value(&thread
->user_timer
);
1637 cur_thread_snap
->ths_user_time
= tval
;
1638 tval
= safe_grab_timer_value(&thread
->system_timer
);
1640 if (thread
->precise_user_kernel_time
) {
1641 cur_thread_snap
->ths_sys_time
= tval
;
1643 cur_thread_snap
->ths_user_time
+= tval
;
1644 cur_thread_snap
->ths_sys_time
= 0;
1647 if (thread
->thread_tag
& THREAD_TAG_MAINTHREAD
) {
1648 cur_thread_snap
->ths_ss_flags
|= kThreadMain
;
1650 if (thread
->effective_policy
.thep_darwinbg
) {
1651 cur_thread_snap
->ths_ss_flags
|= kThreadDarwinBG
;
1653 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_PASSIVE_IO
)) {
1654 cur_thread_snap
->ths_ss_flags
|= kThreadIOPassive
;
1656 if (thread
->suspend_count
> 0) {
1657 cur_thread_snap
->ths_ss_flags
|= kThreadSuspended
;
1659 if (thread
->options
& TH_OPT_GLOBAL_FORCED_IDLE
) {
1660 cur_thread_snap
->ths_ss_flags
|= kGlobalForcedIdle
;
1662 if (thread_on_core
) {
1663 cur_thread_snap
->ths_ss_flags
|= kThreadOnCore
;
1665 if (stackshot_thread_is_idle_worker_unsafe(thread
)) {
1666 cur_thread_snap
->ths_ss_flags
|= kThreadIdleWorker
;
1669 /* make sure state flags defined in kcdata.h still match internal flags */
1670 static_assert(SS_TH_WAIT
== TH_WAIT
);
1671 static_assert(SS_TH_SUSP
== TH_SUSP
);
1672 static_assert(SS_TH_RUN
== TH_RUN
);
1673 static_assert(SS_TH_UNINT
== TH_UNINT
);
1674 static_assert(SS_TH_TERMINATE
== TH_TERMINATE
);
1675 static_assert(SS_TH_TERMINATE2
== TH_TERMINATE2
);
1676 static_assert(SS_TH_IDLE
== TH_IDLE
);
1678 cur_thread_snap
->ths_last_run_time
= thread
->last_run_time
;
1679 cur_thread_snap
->ths_last_made_runnable_time
= thread
->last_made_runnable_time
;
1680 cur_thread_snap
->ths_state
= thread
->state
;
1681 cur_thread_snap
->ths_sched_flags
= thread
->sched_flags
;
1682 cur_thread_snap
->ths_base_priority
= thread
->base_pri
;
1683 cur_thread_snap
->ths_sched_priority
= thread
->sched_pri
;
1684 cur_thread_snap
->ths_eqos
= thread
->effective_policy
.thep_qos
;
1685 cur_thread_snap
->ths_rqos
= thread
->requested_policy
.thrp_qos
;
1686 cur_thread_snap
->ths_rqos_override
= MAX(thread
->requested_policy
.thrp_qos_override
,
1687 thread
->requested_policy
.thrp_qos_workq_override
);
1688 cur_thread_snap
->ths_io_tier
= (uint8_t) proc_get_effective_thread_policy(thread
, TASK_POLICY_IO
);
1689 cur_thread_snap
->ths_thread_t
= VM_KERNEL_UNSLIDE_OR_PERM(thread
);
1691 static_assert(sizeof(thread
->effective_policy
) == sizeof(uint64_t));
1692 static_assert(sizeof(thread
->requested_policy
) == sizeof(uint64_t));
1693 cur_thread_snap
->ths_requested_policy
= *(unaligned_u64
*) &thread
->requested_policy
;
1694 cur_thread_snap
->ths_effective_policy
= *(unaligned_u64
*) &thread
->effective_policy
;
1696 #if STACKSHOT_COLLECTS_LATENCY_INFO
1697 latency_info
.cur_thsnap2_latency
= mach_absolute_time() - latency_info
.cur_thsnap2_latency
;
1698 latency_info
.thread_name_latency
= mach_absolute_time();
1699 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1701 /* if there is thread name then add to buffer */
1702 cur_thread_name
[0] = '\0';
1703 proc_threadname_kdp(thread
->uthread
, cur_thread_name
, STACKSHOT_MAX_THREAD_NAME_SIZE
);
1704 if (strnlen(cur_thread_name
, STACKSHOT_MAX_THREAD_NAME_SIZE
) > 0) {
1705 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_NAME
, sizeof(cur_thread_name
), &out_addr
));
1706 stackshot_memcpy((void *)out_addr
, (void *)cur_thread_name
, sizeof(cur_thread_name
));
1709 #if STACKSHOT_COLLECTS_LATENCY_INFO
1710 latency_info
.thread_name_latency
= mach_absolute_time() - latency_info
.thread_name_latency
;
1711 latency_info
.sur_times_latency
= mach_absolute_time();
1712 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1714 /* record system, user, and runnable times */
1715 time_value_t user_time
, system_time
, runnable_time
;
1716 thread_read_times(thread
, &user_time
, &system_time
, &runnable_time
);
1717 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_CPU_TIMES
, sizeof(struct stackshot_cpu_times_v2
), &out_addr
));
1718 struct stackshot_cpu_times_v2
*stackshot_cpu_times
= (struct stackshot_cpu_times_v2
*)out_addr
;
1719 *stackshot_cpu_times
= (struct stackshot_cpu_times_v2
){
1720 .user_usec
= (uint64_t)user_time
.seconds
* USEC_PER_SEC
+ user_time
.microseconds
,
1721 .system_usec
= (uint64_t)system_time
.seconds
* USEC_PER_SEC
+ system_time
.microseconds
,
1722 .runnable_usec
= (uint64_t)runnable_time
.seconds
* USEC_PER_SEC
+ runnable_time
.microseconds
,
1725 #if STACKSHOT_COLLECTS_LATENCY_INFO
1726 latency_info
.sur_times_latency
= mach_absolute_time() - latency_info
.sur_times_latency
;
1727 latency_info
.user_stack_latency
= mach_absolute_time();
1728 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1730 /* Trace user stack, if any */
1731 if (!active_kthreads_only_p
&& task
->active
&& thread
->task
->map
!= kernel_map
) {
1732 uint32_t thread_snapshot_flags
= 0;
1734 /* Uses 64-bit machine state? */
1735 if (is_64bit_data
) {
1737 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1742 saved_count
= machine_trace_thread64(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, TRUE
,
1743 &thread_snapshot_flags
, &sp
, fp
);
1744 if (saved_count
> 0) {
1745 int frame_size
= sizeof(uint64_t);
1746 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, STACKSHOT_KCTYPE_USER_STACKLR64
,
1747 frame_size
, saved_count
/ frame_size
, &out_addr
));
1748 cur_thread_snap
->ths_ss_flags
|= kUser64_p
;
1752 // I'm using 8 here and not sizeof(stack_contents) because this
1753 // code would not work if you just made stack_contents bigger.
1754 vm_offset_t kern_virt_addr
= machine_trace_thread_get_kva(sp
, thread
->task
->map
, &thread_snapshot_flags
);
1755 if (kern_virt_addr
&& (kern_virt_addr
% 8) == 0) {
1756 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_USER_STACKTOP
, sizeof(struct stack_snapshot_stacktop
), &out_addr
));
1757 struct stack_snapshot_stacktop
*stacktop
= (struct stack_snapshot_stacktop
*)out_addr
;
1759 memcpy(stacktop
->stack_contents
, (void*) kern_virt_addr
, 8);
1762 #endif /* __x86_64__ */
1764 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1765 saved_count
= machine_trace_thread(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, TRUE
,
1766 &thread_snapshot_flags
);
1767 if (saved_count
> 0) {
1768 int frame_size
= sizeof(uint32_t);
1769 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, STACKSHOT_KCTYPE_USER_STACKLR
,
1770 frame_size
, saved_count
/ frame_size
, &out_addr
));
1774 if (thread_snapshot_flags
!= 0) {
1775 cur_thread_snap
->ths_ss_flags
|= thread_snapshot_flags
;
1779 #if STACKSHOT_COLLECTS_LATENCY_INFO
1780 latency_info
.user_stack_latency
= mach_absolute_time() - latency_info
.user_stack_latency
;
1781 latency_info
.kernel_stack_latency
= mach_absolute_time();
1782 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1784 /* Call through to the machine specific trace routines
1785 * Frames are added past the snapshot header.
1787 if (thread
->kernel_stack
!= 0) {
1788 uint32_t thread_snapshot_flags
= 0;
1789 #if defined(__LP64__)
1790 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1791 saved_count
= machine_trace_thread64(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, FALSE
,
1792 &thread_snapshot_flags
, NULL
, 0);
1793 if (saved_count
> 0) {
1794 int frame_size
= sizeof(uint64_t);
1795 cur_thread_snap
->ths_ss_flags
|= kKernel64_p
;
1796 kcd_exit_on_error(kcdata_get_memory_addr_for_array(kcd
, STACKSHOT_KCTYPE_KERN_STACKLR64
,
1797 frame_size
, saved_count
/ frame_size
, &out_addr
));
1800 out_addr
= (mach_vm_address_t
)kcd_end_address(kcd
);
1801 saved_count
= machine_trace_thread(thread
, (char *)out_addr
, (char *)kcd_max_address(kcd
), MAX_FRAMES
, FALSE
,
1802 &thread_snapshot_flags
);
1803 if (saved_count
> 0) {
1804 int frame_size
= sizeof(uint32_t);
1806 kcdata_get_memory_addr_for_array(kcd
, STACKSHOT_KCTYPE_KERN_STACKLR
, frame_size
,
1807 saved_count
/ frame_size
, &out_addr
));
1810 if (thread_snapshot_flags
!= 0) {
1811 cur_thread_snap
->ths_ss_flags
|= thread_snapshot_flags
;
1815 #if STACKSHOT_COLLECTS_LATENCY_INFO
1816 latency_info
.kernel_stack_latency
= mach_absolute_time() - latency_info
.kernel_stack_latency
;
1817 latency_info
.misc_latency
= mach_absolute_time();
1818 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1820 #if CONFIG_THREAD_GROUPS
1821 if (trace_flags
& STACKSHOT_THREAD_GROUP
) {
1822 uint64_t thread_group_id
= thread
->thread_group
? thread_group_get_id(thread
->thread_group
) : 0;
1823 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_THREAD_GROUP
, sizeof(thread_group_id
), &out_addr
));
1824 stackshot_memcpy((void*)out_addr
, &thread_group_id
, sizeof(uint64_t));
1826 #endif /* CONFIG_THREAD_GROUPS */
1828 if (collect_iostats
) {
1829 kcd_exit_on_error(kcdata_record_thread_iostats(kcd
, thread
));
1833 if (collect_instrs_cycles
) {
1834 uint64_t instrs
= 0, cycles
= 0;
1835 mt_stackshot_thread(thread
, &instrs
, &cycles
);
1837 kcd_exit_on_error(kcdata_get_memory_addr(kcd
, STACKSHOT_KCTYPE_INSTRS_CYCLES
, sizeof(struct instrs_cycles_snapshot
), &out_addr
));
1838 struct instrs_cycles_snapshot
*instrs_cycles
= (struct instrs_cycles_snapshot
*)out_addr
;
1839 instrs_cycles
->ics_instructions
= instrs
;
1840 instrs_cycles
->ics_cycles
= cycles
;
1842 #endif /* MONOTONIC */
1844 #if STACKSHOT_COLLECTS_LATENCY_INFO
1845 latency_info
.misc_latency
= mach_absolute_time() - latency_info
.misc_latency
;
1846 if (collect_latency_info
) {
1847 kcd_exit_on_error(kcdata_push_data(kcd
, STACKSHOT_KCTYPE_LATENCY_INFO_THREAD
, sizeof(latency_info
), &latency_info
));
1849 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1856 kcdata_record_thread_delta_snapshot(struct thread_delta_snapshot_v3
* cur_thread_snap
, thread_t thread
, boolean_t thread_on_core
)
1858 cur_thread_snap
->tds_thread_id
= thread_tid(thread
);
1859 if (IPC_VOUCHER_NULL
!= thread
->ith_voucher
) {
1860 cur_thread_snap
->tds_voucher_identifier
= VM_KERNEL_ADDRPERM(thread
->ith_voucher
);
1862 cur_thread_snap
->tds_voucher_identifier
= 0;
1865 cur_thread_snap
->tds_ss_flags
= 0;
1866 if (thread
->effective_policy
.thep_darwinbg
) {
1867 cur_thread_snap
->tds_ss_flags
|= kThreadDarwinBG
;
1869 if (proc_get_effective_thread_policy(thread
, TASK_POLICY_PASSIVE_IO
)) {
1870 cur_thread_snap
->tds_ss_flags
|= kThreadIOPassive
;
1872 if (thread
->suspend_count
> 0) {
1873 cur_thread_snap
->tds_ss_flags
|= kThreadSuspended
;
1875 if (thread
->options
& TH_OPT_GLOBAL_FORCED_IDLE
) {
1876 cur_thread_snap
->tds_ss_flags
|= kGlobalForcedIdle
;
1878 if (thread_on_core
) {
1879 cur_thread_snap
->tds_ss_flags
|= kThreadOnCore
;
1881 if (stackshot_thread_is_idle_worker_unsafe(thread
)) {
1882 cur_thread_snap
->tds_ss_flags
|= kThreadIdleWorker
;
1885 cur_thread_snap
->tds_last_made_runnable_time
= thread
->last_made_runnable_time
;
1886 cur_thread_snap
->tds_state
= thread
->state
;
1887 cur_thread_snap
->tds_sched_flags
= thread
->sched_flags
;
1888 cur_thread_snap
->tds_base_priority
= thread
->base_pri
;
1889 cur_thread_snap
->tds_sched_priority
= thread
->sched_pri
;
1890 cur_thread_snap
->tds_eqos
= thread
->effective_policy
.thep_qos
;
1891 cur_thread_snap
->tds_rqos
= thread
->requested_policy
.thrp_qos
;
1892 cur_thread_snap
->tds_rqos_override
= MAX(thread
->requested_policy
.thrp_qos_override
,
1893 thread
->requested_policy
.thrp_qos_workq_override
);
1894 cur_thread_snap
->tds_io_tier
= (uint8_t) proc_get_effective_thread_policy(thread
, TASK_POLICY_IO
);
1896 static_assert(sizeof(thread
->effective_policy
) == sizeof(uint64_t));
1897 static_assert(sizeof(thread
->requested_policy
) == sizeof(uint64_t));
1898 cur_thread_snap
->tds_requested_policy
= *(unaligned_u64
*) &thread
->requested_policy
;
1899 cur_thread_snap
->tds_effective_policy
= *(unaligned_u64
*) &thread
->effective_policy
;
1905 * Why 12? 12 strikes a decent balance between allocating a large array on
1906 * the stack and having large kcdata item overheads for recording nonrunable
1909 #define UNIQUEIDSPERFLUSH 12
1911 struct saved_uniqueids
{
1912 uint64_t ids
[UNIQUEIDSPERFLUSH
];
1916 enum thread_classification
{
1917 tc_full_snapshot
, /* take a full snapshot */
1918 tc_delta_snapshot
, /* take a delta snapshot */
1921 static enum thread_classification
1922 classify_thread(thread_t thread
, boolean_t
* thread_on_core_p
, uint64_t trace_flags
)
1924 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1926 processor_t last_processor
= thread
->last_processor
;
1928 boolean_t thread_on_core
=
1929 (last_processor
!= PROCESSOR_NULL
&&
1930 (last_processor
->state
== PROCESSOR_SHUTDOWN
|| last_processor
->state
== PROCESSOR_RUNNING
) &&
1931 last_processor
->active_thread
== thread
);
1933 *thread_on_core_p
= thread_on_core
;
1935 /* Capture the full thread snapshot if this is not a delta stackshot or if the thread has run subsequent to the
1936 * previous full stackshot */
1937 if (!collect_delta_stackshot
|| thread_on_core
|| (thread
->last_run_time
> stack_snapshot_delta_since_timestamp
)) {
1938 return tc_full_snapshot
;
1940 return tc_delta_snapshot
;
1944 struct stackshot_context
{
1946 uint64_t trace_flags
;
1949 static kern_return_t
1950 kdp_stackshot_record_task(struct stackshot_context
*ctx
, task_t task
)
1952 boolean_t active_kthreads_only_p
= ((ctx
->trace_flags
& STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY
) != 0);
1953 boolean_t save_donating_pids_p
= ((ctx
->trace_flags
& STACKSHOT_SAVE_IMP_DONATION_PIDS
) != 0);
1954 boolean_t collect_delta_stackshot
= ((ctx
->trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
1955 boolean_t save_owner_info
= ((ctx
->trace_flags
& STACKSHOT_THREAD_WAITINFO
) != 0);
1957 kern_return_t error
= KERN_SUCCESS
;
1958 mach_vm_address_t out_addr
= 0;
1959 int saved_count
= 0;
1962 uint64_t task_uniqueid
= 0;
1963 int num_delta_thread_snapshots
= 0;
1964 int num_waitinfo_threads
= 0;
1965 int num_turnstileinfo_threads
= 0;
1967 uint64_t task_start_abstime
= 0;
1968 boolean_t have_map
= FALSE
, have_pmap
= FALSE
;
1969 boolean_t some_thread_ran
= FALSE
;
1970 unaligned_u64 task_snap_ss_flags
= 0;
1972 #if STACKSHOT_COLLECTS_LATENCY_INFO
1973 struct stackshot_latency_task latency_info
;
1974 latency_info
.setup_latency
= mach_absolute_time();
1975 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
1977 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
1978 uint64_t task_begin_cpu_cycle_count
= 0;
1979 if (!panic_stackshot
) {
1980 task_begin_cpu_cycle_count
= mt_cur_cpu_cycles();
1984 if ((task
== NULL
) || !ml_validate_nofault((vm_offset_t
)task
, sizeof(struct task
))) {
1985 error
= KERN_FAILURE
;
1989 have_map
= (task
->map
!= NULL
) && (ml_validate_nofault((vm_offset_t
)(task
->map
), sizeof(struct _vm_map
)));
1990 have_pmap
= have_map
&& (task
->map
->pmap
!= NULL
) && (ml_validate_nofault((vm_offset_t
)(task
->map
->pmap
), sizeof(struct pmap
)));
1992 task_pid
= pid_from_task(task
);
1993 task_uniqueid
= get_task_uniqueid(task
);
1995 if (!task
->active
|| task_is_a_corpse(task
) || task_is_a_corpse_fork(task
)) {
1997 * Not interested in terminated tasks without threads.
1999 if (queue_empty(&task
->threads
) || task_pid
== -1) {
2000 return KERN_SUCCESS
;
2004 /* All PIDs should have the MSB unset */
2005 assert((task_pid
& (1ULL << 31)) == 0);
2007 #if STACKSHOT_COLLECTS_LATENCY_INFO
2008 latency_info
.setup_latency
= mach_absolute_time() - latency_info
.setup_latency
;
2009 latency_info
.task_uniqueid
= task_uniqueid
;
2010 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2012 /* Trace everything, unless a process was specified */
2013 if ((ctx
->pid
== -1) || (ctx
->pid
== task_pid
)) {
2014 /* add task snapshot marker */
2015 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_BEGIN
,
2016 STACKSHOT_KCCONTAINER_TASK
, task_uniqueid
));
2018 if (collect_delta_stackshot
) {
2020 * For delta stackshots we need to know if a thread from this task has run since the
2021 * previous timestamp to decide whether we're going to record a full snapshot and UUID info.
2023 thread_t thread
= THREAD_NULL
;
2024 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
2026 if ((thread
== NULL
) || !ml_validate_nofault((vm_offset_t
)thread
, sizeof(struct thread
))) {
2027 error
= KERN_FAILURE
;
2031 if (active_kthreads_only_p
&& thread
->kernel_stack
== 0) {
2035 boolean_t thread_on_core
;
2036 enum thread_classification thread_classification
= classify_thread(thread
, &thread_on_core
, ctx
->trace_flags
);
2038 switch (thread_classification
) {
2039 case tc_full_snapshot
:
2040 some_thread_ran
= TRUE
;
2042 case tc_delta_snapshot
:
2043 num_delta_thread_snapshots
++;
2049 if (collect_delta_stackshot
) {
2050 proc_starttime_kdp(task
->bsd_info
, NULL
, NULL
, &task_start_abstime
);
2053 /* Next record any relevant UUID info and store the task snapshot */
2054 if (!collect_delta_stackshot
||
2055 (task_start_abstime
== 0) ||
2056 (task_start_abstime
> stack_snapshot_delta_since_timestamp
) ||
2059 * Collect full task information in these scenarios:
2061 * 1) a full stackshot
2062 * 2) a delta stackshot where the task started after the previous full stackshot
2063 * 3) a delta stackshot where any thread from the task has run since the previous full stackshot
2065 * because the task may have exec'ed, changing its name, architecture, load info, etc
2068 kcd_exit_on_error(kcdata_record_shared_cache_info(stackshot_kcdata_p
, task
, &task_snap_ss_flags
));
2069 kcd_exit_on_error(kcdata_record_uuid_info(stackshot_kcdata_p
, task
, ctx
->trace_flags
, have_pmap
, &task_snap_ss_flags
));
2070 #if STACKSHOT_COLLECTS_LATENCY_INFO
2071 kcd_exit_on_error(kcdata_record_task_snapshot(stackshot_kcdata_p
, task
, ctx
->trace_flags
, have_pmap
, task_snap_ss_flags
, &latency_info
));
2073 kcd_exit_on_error(kcdata_record_task_snapshot(stackshot_kcdata_p
, task
, ctx
->trace_flags
, have_pmap
, task_snap_ss_flags
));
2074 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2076 kcd_exit_on_error(kcdata_record_task_delta_snapshot(stackshot_kcdata_p
, task
, ctx
->trace_flags
, have_pmap
, task_snap_ss_flags
));
2079 #if STACKSHOT_COLLECTS_LATENCY_INFO
2080 latency_info
.misc_latency
= mach_absolute_time();
2081 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2083 struct thread_delta_snapshot_v3
* delta_snapshots
= NULL
;
2084 int current_delta_snapshot_index
= 0;
2085 if (num_delta_thread_snapshots
> 0) {
2086 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_DELTA_SNAPSHOT
,
2087 sizeof(struct thread_delta_snapshot_v3
),
2088 num_delta_thread_snapshots
, &out_addr
));
2089 delta_snapshots
= (struct thread_delta_snapshot_v3
*)out_addr
;
2093 #if STACKSHOT_COLLECTS_LATENCY_INFO
2094 latency_info
.task_thread_count_loop_latency
= mach_absolute_time();
2097 * Iterate over the task threads to save thread snapshots and determine
2098 * how much space we need for waitinfo and turnstile info
2100 thread_t thread
= THREAD_NULL
;
2101 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
2103 if ((thread
== NULL
) || !ml_validate_nofault((vm_offset_t
)thread
, sizeof(struct thread
))) {
2104 error
= KERN_FAILURE
;
2108 uint64_t thread_uniqueid
;
2109 if (active_kthreads_only_p
&& thread
->kernel_stack
== 0) {
2112 thread_uniqueid
= thread_tid(thread
);
2114 boolean_t thread_on_core
;
2115 enum thread_classification thread_classification
= classify_thread(thread
, &thread_on_core
, ctx
->trace_flags
);
2117 switch (thread_classification
) {
2118 case tc_full_snapshot
:
2119 /* add thread marker */
2120 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_BEGIN
,
2121 STACKSHOT_KCCONTAINER_THREAD
, thread_uniqueid
));
2123 /* thread snapshot can be large, including strings, avoid overflowing the stack. */
2124 kcdata_compression_window_open(stackshot_kcdata_p
);
2126 kcd_exit_on_error(kcdata_record_thread_snapshot(stackshot_kcdata_p
, thread
, task
, ctx
->trace_flags
, have_pmap
, thread_on_core
));
2128 kcd_exit_on_error(kcdata_compression_window_close(stackshot_kcdata_p
));
2130 /* mark end of thread snapshot data */
2131 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_END
,
2132 STACKSHOT_KCCONTAINER_THREAD
, thread_uniqueid
));
2134 case tc_delta_snapshot
:
2135 kcd_exit_on_error(kcdata_record_thread_delta_snapshot(&delta_snapshots
[current_delta_snapshot_index
++], thread
, thread_on_core
));
2140 * We want to report owner information regardless of whether a thread
2141 * has changed since the last delta, whether it's a normal stackshot,
2142 * or whether it's nonrunnable
2144 if (save_owner_info
) {
2145 if (stackshot_thread_has_valid_waitinfo(thread
)) {
2146 num_waitinfo_threads
++;
2149 if (stackshot_thread_has_valid_turnstileinfo(thread
)) {
2150 num_turnstileinfo_threads
++;
2154 #if STACKSHOT_COLLECTS_LATENCY_INFO
2155 latency_info
.task_thread_count_loop_latency
= mach_absolute_time() - latency_info
.task_thread_count_loop_latency
;
2156 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2159 thread_waitinfo_t
*thread_waitinfo
= NULL
;
2160 thread_turnstileinfo_t
*thread_turnstileinfo
= NULL
;
2161 int current_waitinfo_index
= 0;
2162 int current_turnstileinfo_index
= 0;
2163 /* allocate space for the wait and turnstil info */
2164 if (num_waitinfo_threads
> 0 || num_turnstileinfo_threads
> 0) {
2165 /* thread waitinfo and turnstileinfo can be quite large, avoid overflowing the stack */
2166 kcdata_compression_window_open(stackshot_kcdata_p
);
2168 if (num_waitinfo_threads
> 0) {
2169 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_WAITINFO
,
2170 sizeof(thread_waitinfo_t
), num_waitinfo_threads
, &out_addr
));
2171 thread_waitinfo
= (thread_waitinfo_t
*)out_addr
;
2174 if (num_turnstileinfo_threads
> 0) {
2175 /* get space for the turnstile info */
2176 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_TURNSTILEINFO
,
2177 sizeof(thread_turnstileinfo_t
), num_turnstileinfo_threads
, &out_addr
));
2178 thread_turnstileinfo
= (thread_turnstileinfo_t
*)out_addr
;
2182 #if STACKSHOT_COLLECTS_LATENCY_INFO
2183 latency_info
.misc_latency
= mach_absolute_time() - latency_info
.misc_latency
;
2184 latency_info
.task_thread_data_loop_latency
= mach_absolute_time();
2185 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2187 /* Iterate over the task's threads to save the wait and turnstile info */
2188 queue_iterate(&task
->threads
, thread
, thread_t
, task_threads
)
2190 uint64_t thread_uniqueid
;
2192 if (active_kthreads_only_p
&& thread
->kernel_stack
== 0) {
2196 thread_uniqueid
= thread_tid(thread
);
2198 /* If we want owner info, we should capture it regardless of its classification */
2199 if (save_owner_info
) {
2200 if (stackshot_thread_has_valid_waitinfo(thread
)) {
2201 stackshot_thread_wait_owner_info(
2203 &thread_waitinfo
[current_waitinfo_index
++]);
2206 if (stackshot_thread_has_valid_turnstileinfo(thread
)) {
2207 stackshot_thread_turnstileinfo(
2209 &thread_turnstileinfo
[current_turnstileinfo_index
++]);
2214 #if STACKSHOT_COLLECTS_LATENCY_INFO
2215 latency_info
.task_thread_data_loop_latency
= mach_absolute_time() - latency_info
.task_thread_data_loop_latency
;
2216 latency_info
.misc2_latency
= mach_absolute_time();
2217 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2219 #if DEBUG || DEVELOPMENT
2220 if (current_delta_snapshot_index
!= num_delta_thread_snapshots
) {
2221 panic("delta thread snapshot count mismatch while capturing snapshots for task %p. expected %d, found %d", task
,
2222 num_delta_thread_snapshots
, current_delta_snapshot_index
);
2224 if (current_waitinfo_index
!= num_waitinfo_threads
) {
2225 panic("thread wait info count mismatch while capturing snapshots for task %p. expected %d, found %d", task
,
2226 num_waitinfo_threads
, current_waitinfo_index
);
2230 if (num_waitinfo_threads
> 0 || num_turnstileinfo_threads
> 0) {
2231 kcd_exit_on_error(kcdata_compression_window_close(stackshot_kcdata_p
));
2234 #if IMPORTANCE_INHERITANCE
2235 if (save_donating_pids_p
) {
2237 ((((mach_vm_address_t
)kcd_end_address(stackshot_kcdata_p
) + (TASK_IMP_WALK_LIMIT
* sizeof(int32_t))) <
2238 (mach_vm_address_t
)kcd_max_address(stackshot_kcdata_p
))
2240 : KERN_RESOURCE_SHORTAGE
));
2241 saved_count
= task_importance_list_pids(task
, TASK_IMP_LIST_DONATING_PIDS
,
2242 (void *)kcd_end_address(stackshot_kcdata_p
), TASK_IMP_WALK_LIMIT
);
2243 if (saved_count
> 0) {
2244 /* Variable size array - better not have it on the stack. */
2245 kcdata_compression_window_open(stackshot_kcdata_p
);
2246 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_DONATING_PIDS
,
2247 sizeof(int32_t), saved_count
, &out_addr
));
2248 kcd_exit_on_error(kcdata_compression_window_close(stackshot_kcdata_p
));
2253 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2254 if (!panic_stackshot
) {
2255 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, (mt_cur_cpu_cycles() - task_begin_cpu_cycle_count
),
2256 "task_cpu_cycle_count"));
2260 #if STACKSHOT_COLLECTS_LATENCY_INFO
2261 latency_info
.misc2_latency
= mach_absolute_time() - latency_info
.misc2_latency
;
2262 if (collect_latency_info
) {
2263 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_LATENCY_INFO_TASK
, sizeof(latency_info
), &latency_info
));
2265 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2267 /* mark end of task snapshot data */
2268 kcd_exit_on_error(kcdata_add_container_marker(stackshot_kcdata_p
, KCDATA_TYPE_CONTAINER_END
, STACKSHOT_KCCONTAINER_TASK
,
2278 static kern_return_t
2279 kdp_stackshot_kcdata_format(int pid
, uint64_t trace_flags
, uint32_t * pBytesTraced
, uint32_t * pBytesUncompressed
)
2281 kern_return_t error
= KERN_SUCCESS
;
2282 mach_vm_address_t out_addr
= 0;
2283 uint64_t abs_time
= 0, abs_time_end
= 0;
2284 uint64_t system_state_flags
= 0;
2285 task_t task
= TASK_NULL
;
2286 mach_timebase_info_data_t timebase
= {0, 0};
2287 uint32_t length_to_copy
= 0, tmp32
= 0;
2288 abs_time
= mach_absolute_time();
2289 uint64_t last_task_start_time
= 0;
2291 #if STACKSHOT_COLLECTS_LATENCY_INFO
2292 struct stackshot_latency_collection latency_info
;
2295 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2296 uint64_t stackshot_begin_cpu_cycle_count
= 0;
2298 if (!panic_stackshot
) {
2299 stackshot_begin_cpu_cycle_count
= mt_cur_cpu_cycles();
2303 #if STACKSHOT_COLLECTS_LATENCY_INFO
2304 collect_latency_info
= trace_flags
& STACKSHOT_DISABLE_LATENCY_INFO
? false : true;
2307 /* process the flags */
2308 boolean_t collect_delta_stackshot
= ((trace_flags
& STACKSHOT_COLLECT_DELTA_SNAPSHOT
) != 0);
2309 boolean_t use_fault_path
= ((trace_flags
& (STACKSHOT_ENABLE_UUID_FAULTING
| STACKSHOT_ENABLE_BT_FAULTING
)) != 0);
2310 stack_enable_faulting
= (trace_flags
& (STACKSHOT_ENABLE_BT_FAULTING
));
2312 /* Currently we only support returning explicit KEXT load info on fileset kernels */
2313 kc_format_t primary_kc_type
= KCFormatUnknown
;
2314 if (PE_get_primary_kc_format(&primary_kc_type
) && (primary_kc_type
!= KCFormatFileset
)) {
2315 trace_flags
&= ~(STACKSHOT_SAVE_KEXT_LOADINFO
);
2318 struct stackshot_context ctx
= {};
2319 ctx
.trace_flags
= trace_flags
;
2322 if (use_fault_path
) {
2323 fault_stats
.sfs_pages_faulted_in
= 0;
2324 fault_stats
.sfs_time_spent_faulting
= 0;
2325 fault_stats
.sfs_stopped_faulting
= (uint8_t) FALSE
;
2328 if (sizeof(void *) == 8) {
2329 system_state_flags
|= kKernel64_p
;
2332 if (stackshot_kcdata_p
== NULL
|| pBytesTraced
== NULL
) {
2333 error
= KERN_INVALID_ARGUMENT
;
2337 /* setup mach_absolute_time and timebase info -- copy out in some cases and needed to convert since_timestamp to seconds for proc start time */
2338 clock_timebase_info(&timebase
);
2340 /* begin saving data into the buffer */
2342 if (pBytesUncompressed
) {
2343 *pBytesUncompressed
= 0;
2345 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, trace_flags
, "stackshot_in_flags"));
2346 kcd_exit_on_error(kcdata_add_uint32_with_description(stackshot_kcdata_p
, (uint32_t)pid
, "stackshot_in_pid"));
2347 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, system_state_flags
, "system_state_flags"));
2348 if (trace_flags
& STACKSHOT_PAGE_TABLES
) {
2349 kcd_exit_on_error(kcdata_add_uint32_with_description(stackshot_kcdata_p
, stack_snapshot_pagetable_mask
, "stackshot_pagetable_mask"));
2352 #if STACKSHOT_COLLECTS_LATENCY_INFO
2353 latency_info
.setup_latency
= mach_absolute_time();
2354 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2357 tmp32
= memorystatus_get_pressure_status_kdp();
2358 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_JETSAM_LEVEL
, sizeof(uint32_t), &tmp32
));
2361 if (!collect_delta_stackshot
) {
2362 tmp32
= THREAD_POLICY_INTERNAL_STRUCT_VERSION
;
2363 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_POLICY_VERSION
, sizeof(uint32_t), &tmp32
));
2366 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_KERN_PAGE_SIZE
, sizeof(uint32_t), &tmp32
));
2368 /* save boot-args and osversion string */
2369 length_to_copy
= MIN((uint32_t)(strlen(version
) + 1), OSVERSIZE
);
2370 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_OSVERSION
, length_to_copy
, (const void *)version
));
2373 length_to_copy
= MIN((uint32_t)(strlen(PE_boot_args()) + 1), BOOT_LINE_LENGTH
);
2374 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_BOOTARGS
, length_to_copy
, PE_boot_args()));
2376 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, KCDATA_TYPE_TIMEBASE
, sizeof(timebase
), &timebase
));
2378 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_DELTA_SINCE_TIMESTAMP
, sizeof(uint64_t), &stack_snapshot_delta_since_timestamp
));
2381 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, KCDATA_TYPE_MACH_ABSOLUTE_TIME
, sizeof(uint64_t), &abs_time
));
2383 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, KCDATA_TYPE_USECS_SINCE_EPOCH
, sizeof(uint64_t), &stackshot_microsecs
));
2385 /* record system level shared cache load info (if available) */
2386 if (!collect_delta_stackshot
&& init_task_shared_region
&&
2387 ml_validate_nofault((vm_offset_t
)init_task_shared_region
, sizeof(struct vm_shared_region
))) {
2388 struct dyld_uuid_info_64_v2 sys_shared_cache_info
= {0};
2390 stackshot_memcpy(sys_shared_cache_info
.imageUUID
, &init_task_shared_region
->sr_uuid
, sizeof(init_task_shared_region
->sr_uuid
));
2391 sys_shared_cache_info
.imageLoadAddress
=
2392 init_task_shared_region
->sr_slide
;
2393 sys_shared_cache_info
.imageSlidBaseAddress
=
2394 init_task_shared_region
->sr_slide
+ init_task_shared_region
->sr_base_address
;
2396 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO
,
2397 sizeof(struct dyld_uuid_info_64_v2
), &sys_shared_cache_info
));
2399 if (trace_flags
& STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT
) {
2401 * Include a map of the system shared cache layout if it has been populated
2402 * (which is only when the system is using a custom shared cache).
2404 if (init_task_shared_region
->sr_images
&& ml_validate_nofault((vm_offset_t
)init_task_shared_region
->sr_images
,
2405 (init_task_shared_region
->sr_images_count
* sizeof(struct dyld_uuid_info_64
)))) {
2406 assert(init_task_shared_region
->sr_images_count
!= 0);
2407 kcd_exit_on_error(kcdata_push_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT
, sizeof(struct dyld_uuid_info_64
), init_task_shared_region
->sr_images_count
, init_task_shared_region
->sr_images
));
2412 /* Add requested information first */
2413 if (trace_flags
& STACKSHOT_GET_GLOBAL_MEM_STATS
) {
2414 struct mem_and_io_snapshot mais
= {0};
2415 kdp_mem_and_io_snapshot(&mais
);
2416 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_GLOBAL_MEM_STATS
, sizeof(mais
), &mais
));
2419 #if CONFIG_THREAD_GROUPS
2420 struct thread_group_snapshot_v2
*thread_groups
= NULL
;
2421 int num_thread_groups
= 0;
2423 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2424 uint64_t thread_group_begin_cpu_cycle_count
= 0;
2426 if (!panic_stackshot
&& (trace_flags
& STACKSHOT_THREAD_GROUP
)) {
2427 thread_group_begin_cpu_cycle_count
= mt_cur_cpu_cycles();
2432 /* Iterate over thread group names */
2433 if (trace_flags
& STACKSHOT_THREAD_GROUP
) {
2434 /* Variable size array - better not have it on the stack. */
2435 kcdata_compression_window_open(stackshot_kcdata_p
);
2437 if (thread_group_iterate_stackshot(stackshot_thread_group_count
, &num_thread_groups
) != KERN_SUCCESS
) {
2438 trace_flags
&= ~(STACKSHOT_THREAD_GROUP
);
2441 if (num_thread_groups
> 0) {
2442 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_THREAD_GROUP_SNAPSHOT
, sizeof(struct thread_group_snapshot_v2
), num_thread_groups
, &out_addr
));
2443 thread_groups
= (struct thread_group_snapshot_v2
*)out_addr
;
2446 if (thread_group_iterate_stackshot(stackshot_thread_group_snapshot
, thread_groups
) != KERN_SUCCESS
) {
2447 error
= KERN_FAILURE
;
2451 kcd_exit_on_error(kcdata_compression_window_close(stackshot_kcdata_p
));
2454 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2455 if (!panic_stackshot
&& (thread_group_begin_cpu_cycle_count
!= 0)) {
2456 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, (mt_cur_cpu_cycles() - thread_group_begin_cpu_cycle_count
),
2457 "thread_groups_cpu_cycle_count"));
2461 trace_flags
&= ~(STACKSHOT_THREAD_GROUP
);
2462 #endif /* CONFIG_THREAD_GROUPS */
2465 #if STACKSHOT_COLLECTS_LATENCY_INFO
2466 latency_info
.setup_latency
= mach_absolute_time() - latency_info
.setup_latency
;
2467 latency_info
.total_task_iteration_latency
= mach_absolute_time();
2468 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2470 /* Iterate over tasks */
2471 queue_iterate(&tasks
, task
, task_t
, tasks
)
2473 if (collect_delta_stackshot
) {
2475 proc_starttime_kdp(task
->bsd_info
, NULL
, NULL
, &abstime
);
2477 if (abstime
> last_task_start_time
) {
2478 last_task_start_time
= abstime
;
2482 error
= kdp_stackshot_record_task(&ctx
, task
);
2489 #if STACKSHOT_COLLECTS_LATENCY_INFO
2490 latency_info
.total_task_iteration_latency
= mach_absolute_time() - latency_info
.total_task_iteration_latency
;
2491 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2493 #if CONFIG_COALITIONS
2494 /* Don't collect jetsam coalition data in delta stakshots - these don't change */
2495 if (!collect_delta_stackshot
|| (last_task_start_time
> stack_snapshot_delta_since_timestamp
)) {
2496 int num_coalitions
= 0;
2497 struct jetsam_coalition_snapshot
*coalitions
= NULL
;
2499 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2500 uint64_t coalition_begin_cpu_cycle_count
= 0;
2502 if (!panic_stackshot
&& (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
)) {
2503 coalition_begin_cpu_cycle_count
= mt_cur_cpu_cycles();
2507 /* Iterate over coalitions */
2508 if (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) {
2509 if (coalition_iterate_stackshot(stackshot_coalition_jetsam_count
, &num_coalitions
, COALITION_TYPE_JETSAM
) != KERN_SUCCESS
) {
2510 trace_flags
&= ~(STACKSHOT_SAVE_JETSAM_COALITIONS
);
2513 if (trace_flags
& STACKSHOT_SAVE_JETSAM_COALITIONS
) {
2514 if (num_coalitions
> 0) {
2515 /* Variable size array - better not have it on the stack. */
2516 kcdata_compression_window_open(stackshot_kcdata_p
);
2517 kcd_exit_on_error(kcdata_get_memory_addr_for_array(stackshot_kcdata_p
, STACKSHOT_KCTYPE_JETSAM_COALITION_SNAPSHOT
, sizeof(struct jetsam_coalition_snapshot
), num_coalitions
, &out_addr
));
2518 coalitions
= (struct jetsam_coalition_snapshot
*)out_addr
;
2520 if (coalition_iterate_stackshot(stackshot_coalition_jetsam_snapshot
, coalitions
, COALITION_TYPE_JETSAM
) != KERN_SUCCESS
) {
2521 error
= KERN_FAILURE
;
2525 kcd_exit_on_error(kcdata_compression_window_close(stackshot_kcdata_p
));
2528 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2529 if (!panic_stackshot
&& (coalition_begin_cpu_cycle_count
!= 0)) {
2530 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, (mt_cur_cpu_cycles() - coalition_begin_cpu_cycle_count
),
2531 "coalitions_cpu_cycle_count"));
2536 trace_flags
&= ~(STACKSHOT_SAVE_JETSAM_COALITIONS
);
2537 #endif /* CONFIG_COALITIONS */
2539 #if STACKSHOT_COLLECTS_LATENCY_INFO
2540 latency_info
.total_terminated_task_iteration_latency
= mach_absolute_time();
2541 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2544 * Iterate over the tasks in the terminated tasks list. We only inspect
2545 * tasks that have a valid bsd_info pointer where P_LPEXIT is NOT set.
2546 * We're only interested in tasks that have remaining threads (which
2547 * could be involved in a deadlock, etc), and the last thread that tears
2548 * itself down during exit sets P_LPEXIT during proc_exit().
2550 queue_iterate(&terminated_tasks
, task
, task_t
, tasks
)
2552 if (task
->bsd_info
&& !proc_in_teardown(task
->bsd_info
)) {
2553 error
= kdp_stackshot_record_task(&ctx
, task
);
2561 #if STACKSHOT_COLLECTS_LATENCY_INFO
2562 latency_info
.total_terminated_task_iteration_latency
= mach_absolute_time() - latency_info
.total_terminated_task_iteration_latency
;
2563 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2565 if (use_fault_path
) {
2566 kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_STACKSHOT_FAULT_STATS
,
2567 sizeof(struct stackshot_fault_stats
), &fault_stats
);
2570 #if STACKSHOT_COLLECTS_LATENCY_INFO
2571 if (collect_latency_info
) {
2572 latency_info
.latency_version
= 1;
2573 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_LATENCY_INFO
, sizeof(latency_info
), &latency_info
));
2575 #endif /* STACKSHOT_COLLECTS_LATENCY_INFO */
2577 /* update timestamp of the stackshot */
2578 abs_time_end
= mach_absolute_time();
2579 #if DEVELOPMENT || DEBUG
2580 struct stackshot_duration stackshot_duration
;
2581 stackshot_duration
.stackshot_duration
= (abs_time_end
- abs_time
);
2582 stackshot_duration
.stackshot_duration_outer
= 0;
2584 if ((trace_flags
& STACKSHOT_DO_COMPRESS
) == 0) {
2585 kcd_exit_on_error(kcdata_get_memory_addr(stackshot_kcdata_p
, STACKSHOT_KCTYPE_STACKSHOT_DURATION
,
2586 sizeof(struct stackshot_duration
), &out_addr
));
2587 struct stackshot_duration
*duration_p
= (void *) out_addr
;
2588 stackshot_memcpy(duration_p
, &stackshot_duration
, sizeof(*duration_p
));
2589 stackshot_duration_outer
= (unaligned_u64
*)&duration_p
->stackshot_duration_outer
;
2591 kcd_exit_on_error(kcdata_push_data(stackshot_kcdata_p
, STACKSHOT_KCTYPE_STACKSHOT_DURATION
, sizeof(stackshot_duration
), &stackshot_duration
));
2592 stackshot_duration_outer
= NULL
;
2596 #if INTERRUPT_MASKED_DEBUG && MONOTONIC
2597 if (!panic_stackshot
) {
2598 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, (mt_cur_cpu_cycles() - stackshot_begin_cpu_cycle_count
),
2599 "stackshot_total_cpu_cycle_cnt"));
2603 kcd_finalize_compression(stackshot_kcdata_p
);
2604 kcd_exit_on_error(kcdata_add_uint64_with_description(stackshot_kcdata_p
, trace_flags
, "stackshot_out_flags"));
2606 kcd_exit_on_error(kcdata_write_buffer_end(stackshot_kcdata_p
));
2608 /* === END of populating stackshot data === */
2610 *pBytesTraced
= (uint32_t) kcdata_memory_get_used_bytes(stackshot_kcdata_p
);
2611 *pBytesUncompressed
= (uint32_t) kcdata_memory_get_uncompressed_bytes(stackshot_kcdata_p
);
2615 #if INTERRUPT_MASKED_DEBUG
2616 if (trace_flags
& STACKSHOT_DO_COMPRESS
) {
2617 ml_spin_debug_clear_self();
2619 #if defined(STACKSHOT_INTERRUPTS_MASKED_CHECK_DISABLED)
2620 ml_spin_debug_clear_self();
2623 if (!panic_stackshot
&& interrupt_masked_debug
) {
2625 * Try to catch instances where stackshot takes too long BEFORE returning from
2628 ml_check_stackshot_interrupt_disabled_duration(current_thread());
2632 stack_enable_faulting
= FALSE
;
2638 proc_was_throttled_from_task(task_t task
)
2640 uint64_t was_throttled
= 0;
2642 if (task
->bsd_info
) {
2643 was_throttled
= proc_was_throttled(task
->bsd_info
);
2646 return was_throttled
;
2650 proc_did_throttle_from_task(task_t task
)
2652 uint64_t did_throttle
= 0;
2654 if (task
->bsd_info
) {
2655 did_throttle
= proc_did_throttle(task
->bsd_info
);
2658 return did_throttle
;
2662 kdp_mem_and_io_snapshot(struct mem_and_io_snapshot
*memio_snap
)
2664 unsigned int pages_reclaimed
;
2665 unsigned int pages_wanted
;
2668 uint64_t compressions
= 0;
2669 uint64_t decompressions
= 0;
2671 percpu_foreach(stat
, vm_stat
) {
2672 compressions
+= stat
->compressions
;
2673 decompressions
+= stat
->decompressions
;
2676 memio_snap
->snapshot_magic
= STACKSHOT_MEM_AND_IO_SNAPSHOT_MAGIC
;
2677 memio_snap
->free_pages
= vm_page_free_count
;
2678 memio_snap
->active_pages
= vm_page_active_count
;
2679 memio_snap
->inactive_pages
= vm_page_inactive_count
;
2680 memio_snap
->purgeable_pages
= vm_page_purgeable_count
;
2681 memio_snap
->wired_pages
= vm_page_wire_count
;
2682 memio_snap
->speculative_pages
= vm_page_speculative_count
;
2683 memio_snap
->throttled_pages
= vm_page_throttled_count
;
2684 memio_snap
->busy_buffer_count
= count_busy_buffers();
2685 memio_snap
->filebacked_pages
= vm_page_pageable_external_count
;
2686 memio_snap
->compressions
= (uint32_t)compressions
;
2687 memio_snap
->decompressions
= (uint32_t)decompressions
;
2688 memio_snap
->compressor_size
= VM_PAGE_COMPRESSOR_COUNT
;
2689 kErr
= mach_vm_pressure_monitor(FALSE
, VM_PRESSURE_TIME_WINDOW
, &pages_reclaimed
, &pages_wanted
);
2692 memio_snap
->pages_wanted
= (uint32_t)pages_wanted
;
2693 memio_snap
->pages_reclaimed
= (uint32_t)pages_reclaimed
;
2694 memio_snap
->pages_wanted_reclaimed_valid
= 1;
2696 memio_snap
->pages_wanted
= 0;
2697 memio_snap
->pages_reclaimed
= 0;
2698 memio_snap
->pages_wanted_reclaimed_valid
= 0;
2703 stackshot_memcpy(void *dst
, const void *src
, size_t len
)
2705 #if defined(__arm__) || defined(__arm64__)
2706 if (panic_stackshot
) {
2707 uint8_t *dest_bytes
= (uint8_t *)dst
;
2708 const uint8_t *src_bytes
= (const uint8_t *)src
;
2709 for (size_t i
= 0; i
< len
; i
++) {
2710 dest_bytes
[i
] = src_bytes
[i
];
2714 memcpy(dst
, src
, len
);
2718 stackshot_strlcpy(char *dst
, const char *src
, size_t maxlen
)
2720 const size_t srclen
= strlen(src
);
2722 if (srclen
< maxlen
) {
2723 stackshot_memcpy(dst
, src
, srclen
+ 1);
2724 } else if (maxlen
!= 0) {
2725 stackshot_memcpy(dst
, src
, maxlen
- 1);
2726 dst
[maxlen
- 1] = '\0';
2733 kdp_extract_page_mask_and_size(vm_map_t map
, int *effective_page_mask
, int *effective_page_size
)
2735 if (VM_MAP_PAGE_SHIFT(map
) < PAGE_SHIFT
) {
2736 *effective_page_mask
= VM_MAP_PAGE_MASK(map
);
2737 *effective_page_size
= VM_MAP_PAGE_SIZE(map
);
2739 *effective_page_mask
= PAGE_MASK
;
2740 *effective_page_size
= PAGE_SIZE
;
2745 * Returns the physical address of the specified map:target address,
2746 * using the kdp fault path if requested and the page is not resident.
2749 kdp_find_phys(vm_map_t map
, vm_offset_t target_addr
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2751 vm_offset_t cur_phys_addr
;
2752 unsigned cur_wimg_bits
;
2753 uint64_t fault_start_time
= 0;
2754 int effective_page_mask
, effective_page_size
;
2756 if (map
== VM_MAP_NULL
) {
2760 kdp_extract_page_mask_and_size(map
, &effective_page_mask
, &effective_page_size
);
2762 cur_phys_addr
= kdp_vtophys(map
->pmap
, target_addr
);
2763 if (!pmap_valid_page((ppnum_t
) atop(cur_phys_addr
))) {
2764 if (!try_fault
|| fault_stats
.sfs_stopped_faulting
) {
2765 if (kdp_fault_results
) {
2766 *kdp_fault_results
|= KDP_FAULT_RESULT_PAGED_OUT
;
2773 * The pmap doesn't have a valid page so we start at the top level
2774 * vm map and try a lightweight fault. Update fault path usage stats.
2776 fault_start_time
= mach_absolute_time();
2777 cur_phys_addr
= kdp_lightweight_fault(map
, (target_addr
& ~effective_page_mask
));
2778 fault_stats
.sfs_time_spent_faulting
+= (mach_absolute_time() - fault_start_time
);
2780 if ((fault_stats
.sfs_time_spent_faulting
>= fault_stats
.sfs_system_max_fault_time
) && !panic_stackshot
) {
2781 fault_stats
.sfs_stopped_faulting
= (uint8_t) TRUE
;
2784 cur_phys_addr
+= (target_addr
& effective_page_mask
);
2786 if (!pmap_valid_page((ppnum_t
) atop(cur_phys_addr
))) {
2787 if (kdp_fault_results
) {
2788 *kdp_fault_results
|= (KDP_FAULT_RESULT_TRIED_FAULT
| KDP_FAULT_RESULT_PAGED_OUT
);
2794 if (kdp_fault_results
) {
2795 *kdp_fault_results
|= KDP_FAULT_RESULT_FAULTED_IN
;
2798 fault_stats
.sfs_pages_faulted_in
++;
2801 * This check is done in kdp_lightweight_fault for the fault path.
2803 cur_wimg_bits
= pmap_cache_attributes((ppnum_t
) atop(cur_phys_addr
));
2805 if ((cur_wimg_bits
& VM_WIMG_MASK
) != VM_WIMG_DEFAULT
) {
2810 return cur_phys_addr
;
2815 task_t task
, uint64_t addr
, uint64_t *result
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2817 if (task_has_64Bit_addr(task
)) {
2818 return kdp_copyin(task
->map
, addr
, result
, sizeof(uint64_t), try_fault
, kdp_fault_results
);
2821 boolean_t r
= kdp_copyin(task
->map
, addr
, &buf
, sizeof(uint32_t), try_fault
, kdp_fault_results
);
2828 kdp_copyin_string_slowpath(
2829 task_t task
, uint64_t addr
, char *buf
, int buf_sz
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2832 uint64_t validated
= 0, valid_from
;
2833 uint64_t phys_src
, phys_dest
;
2834 int effective_page_mask
, effective_page_size
;
2835 vm_map_t map
= task
->map
;
2837 kdp_extract_page_mask_and_size(map
, &effective_page_mask
, &effective_page_size
);
2839 for (i
= 0; i
< buf_sz
; i
++) {
2840 if (validated
== 0) {
2842 phys_src
= kdp_find_phys(map
, addr
+ i
, try_fault
, kdp_fault_results
);
2843 phys_dest
= kvtophys((vm_offset_t
)&buf
[i
]);
2844 uint64_t src_rem
= effective_page_size
- (phys_src
& effective_page_mask
);
2845 uint64_t dst_rem
= PAGE_SIZE
- (phys_dest
& PAGE_MASK
);
2846 if (phys_src
&& phys_dest
) {
2847 validated
= MIN(src_rem
, dst_rem
);
2849 bcopy_phys(phys_src
, phys_dest
, 1);
2858 bcopy_phys(phys_src
+ (i
- valid_from
), phys_dest
+ (i
- valid_from
), 1);
2862 if (buf
[i
] == '\0') {
2867 /* ran out of space */
2873 task_t task
, uint64_t addr
, char *buf
, int buf_sz
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2875 /* try to opportunistically copyin 32 bytes, most strings should fit */
2879 bzero(optbuffer
, sizeof(optbuffer
));
2880 res
= kdp_copyin(task
->map
, addr
, optbuffer
, sizeof(optbuffer
), try_fault
, kdp_fault_results
);
2881 if (res
== FALSE
|| strnlen(optbuffer
, sizeof(optbuffer
)) == sizeof(optbuffer
)) {
2882 /* try the slowpath */
2883 return kdp_copyin_string_slowpath(task
, addr
, buf
, buf_sz
, try_fault
, kdp_fault_results
);
2887 return (int) strlcpy(buf
, optbuffer
, buf_sz
) + 1;
2891 kdp_copyin(vm_map_t map
, uint64_t uaddr
, void *dest
, size_t size
, boolean_t try_fault
, uint32_t *kdp_fault_results
)
2894 char *kvaddr
= dest
;
2895 int effective_page_mask
, effective_page_size
;
2897 kdp_extract_page_mask_and_size(map
, &effective_page_mask
, &effective_page_size
);
2899 #if defined(__arm__) || defined(__arm64__)
2900 /* Identify if destination buffer is in panic storage area */
2901 if (panic_stackshot
&& ((vm_offset_t
)dest
>= gPanicBase
) && ((vm_offset_t
)dest
< (gPanicBase
+ gPanicSize
))) {
2902 if (((vm_offset_t
)dest
+ size
) > (gPanicBase
+ gPanicSize
)) {
2909 uint64_t phys_src
= kdp_find_phys(map
, uaddr
, try_fault
, kdp_fault_results
);
2910 uint64_t phys_dest
= kvtophys((vm_offset_t
)kvaddr
);
2911 uint64_t src_rem
= effective_page_size
- (phys_src
& effective_page_mask
);
2912 uint64_t dst_rem
= PAGE_SIZE
- (phys_dest
& PAGE_MASK
);
2913 size_t cur_size
= (uint32_t) MIN(src_rem
, dst_rem
);
2914 cur_size
= MIN(cur_size
, rem
);
2916 if (phys_src
&& phys_dest
) {
2917 #if defined(__arm__) || defined(__arm64__)
2919 * On arm devices the panic buffer is mapped as device memory and doesn't allow
2920 * unaligned accesses. To prevent these, we copy over bytes individually here.
2922 if (panic_stackshot
) {
2923 stackshot_memcpy(kvaddr
, (const void *)phystokv(phys_src
), cur_size
);
2925 #endif /* defined(__arm__) || defined(__arm64__) */
2926 bcopy_phys(phys_src
, phys_dest
, cur_size
);
2940 do_stackshot(void *context
)
2942 #pragma unused(context)
2945 stack_snapshot_ret
= kdp_stackshot_kcdata_format(stack_snapshot_pid
,
2946 stack_snapshot_flags
,
2947 &stack_snapshot_bytes_traced
,
2948 &stack_snapshot_bytes_uncompressed
);
2950 if (stack_snapshot_ret
== KERN_SUCCESS
&& stack_snapshot_flags
& STACKSHOT_DO_COMPRESS
) {
2951 kcdata_finish_compression(stackshot_kcdata_p
);
2955 return stack_snapshot_ret
;
2959 * A fantastical routine that tries to be fast about returning
2960 * translations. Caches the last page we found a translation
2961 * for, so that we can be quick about multiple queries to the
2962 * same page. It turns out this is exactly the workflow
2963 * machine_trace_thread and its relatives tend to throw at us.
2965 * Please zero the nasty global this uses after a bulk lookup;
2966 * this isn't safe across a switch of the map or changes
2969 * This also means that if zero is a valid KVA, we are
2970 * screwed. Sucks to be us. Fortunately, this should never
2974 machine_trace_thread_get_kva(vm_offset_t cur_target_addr
, vm_map_t map
, uint32_t *thread_trace_flags
)
2976 vm_offset_t cur_target_page
;
2977 vm_offset_t cur_phys_addr
;
2978 vm_offset_t kern_virt_target_addr
;
2979 uint32_t kdp_fault_results
= 0;
2981 cur_target_page
= atop(cur_target_addr
);
2983 if ((cur_target_page
!= prev_target_page
) || validate_next_addr
) {
2985 * Alright; it wasn't our previous page. So
2986 * we must validate that there is a page
2987 * table entry for this address under the
2988 * current pmap, and that it has default
2989 * cache attributes (otherwise it may not be
2990 * safe to access it).
2992 cur_phys_addr
= kdp_find_phys(map
, cur_target_addr
, stack_enable_faulting
, &kdp_fault_results
);
2993 if (thread_trace_flags
) {
2994 if (kdp_fault_results
& KDP_FAULT_RESULT_PAGED_OUT
) {
2995 *thread_trace_flags
|= kThreadTruncatedBT
;
2998 if (kdp_fault_results
& KDP_FAULT_RESULT_TRIED_FAULT
) {
2999 *thread_trace_flags
|= kThreadTriedFaultBT
;
3002 if (kdp_fault_results
& KDP_FAULT_RESULT_FAULTED_IN
) {
3003 *thread_trace_flags
|= kThreadFaultedBT
;
3007 if (cur_phys_addr
== 0) {
3010 kern_virt_target_addr
= phystokv(cur_phys_addr
);
3011 prev_target_page
= cur_target_page
;
3012 prev_target_kva
= (kern_virt_target_addr
& ~PAGE_MASK
);
3013 validate_next_addr
= FALSE
;
3015 /* We found a translation, so stash this page */
3016 kern_virt_target_addr
= prev_target_kva
+ (cur_target_addr
& PAGE_MASK
);
3020 kasan_notify_address(kern_virt_target_addr
, sizeof(uint64_t));
3022 return kern_virt_target_addr
;
3026 machine_trace_thread_clear_validation_cache(void)
3028 validate_next_addr
= TRUE
;
3032 stackshot_thread_is_idle_worker_unsafe(thread_t thread
)
3034 /* When the pthread kext puts a worker thread to sleep, it will
3035 * set kThreadWaitParkedWorkQueue in the block_hint of the thread
3036 * struct. See parkit() in kern/kern_support.c in libpthread.
3038 return (thread
->state
& TH_WAIT
) &&
3039 (thread
->block_hint
== kThreadWaitParkedWorkQueue
);
3042 #if CONFIG_COALITIONS
3044 stackshot_coalition_jetsam_count(void *arg
, int i
, coalition_t coal
)
3046 #pragma unused(i, coal)
3047 unsigned int *coalition_count
= (unsigned int*)arg
;
3048 (*coalition_count
)++;
3052 stackshot_coalition_jetsam_snapshot(void *arg
, int i
, coalition_t coal
)
3054 if (coalition_type(coal
) != COALITION_TYPE_JETSAM
) {
3058 struct jetsam_coalition_snapshot
*coalitions
= (struct jetsam_coalition_snapshot
*)arg
;
3059 struct jetsam_coalition_snapshot
*jcs
= &coalitions
[i
];
3060 task_t leader
= TASK_NULL
;
3061 jcs
->jcs_id
= coalition_id(coal
);
3063 jcs
->jcs_thread_group
= 0;
3065 if (coalition_term_requested(coal
)) {
3066 jcs
->jcs_flags
|= kCoalitionTermRequested
;
3068 if (coalition_is_terminated(coal
)) {
3069 jcs
->jcs_flags
|= kCoalitionTerminated
;
3071 if (coalition_is_reaped(coal
)) {
3072 jcs
->jcs_flags
|= kCoalitionReaped
;
3074 if (coalition_is_privileged(coal
)) {
3075 jcs
->jcs_flags
|= kCoalitionPrivileged
;
3078 #if CONFIG_THREAD_GROUPS
3079 struct thread_group
*thread_group
= kdp_coalition_get_thread_group(coal
);
3081 jcs
->jcs_thread_group
= thread_group_get_id(thread_group
);
3083 #endif /* CONFIG_THREAD_GROUPS */
3085 leader
= kdp_coalition_get_leader(coal
);
3087 jcs
->jcs_leader_task_uniqueid
= get_task_uniqueid(leader
);
3089 jcs
->jcs_leader_task_uniqueid
= 0;
3092 #endif /* CONFIG_COALITIONS */
3094 #if CONFIG_THREAD_GROUPS
3096 stackshot_thread_group_count(void *arg
, int i
, struct thread_group
*tg
)
3098 #pragma unused(i, tg)
3099 unsigned int *n
= (unsigned int*)arg
;
3104 stackshot_thread_group_snapshot(void *arg
, int i
, struct thread_group
*tg
)
3106 struct thread_group_snapshot_v2
*thread_groups
= (struct thread_group_snapshot_v2
*)arg
;
3107 struct thread_group_snapshot_v2
*tgs
= &thread_groups
[i
];
3108 uint64_t flags
= kdp_thread_group_get_flags(tg
);
3109 tgs
->tgs_id
= thread_group_get_id(tg
);
3110 stackshot_memcpy(tgs
->tgs_name
, thread_group_get_name(tg
), THREAD_GROUP_MAXNAME
);
3111 tgs
->tgs_flags
= ((flags
& THREAD_GROUP_FLAGS_EFFICIENT
) ? kThreadGroupEfficient
: 0) |
3112 ((flags
& THREAD_GROUP_FLAGS_UI_APP
) ? kThreadGroupUIApp
: 0);
3114 #endif /* CONFIG_THREAD_GROUPS */
3116 /* Determine if a thread has waitinfo that stackshot can provide */
3118 stackshot_thread_has_valid_waitinfo(thread_t thread
)
3120 if (!(thread
->state
& TH_WAIT
)) {
3124 switch (thread
->block_hint
) {
3125 // If set to None or is a parked work queue, ignore it
3126 case kThreadWaitParkedWorkQueue
:
3127 case kThreadWaitNone
:
3129 // There is a short window where the pthread kext removes a thread
3130 // from its ksyn wait queue before waking the thread up
3131 case kThreadWaitPThreadMutex
:
3132 case kThreadWaitPThreadRWLockRead
:
3133 case kThreadWaitPThreadRWLockWrite
:
3134 case kThreadWaitPThreadCondVar
:
3135 return kdp_pthread_get_thread_kwq(thread
) != NULL
;
3136 // All other cases are valid block hints if in a wait state
3142 /* Determine if a thread has turnstileinfo that stackshot can provide */
3144 stackshot_thread_has_valid_turnstileinfo(thread_t thread
)
3146 struct turnstile
*ts
= thread_get_waiting_turnstile(thread
);
3148 return stackshot_thread_has_valid_waitinfo(thread
) &&
3149 ts
!= TURNSTILE_NULL
;
3153 stackshot_thread_turnstileinfo(thread_t thread
, thread_turnstileinfo_t
*tsinfo
)
3155 struct turnstile
*ts
;
3157 /* acquire turnstile information and store it in the stackshot */
3158 ts
= thread_get_waiting_turnstile(thread
);
3159 tsinfo
->waiter
= thread_tid(thread
);
3160 kdp_turnstile_fill_tsinfo(ts
, tsinfo
);
3164 stackshot_thread_wait_owner_info(thread_t thread
, thread_waitinfo_t
*waitinfo
)
3166 waitinfo
->waiter
= thread_tid(thread
);
3167 waitinfo
->wait_type
= thread
->block_hint
;
3169 switch (waitinfo
->wait_type
) {
3170 case kThreadWaitKernelMutex
:
3171 kdp_lck_mtx_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3173 case kThreadWaitPortReceive
:
3174 kdp_mqueue_recv_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3176 case kThreadWaitPortSend
:
3177 kdp_mqueue_send_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3179 case kThreadWaitSemaphore
:
3180 kdp_sema_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3182 case kThreadWaitUserLock
:
3183 kdp_ulock_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3185 case kThreadWaitKernelRWLockRead
:
3186 case kThreadWaitKernelRWLockWrite
:
3187 case kThreadWaitKernelRWLockUpgrade
:
3188 kdp_rwlck_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3190 case kThreadWaitPThreadMutex
:
3191 case kThreadWaitPThreadRWLockRead
:
3192 case kThreadWaitPThreadRWLockWrite
:
3193 case kThreadWaitPThreadCondVar
:
3194 kdp_pthread_find_owner(thread
, waitinfo
);
3196 case kThreadWaitWorkloopSyncWait
:
3197 kdp_workloop_sync_wait_find_owner(thread
, thread
->wait_event
, waitinfo
);
3199 case kThreadWaitOnProcess
:
3200 kdp_wait4_find_process(thread
, thread
->wait_event
, waitinfo
);
3202 case kThreadWaitSleepWithInheritor
:
3203 kdp_sleep_with_inheritor_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3205 case kThreadWaitEventlink
:
3206 kdp_eventlink_find_owner(thread
->waitq
, thread
->wait_event
, waitinfo
);
3208 case kThreadWaitCompressor
:
3209 kdp_compressor_busy_find_owner(thread
->wait_event
, waitinfo
);
3212 waitinfo
->owner
= 0;
3213 waitinfo
->context
= 0;