xref: /xnu-11215/tests/stackshot_tests.m (revision 4f1223e8)
1#include <darwintest.h>
2#include <darwintest_utils.h>
3#include <darwintest_multiprocess.h>
4#include <kern/debug.h>
5#include <kern/kern_cdata.h>
6#include <kern/block_hint.h>
7#include <kdd.h>
8#include <libproc.h>
9#include <os/atomic_private.h>
10#include <mach-o/dyld.h>
11#include <mach-o/dyld_images.h>
12#include <mach-o/dyld_priv.h>
13#include <sys/syscall.h>
14#include <sys/stackshot.h>
15#include <uuid/uuid.h>
16#include <servers/bootstrap.h>
17#include <pthread/workqueue_private.h>
18#include <dispatch/private.h>
19#include <stdalign.h>
20#include <TargetConditionals.h>
21
22#import <zlib.h>
23#import <IOKit/IOKitLib.h>
24#import <IOKit/IOKitLibPrivate.h>
25#import <IOKit/IOKitKeysPrivate.h>
26#import "test_utils.h"
27
28
29
30T_GLOBAL_META(
31		T_META_NAMESPACE("xnu.stackshot"),
32		T_META_RADAR_COMPONENT_NAME("xnu"),
33		T_META_RADAR_COMPONENT_VERSION("stackshot"),
34		T_META_OWNER("jonathan_w_adams"),
35		T_META_CHECK_LEAKS(false),
36		T_META_ASROOT(true),
37		XNU_T_META_SOC_SPECIFIC
38		);
39
40static const char *current_process_name(void);
41static void verify_stackshot_sharedcache_layout(struct dyld_uuid_info_64 *uuids, uint32_t uuid_count);
42static void parse_stackshot(uint64_t stackshot_parsing_flags, void *ssbuf, size_t sslen, NSDictionary *extra);
43static void parse_thread_group_stackshot(void **sbuf, size_t sslen);
44static uint64_t stackshot_timestamp(void *ssbuf, size_t sslen);
45static void initialize_thread(void);
46
47static uint64_t global_flags = 0;
48
49#define DEFAULT_STACKSHOT_BUFFER_SIZE (1024 * 1024)
50#define MAX_STACKSHOT_BUFFER_SIZE     (6 * 1024 * 1024)
51
52#define SRP_SERVICE_NAME "com.apple.xnu.test.stackshot.special_reply_port"
53
54/* bit flags for parse_stackshot */
55#define PARSE_STACKSHOT_DELTA                0x01
56#define PARSE_STACKSHOT_ZOMBIE               0x02
57#define PARSE_STACKSHOT_SHAREDCACHE_LAYOUT   0x04
58#define PARSE_STACKSHOT_DISPATCH_QUEUE_LABEL 0x08
59#define PARSE_STACKSHOT_TURNSTILEINFO        0x10
60#define PARSE_STACKSHOT_POSTEXEC             0x20
61#define PARSE_STACKSHOT_WAITINFO_CSEG        0x40
62#define PARSE_STACKSHOT_WAITINFO_SRP         0x80
63#define PARSE_STACKSHOT_TRANSLATED           0x100
64#define PARSE_STACKSHOT_SHAREDCACHE_FLAGS    0x200
65#define PARSE_STACKSHOT_EXEC_INPROGRESS      0x400
66#define PARSE_STACKSHOT_TRANSITIONING        0x800
67#define PARSE_STACKSHOT_ASYNCSTACK           0x1000
68#define PARSE_STACKSHOT_COMPACTINFO          0x2000 /* TODO: rdar://88789261 */
69#define PARSE_STACKSHOT_DRIVERKIT            0x4000
70#define PARSE_STACKSHOT_THROTTLED_SP         0x8000
71#define PARSE_STACKSHOT_SUSPENDINFO          0x10000
72#define PARSE_STACKSHOT_TARGETPID            0x20000
73
74/* keys for 'extra' dictionary for parse_stackshot */
75static const NSString* zombie_child_pid_key = @"zombie_child_pid"; // -> @(pid), required for PARSE_STACKSHOT_ZOMBIE
76static const NSString* postexec_child_unique_pid_key = @"postexec_child_unique_pid";  // -> @(unique_pid), required for PARSE_STACKSHOT_POSTEXEC
77static const NSString* cseg_expected_threadid_key = @"cseg_expected_threadid"; // -> @(tid), required for PARSE_STACKSHOT_WAITINFO_CSEG
78static const NSString* srp_expected_threadid_key = @"srp_expected_threadid"; // -> @(tid), this or ..._pid required for PARSE_STACKSHOT_WAITINFO_SRP
79static const NSString* srp_expected_pid_key = @"srp_expected_pid"; // -> @(pid), this or ..._threadid required for PARSE_STACKSHOT_WAITINFO_SRP
80static const NSString* translated_child_pid_key = @"translated_child_pid"; // -> @(pid), required for PARSE_STACKSHOT_TRANSLATED
81static const NSString* sharedcache_child_pid_key = @"sharedcache_child_pid"; // @(pid), required for PARSE_STACKSHOT_SHAREDCACHE_FLAGS
82static const NSString* sharedcache_child_sameaddr_key = @"sharedcache_child_sameaddr"; // @(0 or 1), required for PARSE_STACKSHOT_SHAREDCACHE_FLAGS
83static const NSString* exec_inprogress_pid_key = @"exec_inprogress_pid";
84static const NSString* exec_inprogress_found_key = @"exec_inprogress_found";  // callback when inprogress is found
85static const NSString* transitioning_pid_key = @"transitioning_task_pid"; // -> @(pid), required for PARSE_STACKSHOT_TRANSITIONING
86static const NSString* asyncstack_expected_threadid_key = @"asyncstack_expected_threadid"; // -> @(tid), required for PARSE_STACKSHOT_ASYNCSTACK
87static const NSString* asyncstack_expected_stack_key = @"asyncstack_expected_stack"; // -> @[pc...]), expected PCs for asyncstack
88static const NSString* driverkit_found_key = @"driverkit_found_key"; // callback when driverkit process is found. argument is the process pid.
89static const NSString* sp_throttled_expected_ctxt_key = @"sp_throttled_expected_ctxt_key"; // -> @(ctxt), required for PARSE_STACKSHOT_THROTTLED_SP
90static const NSString* sp_throttled_expect_flag = @"sp_throttled_expect_flag"; // -> @(is_throttled), required for PARSE_STACKSHOT_THROTTLED_SP
91static const NSString* no_exclaves_key = @"no_exclaves";
92
93#define TEST_STACKSHOT_QUEUE_LABEL        "houston.we.had.a.problem"
94#define TEST_STACKSHOT_QUEUE_LABEL_LENGTH sizeof(TEST_STACKSHOT_QUEUE_LABEL)
95
96#define THROTTLED_SERVICE_NAME "com.apple.xnu.test.stackshot.throttled_service"
97
98static int64_t
99run_sysctl_test(const char *t, int64_t value)
100{
101	char name[1024];
102	int64_t result = 0;
103	size_t s = sizeof(value);
104	int rc;
105
106	snprintf(name, sizeof(name), "debug.test.%s", t);
107	rc = sysctlbyname(name, &result, &s, &value, s);
108	T_QUIET; T_ASSERT_POSIX_SUCCESS(rc, "sysctlbyname(%s)", name);
109	return result;
110}
111
112T_DECL(microstackshots, "test the microstackshot syscall", T_META_TAG_VM_PREFERRED)
113{
114	void *buf = NULL;
115	unsigned int size = DEFAULT_STACKSHOT_BUFFER_SIZE;
116
117	while (1) {
118		buf = malloc(size);
119		T_QUIET; T_ASSERT_NOTNULL(buf, "allocated stackshot buffer");
120
121#pragma clang diagnostic push
122#pragma clang diagnostic ignored "-Wdeprecated-declarations"
123		int len = syscall(SYS_microstackshot, buf, size,
124				(uint32_t) STACKSHOT_GET_MICROSTACKSHOT);
125#pragma clang diagnostic pop
126		if (len == ENOSYS) {
127			T_SKIP("microstackshot syscall failed, likely not compiled with CONFIG_TELEMETRY");
128		}
129		if (len == -1 && errno == ENOSPC) {
130			/* syscall failed because buffer wasn't large enough, try again */
131			free(buf);
132			buf = NULL;
133			size *= 2;
134			T_ASSERT_LE(size, (unsigned int)MAX_STACKSHOT_BUFFER_SIZE,
135					"growing stackshot buffer to sane size");
136			continue;
137		}
138		T_ASSERT_POSIX_SUCCESS(len, "called microstackshot syscall");
139		break;
140    }
141
142	T_EXPECT_EQ(*(uint32_t *)buf,
143			(uint32_t)STACKSHOT_MICRO_SNAPSHOT_MAGIC,
144			"magic value for microstackshot matches");
145
146	free(buf);
147}
148
149struct scenario {
150	const char *name;
151	uint64_t flags;
152	bool quiet;
153	bool should_fail;
154	bool maybe_unsupported;
155	bool maybe_enomem;
156	bool no_recordfile;
157	pid_t target_pid;
158	bool target_kernel;
159	uint64_t since_timestamp;
160	uint32_t size_hint;
161	dt_stat_time_t timer;
162};
163
164static void
165quiet(struct scenario *scenario)
166{
167	if (scenario->timer || scenario->quiet) {
168		T_QUIET;
169	}
170}
171
172static void
173take_stackshot(struct scenario *scenario, bool compress_ok, void (^cb)(void *buf, size_t size))
174{
175start:
176	initialize_thread();
177
178	void *config = stackshot_config_create();
179	quiet(scenario);
180	T_ASSERT_NOTNULL(config, "created stackshot config");
181
182	int ret = stackshot_config_set_flags(config, scenario->flags | global_flags);
183	quiet(scenario);
184	T_ASSERT_POSIX_ZERO(ret, "set flags %#llx on stackshot config", scenario->flags);
185
186	if (scenario->size_hint > 0) {
187		ret = stackshot_config_set_size_hint(config, scenario->size_hint);
188		quiet(scenario);
189		T_ASSERT_POSIX_ZERO(ret, "set size hint %" PRIu32 " on stackshot config",
190				scenario->size_hint);
191	}
192
193	if (scenario->target_pid > 0) {
194		ret = stackshot_config_set_pid(config, scenario->target_pid);
195		quiet(scenario);
196		T_ASSERT_POSIX_ZERO(ret, "set target pid %d on stackshot config",
197				scenario->target_pid);
198	} else if (scenario->target_kernel) {
199		ret = stackshot_config_set_pid(config, 0);
200		quiet(scenario);
201		T_ASSERT_POSIX_ZERO(ret, "set kernel target on stackshot config");
202	}
203
204	if (scenario->since_timestamp > 0) {
205		ret = stackshot_config_set_delta_timestamp(config, scenario->since_timestamp);
206		quiet(scenario);
207		T_ASSERT_POSIX_ZERO(ret, "set since timestamp %" PRIu64 " on stackshot config",
208				scenario->since_timestamp);
209	}
210
211	int retries_remaining = 5;
212
213retry: ;
214	uint64_t start_time = mach_absolute_time();
215	ret = stackshot_capture_with_config(config);
216	uint64_t end_time = mach_absolute_time();
217
218	if (scenario->should_fail) {
219		T_EXPECTFAIL;
220		T_ASSERT_POSIX_ZERO(ret, "called stackshot_capture_with_config");
221		return;
222	}
223
224	if (ret == EBUSY || ret == ETIMEDOUT) {
225		if (retries_remaining > 0) {
226			if (!scenario->timer) {
227				T_LOG("stackshot_capture_with_config failed with %s (%d), retrying",
228						strerror(ret), ret);
229			}
230
231			retries_remaining--;
232			goto retry;
233		} else {
234			T_ASSERT_POSIX_ZERO(ret,
235					"called stackshot_capture_with_config (no retries remaining)");
236		}
237	} else if ((ret == ENOTSUP) && scenario->maybe_unsupported) {
238		T_SKIP("kernel indicated this stackshot configuration is not supported");
239	} else if ((ret == ENOMEM) && scenario->maybe_enomem) {
240		T_SKIP("insufficient available memory to run test");
241	} else {
242		quiet(scenario);
243		T_ASSERT_POSIX_ZERO(ret, "called stackshot_capture_with_config");
244	}
245
246	if (scenario->timer) {
247		dt_stat_mach_time_add(scenario->timer, end_time - start_time);
248	}
249	void *buf = stackshot_config_get_stackshot_buffer(config);
250	size_t size = stackshot_config_get_stackshot_size(config);
251	if (scenario->name && !scenario->no_recordfile) {
252		char sspath[MAXPATHLEN];
253		strlcpy(sspath, scenario->name, sizeof(sspath));
254		strlcat(sspath, ".kcdata", sizeof(sspath));
255		T_QUIET; T_ASSERT_POSIX_ZERO(dt_resultfile(sspath, sizeof(sspath)),
256				"create result file path");
257
258		if (!scenario->quiet) {
259			T_LOG("writing stackshot to %s", sspath);
260		}
261
262		FILE *f = fopen(sspath, "w");
263		T_WITH_ERRNO; T_QUIET; T_ASSERT_NOTNULL(f,
264				"open stackshot output file");
265
266		size_t written = fwrite(buf, size, 1, f);
267		T_QUIET; T_ASSERT_POSIX_SUCCESS(written, "wrote stackshot to file");
268
269		fclose(f);
270	}
271	cb(buf, size);
272	if (compress_ok) {
273		if (global_flags == 0) {
274			T_LOG("Restarting test with compression");
275			global_flags |= STACKSHOT_DO_COMPRESS;
276			goto start;
277		} else {
278			global_flags = 0;
279		}
280	}
281
282	ret = stackshot_config_dealloc(config);
283	T_QUIET; T_EXPECT_POSIX_ZERO(ret, "deallocated stackshot config");
284}
285
286T_DECL(simple_compressed, "take a simple compressed stackshot", T_META_TAG_VM_PREFERRED)
287{
288	struct scenario scenario = {
289		.name = "kcdata_compressed",
290		.flags = (STACKSHOT_DO_COMPRESS | STACKSHOT_SAVE_LOADINFO | STACKSHOT_THREAD_WAITINFO | STACKSHOT_GET_GLOBAL_MEM_STATS |
291				STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
292	};
293
294	T_LOG("taking compressed kcdata stackshot");
295	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
296		parse_stackshot(0, ssbuf, sslen, nil);
297	});
298}
299
300T_DECL(panic_compressed, "take a compressed stackshot with the same flags as a panic stackshot", T_META_TAG_VM_PREFERRED)
301{
302	uint64_t stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO |
303			STACKSHOT_SAVE_LOADINFO |
304			STACKSHOT_KCDATA_FORMAT |
305			STACKSHOT_ENABLE_BT_FAULTING |
306			STACKSHOT_ENABLE_UUID_FAULTING |
307			STACKSHOT_DO_COMPRESS |
308			STACKSHOT_NO_IO_STATS |
309			STACKSHOT_THREAD_WAITINFO |
310#if TARGET_OS_MAC
311			STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT |
312#endif
313			STACKSHOT_DISABLE_LATENCY_INFO);
314
315	struct scenario scenario = {
316		.name = "kcdata_panic_compressed",
317		.flags = stackshot_flags,
318	};
319
320	T_LOG("taking compressed kcdata stackshot with panic flags");
321	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
322		parse_stackshot(0, ssbuf, sslen, nil);
323	});
324}
325
326T_DECL(kcdata, "test that kcdata stackshots can be taken and parsed", T_META_TAG_VM_PREFERRED)
327{
328	struct scenario scenario = {
329		.name = "kcdata",
330		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS |
331				STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
332	};
333
334	T_LOG("taking kcdata stackshot");
335	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
336		parse_stackshot(0, ssbuf, sslen, nil);
337	});
338}
339
340static void
341get_stats(stackshot_stats_t *_Nonnull out)
342{
343	size_t oldlen = sizeof (*out);
344	bzero(out, oldlen);
345	int result = sysctlbyname("kern.stackshot_stats", out, &oldlen, NULL, 0);
346	T_WITH_ERRNO; T_ASSERT_POSIX_SUCCESS(result, "reading \"kern.stackshot_stats\" sysctl should succeed");
347	T_EXPECT_EQ(oldlen, sizeof (*out), "kernel should update full stats structure");
348}
349
350static void
351log_stats(mach_timebase_info_data_t timebase, uint64_t now, const char *name, stackshot_stats_t stat)
352{
353	uint64_t last_ago = (now - stat.ss_last_start) * timebase.numer / timebase.denom;
354	uint64_t last_duration = (stat.ss_last_end - stat.ss_last_start) * timebase.numer / timebase.denom;
355	uint64_t total_duration = (stat.ss_duration) * timebase.numer / timebase.denom;
356
357	uint64_t nanosec = 1000000000llu;
358	T_LOG("%s: %8lld stackshots, %10lld.%09lld total nsecs, last %lld.%09lld secs ago, %lld.%09lld secs long",
359		name, stat.ss_count,
360		total_duration / nanosec, total_duration % nanosec,
361		last_ago / nanosec, last_ago % nanosec,
362		last_duration / nanosec, last_duration % nanosec);
363}
364
365T_DECL(stats, "test that stackshot stats can be read out and change when a stackshot occurs", T_META_TAG_VM_PREFERRED)
366{
367	mach_timebase_info_data_t timebase = {0, 0};
368	mach_timebase_info(&timebase);
369
370	struct scenario scenario = {
371		.name = "kcdata",
372		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
373	};
374
375	stackshot_stats_t pre, post;
376
377	get_stats(&pre);
378
379	T_LOG("taking kcdata stackshot");
380	take_stackshot(&scenario, true, ^(__unused void *ssbuf, __unused size_t sslen) {
381		(void)0;
382	});
383
384	get_stats(&post);
385
386	uint64_t now = mach_absolute_time();
387
388	log_stats(timebase, now, "  pre", pre);
389	log_stats(timebase, now, " post", post);
390
391	int64_t delta_stackshots = (int64_t)(post.ss_count - pre.ss_count);
392	int64_t delta_duration = (int64_t)(post.ss_duration - pre.ss_duration) * (int64_t)timebase.numer / (int64_t)timebase.denom;
393	int64_t delta_nsec = delta_duration % 1000000000ll;
394	if (delta_nsec < 0) {
395	    delta_nsec += 1000000000ll;
396	}
397	T_LOG("delta: %+8lld stackshots, %+10lld.%09lld total nsecs", delta_stackshots, delta_duration / 1000000000ll, delta_nsec);
398
399	T_EXPECT_LT(pre.ss_last_start, pre.ss_last_end, "pre: stackshot should take time");
400	T_EXPECT_LT(pre.ss_count, post.ss_count, "stackshot count should increase when a stackshot is taken");
401	T_EXPECT_LT(pre.ss_duration, post.ss_duration, "stackshot duration should increase when a stackshot is taken");
402	T_EXPECT_LT(pre.ss_last_end, post.ss_last_start, "previous end should be less than new start after a stackshot");
403	T_EXPECT_LT(post.ss_last_start, post.ss_last_end, "post: stackshot should take time");
404}
405
406T_DECL(kcdata_faulting, "test that kcdata stackshots while faulting can be taken and parsed", T_META_TAG_VM_PREFERRED)
407{
408	struct scenario scenario = {
409		.name = "faulting",
410		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
411				| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT
412				| STACKSHOT_ENABLE_BT_FAULTING | STACKSHOT_ENABLE_UUID_FAULTING),
413	};
414
415	T_LOG("taking faulting stackshot");
416	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
417		parse_stackshot(0, ssbuf, sslen, nil);
418	});
419}
420
421T_DECL(bad_flags, "test a poorly-formed stackshot syscall", T_META_TAG_VM_PREFERRED)
422{
423	struct scenario scenario = {
424		.flags = STACKSHOT_SAVE_IN_KERNEL_BUFFER /* not allowed from user space */,
425		.should_fail = true,
426	};
427
428	T_LOG("attempting to take stackshot with kernel-only flag");
429	take_stackshot(&scenario, true, ^(__unused void *ssbuf, __unused size_t sslen) {
430		T_ASSERT_FAIL("stackshot data callback called");
431	});
432}
433
434T_DECL(delta, "test delta stackshots", T_META_TAG_VM_PREFERRED)
435{
436	struct scenario scenario = {
437		.name = "delta",
438		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
439				| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
440	};
441
442	T_LOG("taking full stackshot");
443	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
444		uint64_t stackshot_time = stackshot_timestamp(ssbuf, sslen);
445
446		T_LOG("taking delta stackshot since time %" PRIu64, stackshot_time);
447
448		parse_stackshot(0, ssbuf, sslen, nil);
449
450		struct scenario delta_scenario = {
451			.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
452					| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT
453					| STACKSHOT_COLLECT_DELTA_SNAPSHOT),
454			.since_timestamp = stackshot_time
455		};
456
457		take_stackshot(&delta_scenario, false, ^(void *dssbuf, size_t dsslen) {
458			parse_stackshot(PARSE_STACKSHOT_DELTA, dssbuf, dsslen, nil);
459		});
460	});
461}
462
463T_DECL(shared_cache_layout, "test stackshot inclusion of shared cache layout", T_META_TAG_VM_PREFERRED)
464{
465	struct scenario scenario = {
466		.name = "shared_cache_layout",
467		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
468				| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT |
469				STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT),
470	};
471
472	size_t shared_cache_length;
473	const void *cache_header = _dyld_get_shared_cache_range(&shared_cache_length);
474	if (cache_header == NULL) {
475		T_SKIP("Device not running with shared cache, skipping test...");
476	}
477
478	if (shared_cache_length == 0) {
479		T_SKIP("dyld reports that currently running shared cache has zero length");
480	}
481
482	T_LOG("taking stackshot with STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT set");
483	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
484		parse_stackshot(PARSE_STACKSHOT_SHAREDCACHE_LAYOUT, ssbuf, sslen, nil);
485	});
486}
487
488T_DECL(stress, "test that taking stackshots for 60 seconds doesn't crash the system", T_META_TAG_VM_PREFERRED)
489{
490	uint64_t max_diff_time = 60ULL /* seconds */ * 1000000000ULL;
491	uint64_t start_time;
492
493	struct scenario scenario = {
494		.name = "stress",
495		.quiet = true,
496		.flags = (STACKSHOT_KCDATA_FORMAT |
497				STACKSHOT_THREAD_WAITINFO |
498				STACKSHOT_SAVE_LOADINFO |
499				STACKSHOT_SAVE_KEXT_LOADINFO |
500				STACKSHOT_GET_GLOBAL_MEM_STATS |
501				STACKSHOT_SAVE_IMP_DONATION_PIDS |
502				STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT |
503				STACKSHOT_THREAD_GROUP |
504				STACKSHOT_SAVE_JETSAM_COALITIONS |
505				STACKSHOT_ASID |
506				STACKSHOT_EXCLAVES |
507				0),
508	};
509
510	start_time = clock_gettime_nsec_np(CLOCK_MONOTONIC);
511	while (clock_gettime_nsec_np(CLOCK_MONOTONIC) - start_time < max_diff_time) {
512		take_stackshot(&scenario, false, ^(void * __unused ssbuf,
513				size_t __unused sslen) {
514			printf(".");
515			fflush(stdout);
516		});
517
518		/*
519		 * After the first stackshot, there's no point in continuing to
520		 * write them to disk, and it wears down the SSDs.
521		 */
522		scenario.no_recordfile = true;
523
524		/* Leave some time for the testing infrastructure to catch up */
525		usleep(10000);
526
527	}
528	printf("\n");
529}
530
531T_DECL(dispatch_queue_label, "test that kcdata stackshots contain libdispatch queue labels", T_META_TAG_VM_PREFERRED)
532{
533	struct scenario scenario = {
534		.name = "kcdata",
535		.flags = (STACKSHOT_GET_DQ | STACKSHOT_KCDATA_FORMAT),
536	};
537	dispatch_semaphore_t child_ready_sem, parent_done_sem;
538	dispatch_queue_t dq;
539
540#if TARGET_OS_WATCH
541	T_SKIP("This test is flaky on watches: 51663346");
542#endif
543
544	child_ready_sem = dispatch_semaphore_create(0);
545	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "dqlabel child semaphore");
546
547	parent_done_sem = dispatch_semaphore_create(0);
548	T_QUIET; T_ASSERT_NOTNULL(parent_done_sem, "dqlabel parent semaphore");
549
550	dq = dispatch_queue_create(TEST_STACKSHOT_QUEUE_LABEL, NULL);
551	T_QUIET; T_ASSERT_NOTNULL(dq, "dispatch queue");
552
553	/* start the helper thread */
554	dispatch_async(dq, ^{
555			dispatch_semaphore_signal(child_ready_sem);
556
557			dispatch_semaphore_wait(parent_done_sem, DISPATCH_TIME_FOREVER);
558	});
559
560	/* block behind the child starting up */
561	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
562
563	T_LOG("taking kcdata stackshot with libdispatch queue labels");
564	take_stackshot(&scenario, true, ^(void *ssbuf, size_t sslen) {
565		parse_stackshot(PARSE_STACKSHOT_DISPATCH_QUEUE_LABEL, ssbuf, sslen, nil);
566	});
567
568	dispatch_semaphore_signal(parent_done_sem);
569}
570
571#define CACHEADDR_ENV "STACKSHOT_TEST_DYLDADDR"
572T_HELPER_DECL(spawn_reslide_child, "child process to spawn with alternate slide")
573{
574	size_t shared_cache_len;
575	const void *addr, *prevaddr;
576	uintmax_t v;
577	char *endptr;
578
579	const char *cacheaddr_env = getenv(CACHEADDR_ENV);
580	T_QUIET; T_ASSERT_NOTNULL(cacheaddr_env, "getenv("CACHEADDR_ENV")");
581	errno = 0;
582	endptr = NULL;
583	v = strtoumax(cacheaddr_env, &endptr, 16);	/* read hex value */
584	T_WITH_ERRNO; T_QUIET; T_ASSERT_NE(v, 0l, "getenv(%s) = \"%s\" should be a non-zero hex number", CACHEADDR_ENV, cacheaddr_env);
585	T_QUIET; T_ASSERT_EQ(*endptr, 0, "getenv(%s) = \"%s\" endptr \"%s\" should be empty", CACHEADDR_ENV, cacheaddr_env, endptr);
586
587	prevaddr = (const void *)v;
588	addr = _dyld_get_shared_cache_range(&shared_cache_len);
589	T_QUIET; T_ASSERT_NOTNULL(addr, "shared cache address");
590
591	T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(getppid(), (addr == prevaddr) ? SIGUSR2 : SIGUSR1), "signaled parent to take stackshot");
592	for (;;) {
593		(void) pause();		/* parent will kill -9 us */
594	}
595}
596
597T_DECL(shared_cache_flags, "tests stackshot's task_ss_flags for the shared cache", T_META_TAG_VM_PREFERRED)
598{
599	posix_spawnattr_t		attr;
600	char *env_addr;
601	char path[PATH_MAX];
602	__block bool child_same_addr = false;
603
604	uint32_t path_size = sizeof(path);
605	T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
606	char *args[] = { path, "-n", "spawn_reslide_child", NULL };
607	pid_t pid;
608	size_t shared_cache_len;
609	const void *addr;
610
611	dispatch_source_t child_diffsig_src, child_samesig_src;
612	dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
613	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "shared_cache child semaphore");
614
615	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
616	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
617
618	signal(SIGUSR1, SIG_IGN);
619	signal(SIGUSR2, SIG_IGN);
620	child_samesig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
621	T_QUIET; T_ASSERT_NOTNULL(child_samesig_src, "dispatch_source_create (child_samesig_src)");
622	child_diffsig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR2, 0, signal_processing_q);
623	T_QUIET; T_ASSERT_NOTNULL(child_diffsig_src, "dispatch_source_create (child_diffsig_src)");
624
625	/* child will signal us depending on if their addr is the same or different */
626	dispatch_source_set_event_handler(child_samesig_src, ^{ child_same_addr = false; dispatch_semaphore_signal(child_ready_sem); });
627	dispatch_source_set_event_handler(child_diffsig_src, ^{ child_same_addr = true; dispatch_semaphore_signal(child_ready_sem); });
628	dispatch_activate(child_samesig_src);
629	dispatch_activate(child_diffsig_src);
630
631	addr = _dyld_get_shared_cache_range(&shared_cache_len);
632	T_QUIET; T_ASSERT_NOTNULL(addr, "shared cache address");
633
634	T_QUIET; T_ASSERT_POSIX_SUCCESS(asprintf(&env_addr, "%p", addr), "asprintf of env_addr succeeded");
635	T_QUIET; T_ASSERT_POSIX_SUCCESS(setenv(CACHEADDR_ENV, env_addr, true), "setting "CACHEADDR_ENV" to %s", env_addr);
636
637	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawnattr_init(&attr), "posix_spawnattr_init");
638	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawnattr_setflags(&attr, _POSIX_SPAWN_RESLIDE), "posix_spawnattr_setflags");
639	int sp_ret = posix_spawn(&pid, path, NULL, &attr, args, environ);
640	T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", args[0], pid);
641
642	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
643	T_LOG("received signal from child (%s), capturing stackshot", child_same_addr ? "same shared cache addr" : "different shared cache addr");
644
645	struct scenario scenario = {
646		.name = "shared_cache_flags",
647		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
648				| STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT
649				| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
650	};
651
652	take_stackshot(&scenario, false, ^( void *ssbuf, size_t sslen) {
653		int status;
654		/* First kill the child so we can reap it */
655		T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(pid, SIGKILL), "killing spawned process");
656		T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on spawned child");
657		T_QUIET; T_ASSERT_EQ(!!WIFSIGNALED(status), 1, "waitpid status should be signalled");
658		T_QUIET; T_ASSERT_EQ(WTERMSIG(status), SIGKILL, "waitpid status should be SIGKILLed");
659
660		parse_stackshot(PARSE_STACKSHOT_SHAREDCACHE_FLAGS, ssbuf, sslen,
661			@{sharedcache_child_pid_key: @(pid), sharedcache_child_sameaddr_key: @(child_same_addr ? 1 : 0)});
662	});
663}
664
665T_DECL(transitioning_tasks, "test that stackshot contains transitioning task info", T_META_BOOTARGS_SET("enable_proc_exit_lpexit_spin=1"), T_META_TAG_VM_PREFERRED)
666{
667    int32_t sysctlValue = -1, numAttempts =0;
668    char path[PATH_MAX];
669    uint32_t path_size = sizeof(path);
670    T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
671    char *args[] = { path, "-n", "exec_child_preexec", NULL };
672
673    dispatch_source_t child_sig_src;
674    dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
675    T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "exec child semaphore");
676
677    dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
678    T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
679
680    pid_t pid;
681
682    signal(SIGUSR1, SIG_IGN);
683    child_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
684    T_QUIET; T_ASSERT_NOTNULL(child_sig_src, "dispatch_source_create (child_sig_src)");
685
686    dispatch_source_set_event_handler(child_sig_src, ^{ dispatch_semaphore_signal(child_ready_sem); });
687    dispatch_activate(child_sig_src);
688
689    T_ASSERT_POSIX_SUCCESS(sysctlbyname("debug.proc_exit_lpexit_spin_pid", NULL, NULL, &sysctlValue, sizeof(sysctlValue)), "set debug.proc_exit_lpexit_spin_pid=-1");
690
691    int proc_exit_spin_pos = 0 ;
692
693    while (0 == sysctlbyname("debug.proc_exit_lpexit_spin_pos", NULL, NULL, &proc_exit_spin_pos, sizeof(proc_exit_spin_pos))) {
694
695        T_LOG(" ##### Testing while spinning in proc_exit at position %d ##### ", proc_exit_spin_pos);
696
697        int sp_ret = posix_spawn(&pid, args[0], NULL, NULL, args, NULL);
698        T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", args[0], pid);
699
700        dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
701
702        struct proc_uniqidentifierinfo proc_info_data = { };
703        int retval = proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO, 0, &proc_info_data, sizeof(proc_info_data));
704        T_QUIET; T_EXPECT_POSIX_SUCCESS(retval, "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO");
705        T_QUIET; T_ASSERT_EQ_INT(retval, (int) sizeof(proc_info_data), "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO returned data");
706
707        T_ASSERT_POSIX_SUCCESS(kill(pid, SIGUSR1), "signaled pre-exec child to exec");
708
709	/* wait for a signal from post-exec child */
710        dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
711
712        T_ASSERT_POSIX_SUCCESS(sysctlbyname("debug.proc_exit_lpexit_spin_pid", NULL, NULL, &pid, sizeof(pid)), "set debug.proc_exit_lpexit_spin_pid =  %d, ", pid);
713
714        T_ASSERT_POSIX_SUCCESS(kill(pid, SIGKILL), "kill post-exec child %d", pid);
715
716        sysctlValue = 0;
717        size_t len = sizeof(sysctlValue);
718        while (numAttempts < 5) {
719            T_ASSERT_POSIX_SUCCESS(sysctlbyname("debug.proc_exit_lpexit_spinning", &sysctlValue, &len, NULL, 0), "retrieve debug.proc_exit_lpexit_spinning");
720            if (sysctlValue != 1) numAttempts++;
721            else break;
722            sleep(1);
723        }
724
725        T_ASSERT_EQ_UINT(sysctlValue, 1, "find spinning task in proc_exit()");
726
727        struct scenario scenario = {
728            .name = "transitioning_tasks",
729            .flags = (STACKSHOT_KCDATA_FORMAT)
730        };
731
732        take_stackshot(&scenario, false, ^( void *ssbuf, size_t sslen) {
733            parse_stackshot(PARSE_STACKSHOT_TRANSITIONING, ssbuf, sslen, @{transitioning_pid_key: @(pid)});
734
735            // Kill the child
736            int sysctlValueB = -1;
737            T_ASSERT_POSIX_SUCCESS(sysctlbyname("debug.proc_exit_lpexit_spin_pid", NULL, NULL, &sysctlValueB, sizeof(sysctlValueB)), "set debug.proc_exit_lpexit_spin_pid=-1");
738            sleep(1);
739            size_t blen = sizeof(sysctlValueB);
740            T_ASSERT_POSIX_SUCCESS(sysctlbyname("debug.proc_exit_lpexit_spinning", &sysctlValueB, &blen, NULL, 0), "retrieve debug.proc_exit_lpexit_spinning");
741            T_ASSERT_EQ_UINT(sysctlValueB, 0, "make sure nothing is spining in proc_exit()");
742            int status;
743            T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on post-exec child");
744        });
745
746        proc_exit_spin_pos++;
747    }
748
749}
750
751static void *stuck_sysctl_thread(void *arg) {
752	int val = 1;
753	dispatch_semaphore_t child_thread_started = *(dispatch_semaphore_t *)arg;
754
755	dispatch_semaphore_signal(child_thread_started);
756	T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.wedge_thread", NULL, NULL, &val, sizeof(val)), "wedge child thread");
757
758	return NULL;
759}
760
761T_HELPER_DECL(zombie_child, "child process to sample as a zombie")
762{
763	pthread_t pthread;
764	dispatch_semaphore_t child_thread_started = dispatch_semaphore_create(0);
765	T_QUIET; T_ASSERT_NOTNULL(child_thread_started, "zombie child thread semaphore");
766
767	/* spawn another thread to get stuck in the kernel, then call exit() to become a zombie */
768	T_QUIET; T_ASSERT_POSIX_SUCCESS(pthread_create(&pthread, NULL, stuck_sysctl_thread, &child_thread_started), "pthread_create");
769
770	dispatch_semaphore_wait(child_thread_started, DISPATCH_TIME_FOREVER);
771
772	/* sleep for a bit in the hope of ensuring that the other thread has called the sysctl before we signal the parent */
773	usleep(100);
774	T_ASSERT_POSIX_SUCCESS(kill(getppid(), SIGUSR1), "signaled parent to take stackshot");
775
776	exit(0);
777}
778
779T_DECL(zombie, "tests a stackshot of a zombie task with a thread stuck in the kernel",
780	T_META_ENABLED(false), /* test is too flaky to run by default, but transitioning_tasks covers this case as well */
781	T_META_TAG_VM_PREFERRED)
782{
783	char path[PATH_MAX];
784	uint32_t path_size = sizeof(path);
785	T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
786	char *args[] = { path, "-n", "zombie_child", NULL };
787
788	dispatch_source_t child_sig_src;
789	dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
790	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "zombie child semaphore");
791
792	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
793	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
794
795	pid_t pid;
796
797	T_LOG("spawning a child");
798
799	signal(SIGUSR1, SIG_IGN);
800	child_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
801	T_QUIET; T_ASSERT_NOTNULL(child_sig_src, "dispatch_source_create (child_sig_src)");
802
803	dispatch_source_set_event_handler(child_sig_src, ^{ dispatch_semaphore_signal(child_ready_sem); });
804	dispatch_activate(child_sig_src);
805
806	int sp_ret = posix_spawn(&pid, args[0], NULL, NULL, args, NULL);
807	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", args[0], pid);
808
809	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
810
811	T_LOG("received signal from child, capturing stackshot");
812
813	struct proc_bsdshortinfo bsdshortinfo;
814	int retval, iterations_to_wait = 10;
815
816	while (iterations_to_wait > 0) {
817		retval = proc_pidinfo(pid, PROC_PIDT_SHORTBSDINFO, 0, &bsdshortinfo, sizeof(bsdshortinfo));
818		if ((retval == 0) && errno == ESRCH) {
819			T_LOG("unable to find child using proc_pidinfo, assuming zombie");
820			break;
821		}
822
823		T_QUIET; T_WITH_ERRNO; T_ASSERT_GT(retval, 0, "proc_pidinfo(PROC_PIDT_SHORTBSDINFO) returned a value > 0");
824		T_QUIET; T_ASSERT_EQ(retval, (int)sizeof(bsdshortinfo), "proc_pidinfo call for PROC_PIDT_SHORTBSDINFO returned expected size");
825
826		if (bsdshortinfo.pbsi_flags & PROC_FLAG_INEXIT) {
827			T_LOG("child proc info marked as in exit");
828			break;
829		}
830
831		iterations_to_wait--;
832		if (iterations_to_wait == 0) {
833			/*
834			 * This will mark the test as failed but let it continue so we
835			 * don't leave a process stuck in the kernel.
836			 */
837			T_FAIL("unable to discover that child is marked as exiting");
838		}
839
840		/* Give the child a few more seconds to make it to exit */
841		sleep(5);
842	}
843
844	/* Give the child some more time to make it through exit */
845	sleep(10);
846
847	struct scenario scenario = {
848		.name = "zombie",
849		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
850				| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
851	};
852
853	take_stackshot(&scenario, false, ^( void *ssbuf, size_t sslen) {
854		/* First unwedge the child so we can reap it */
855		int val = 1, status;
856		T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.unwedge_thread", NULL, NULL, &val, sizeof(val)), "unwedge child");
857
858		T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on zombie child");
859
860		parse_stackshot(PARSE_STACKSHOT_ZOMBIE, ssbuf, sslen, @{zombie_child_pid_key: @(pid)});
861	});
862}
863
864T_HELPER_DECL(exec_child_preexec, "child process pre-exec")
865{
866	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
867	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
868
869	signal(SIGUSR1, SIG_IGN);
870	dispatch_source_t parent_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
871	T_QUIET; T_ASSERT_NOTNULL(parent_sig_src, "dispatch_source_create (child_sig_src)");
872	dispatch_source_set_event_handler(parent_sig_src, ^{
873
874		// Parent took a timestamp then signaled us: exec into the next process
875
876		char path[PATH_MAX];
877		uint32_t path_size = sizeof(path);
878		T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
879		char *args[] = { path, "-n", "exec_child_postexec", NULL };
880
881		T_QUIET; T_ASSERT_POSIX_ZERO(execve(args[0], args, NULL), "execing into exec_child_postexec");
882	});
883	dispatch_activate(parent_sig_src);
884
885	T_ASSERT_POSIX_SUCCESS(kill(getppid(), SIGUSR1), "signaled parent to take timestamp");
886
887	sleep(100);
888	// Should never get here
889	T_FAIL("Received signal to exec from parent");
890}
891
892T_HELPER_DECL(exec_child_postexec, "child process post-exec to sample")
893{
894	T_ASSERT_POSIX_SUCCESS(kill(getppid(), SIGUSR1), "signaled parent to take stackshot");
895	sleep(100);
896	// Should never get here
897	T_FAIL("Killed by parent");
898}
899
900T_DECL(exec, "test getting full task snapshots for a task that execs", T_META_TAG_VM_PREFERRED)
901{
902	char path[PATH_MAX];
903	uint32_t path_size = sizeof(path);
904	T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
905	char *args[] = { path, "-n", "exec_child_preexec", NULL };
906
907	dispatch_source_t child_sig_src;
908	dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
909	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "exec child semaphore");
910
911	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
912	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
913
914	pid_t pid;
915
916	T_LOG("spawning a child");
917
918	signal(SIGUSR1, SIG_IGN);
919	child_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
920	T_QUIET; T_ASSERT_NOTNULL(child_sig_src, "dispatch_source_create (child_sig_src)");
921
922	dispatch_source_set_event_handler(child_sig_src, ^{ dispatch_semaphore_signal(child_ready_sem); });
923	dispatch_activate(child_sig_src);
924
925	int sp_ret = posix_spawn(&pid, args[0], NULL, NULL, args, NULL);
926	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", args[0], pid);
927
928	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
929	uint64_t start_time = mach_absolute_time();
930
931	struct proc_uniqidentifierinfo proc_info_data = { };
932	int retval = proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO, 0, &proc_info_data, sizeof(proc_info_data));
933	T_QUIET; T_EXPECT_POSIX_SUCCESS(retval, "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO");
934	T_QUIET; T_ASSERT_EQ_INT(retval, (int) sizeof(proc_info_data), "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO returned data");
935	uint64_t unique_pid = proc_info_data.p_uniqueid;
936
937	T_LOG("received signal from pre-exec child, unique_pid is %llu, timestamp is %llu", unique_pid, start_time);
938
939	T_ASSERT_POSIX_SUCCESS(kill(pid, SIGUSR1), "signaled pre-exec child to exec");
940
941	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
942
943	T_LOG("received signal from post-exec child, capturing stackshot");
944
945	struct scenario scenario = {
946		.name = "exec",
947		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
948				  | STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT
949				  | STACKSHOT_COLLECT_DELTA_SNAPSHOT),
950		.since_timestamp = start_time
951	};
952
953	take_stackshot(&scenario, false, ^( void *ssbuf, size_t sslen) {
954		// Kill the child
955		int status;
956		T_ASSERT_POSIX_SUCCESS(kill(pid, SIGKILL), "kill post-exec child %d", pid);
957		T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on post-exec child");
958
959		parse_stackshot(PARSE_STACKSHOT_POSTEXEC | PARSE_STACKSHOT_DELTA, ssbuf, sslen, @{postexec_child_unique_pid_key: @(unique_pid)});
960	});
961}
962
963T_DECL(
964	exec_inprogress,
965	"test stackshots of processes in the middle of exec",
966	T_META_ENABLED(false), /* rdar://111691318 */
967	T_META_TAG_VM_PREFERRED)
968{
969	pid_t pid;
970	/* a BASH quine which execs itself as long as the parent doesn't exit */
971        char *bash_prog = "[[ $PPID -ne 1 ]] && exec /bin/bash -c \"$0\" \"$0\"";
972	char *args[] = { "/bin/bash", "-c", bash_prog, bash_prog, NULL };
973
974	posix_spawnattr_t sattr;
975	T_ASSERT_POSIX_ZERO(posix_spawnattr_init(&sattr), "posix_spawnattr_init");
976	T_ASSERT_POSIX_ZERO(posix_spawn(&pid, args[0], NULL, &sattr, args, NULL), "spawn exec_inprogress_child");
977
978	struct scenario scenario = {
979		.name = "exec_inprogress",
980		.flags = (STACKSHOT_KCDATA_FORMAT),
981		.target_pid = pid,
982	};
983
984	int tries = 0;
985	int tries_limit = 30;
986	__block bool found = false;
987	__block uint64_t cid1 = 0, cid2 = 0;
988
989	for (tries = 0; !found && tries < tries_limit; tries++) {
990		take_stackshot(&scenario, false,
991		    ^( void *ssbuf, size_t sslen) {
992			parse_stackshot(PARSE_STACKSHOT_EXEC_INPROGRESS | PARSE_STACKSHOT_TARGETPID,
993			    ssbuf, sslen, @{
994				exec_inprogress_pid_key: @(pid),
995				exec_inprogress_found_key: ^(uint64_t id1, uint64_t id2) { found = true; cid1 = id1; cid2 = id2; }});
996		});
997	}
998	T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(pid, SIGKILL), "killing exec loop");
999	T_ASSERT_TRUE(found, "able to find our execing process mid-exec in %d tries", tries);
1000	T_ASSERT_NE(cid1, cid2, "container IDs for in-progress exec are unique");
1001	T_PASS("found mid-exec process in %d tries", tries);
1002}
1003
1004#ifdef _LP64
1005#if __has_feature(ptrauth_calls)
1006#define __ptrauth_swift_async_context_parent \
1007  __ptrauth(ptrauth_key_process_independent_data, 1, 0xbda2)
1008#define __ptrauth_swift_async_context_resume \
1009  __ptrauth(ptrauth_key_function_pointer, 1, 0xd707)
1010#else
1011#define __ptrauth_swift_async_context_parent
1012#define __ptrauth_swift_async_context_resume
1013#endif
1014// Add 1 to match the symbolication aid added by the stackshot backtracer.
1015#define asyncstack_frame(x) ((uintptr_t)(void *)ptrauth_strip((void *)(x), ptrauth_key_function_pointer) + 1)
1016
1017// This struct fakes the Swift AsyncContext struct which is used by
1018// the Swift concurrency runtime. We only care about the first 2 fields.
1019struct fake_async_context {
1020	struct fake_async_context* __ptrauth_swift_async_context_parent next;
1021	void(*__ptrauth_swift_async_context_resume resume_pc)(void);
1022};
1023
1024static void
1025level1_func()
1026{
1027}
1028static void
1029level2_func()
1030{
1031}
1032
1033// Create a chain of fake async contexts; sync with asyncstack_expected_stack below
1034static alignas(16) struct fake_async_context level1 = { 0, level1_func };
1035static alignas(16) struct fake_async_context level2 = { &level1, level2_func };
1036
1037struct async_test_semaphores {
1038	dispatch_semaphore_t child_ready_sem;	/* signal parent we're ready */
1039	dispatch_semaphore_t child_exit_sem;	/* parent tells us to go away */
1040};
1041
1042#define	ASYNCSTACK_THREAD_NAME "asyncstack_thread"
1043
1044static void __attribute__((noinline, not_tail_called))
1045expect_asyncstack(void *arg)
1046{
1047	struct async_test_semaphores *async_ts = arg;
1048
1049	T_QUIET; T_ASSERT_POSIX_ZERO(pthread_setname_np(ASYNCSTACK_THREAD_NAME),
1050	     "set thread name to %s", ASYNCSTACK_THREAD_NAME);
1051
1052	/* Tell the main thread we're all set up, then wait for permission to exit */
1053	dispatch_semaphore_signal(async_ts->child_ready_sem);
1054	dispatch_semaphore_wait(async_ts->child_exit_sem, DISPATCH_TIME_FOREVER);
1055	usleep(1);	/* make sure we don't tailcall semaphore_wait */
1056}
1057
1058static void *
1059asyncstack_thread(void *arg)
1060{
1061	uint64_t *fp = __builtin_frame_address(0);
1062	// We cannot use a variable of pointer type, because this ABI is valid
1063	// on arm64_32 where pointers are 32bits, but the context pointer will
1064	// still be stored in a 64bits slot on the stack.
1065#if __has_feature(ptrauth_calls)
1066#define __stack_context_auth __ptrauth(ptrauth_key_process_dependent_data, 1, \
1067	        0xc31a)
1068	struct fake_async_context * __stack_context_auth ctx = &level2;
1069#else // __has_feature(ptrauth_calls)
1070	/* struct fake_async_context * */uint64_t ctx  = (uintptr_t)&level2;
1071#endif // !__has_feature(ptrauth_calls)
1072
1073	// The signature of an async frame on the OS stack is:
1074	// [ <AsyncContext address>, <Saved FP | (1<<60)>, <return address> ]
1075	// The Async context must be right before the saved FP on the stack. This
1076	// should happen naturally in an optimized build as it is the only
1077	// variable on the stack.
1078	// This function cannot use T_ASSERT_* becuse it changes the stack
1079	// layout.
1080	assert((uintptr_t)fp - (uintptr_t)&ctx == 8);
1081
1082	// Modify the saved FP on the stack to include the async frame marker
1083	*fp |= (0x1ULL << 60);
1084	expect_asyncstack(arg);
1085	return NULL;
1086}
1087
1088T_DECL(asyncstack, "test swift async stack entries", T_META_TAG_VM_PREFERRED)
1089{
1090	struct scenario scenario = {
1091		.name = "asyncstack",
1092		.flags = STACKSHOT_KCDATA_FORMAT | STACKSHOT_SAVE_LOADINFO,
1093	};
1094	struct async_test_semaphores async_ts = {
1095	    .child_ready_sem = dispatch_semaphore_create(0),
1096	    .child_exit_sem = dispatch_semaphore_create(0),
1097	};
1098	T_QUIET; T_ASSERT_NOTNULL(async_ts.child_ready_sem, "child_ready_sem alloc");
1099	T_QUIET; T_ASSERT_NOTNULL(async_ts.child_exit_sem, "child_exit_sem alloc");
1100
1101	pthread_t pthread;
1102	__block uint64_t threadid = 0;
1103	T_QUIET; T_ASSERT_POSIX_ZERO(pthread_create(&pthread, NULL, asyncstack_thread, &async_ts), "pthread_create");
1104	T_QUIET; T_ASSERT_POSIX_ZERO(pthread_threadid_np(pthread, &threadid), "pthread_threadid_np");
1105
1106	dispatch_semaphore_wait(async_ts.child_ready_sem, DISPATCH_TIME_FOREVER);
1107
1108	take_stackshot(&scenario, true, ^( void *ssbuf, size_t sslen) {
1109		parse_stackshot(PARSE_STACKSHOT_ASYNCSTACK, ssbuf, sslen, @{
1110		    asyncstack_expected_threadid_key: @(threadid),
1111		       asyncstack_expected_stack_key: @[ @(asyncstack_frame(level2_func)), @(asyncstack_frame(level1_func)) ],
1112		});
1113	});
1114
1115	dispatch_semaphore_signal(async_ts.child_exit_sem);
1116	T_QUIET; T_ASSERT_POSIX_ZERO(pthread_join(pthread, NULL), "wait for thread");
1117
1118}
1119#endif /* #ifdef _LP64 */
1120
1121static uint32_t
1122get_user_promotion_basepri(void)
1123{
1124	mach_msg_type_number_t count = THREAD_POLICY_STATE_COUNT;
1125	struct thread_policy_state thread_policy;
1126	boolean_t get_default = FALSE;
1127	mach_port_t thread_port = pthread_mach_thread_np(pthread_self());
1128
1129	kern_return_t kr = thread_policy_get(thread_port, THREAD_POLICY_STATE,
1130	    (thread_policy_t)&thread_policy, &count, &get_default);
1131	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_policy_get");
1132	return thread_policy.thps_user_promotion_basepri;
1133}
1134
1135static int
1136get_pri(thread_t thread_port)
1137{
1138	kern_return_t kr;
1139
1140	thread_extended_info_data_t extended_info;
1141	mach_msg_type_number_t count = THREAD_EXTENDED_INFO_COUNT;
1142	kr = thread_info(thread_port, THREAD_EXTENDED_INFO,
1143	    (thread_info_t)&extended_info, &count);
1144
1145	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_info");
1146
1147	return extended_info.pth_curpri;
1148}
1149
1150
1151T_DECL(turnstile_singlehop, "turnstile single hop test", T_META_TAG_VM_PREFERRED)
1152{
1153	dispatch_queue_t dq1, dq2;
1154	dispatch_semaphore_t sema_x;
1155	dispatch_queue_attr_t dq1_attr, dq2_attr;
1156	__block qos_class_t main_qos = 0;
1157	__block int main_relpri = 0, main_relpri2 = 0, main_afterpri = 0;
1158	struct scenario scenario = {
1159		.name = "turnstile_singlehop",
1160		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
1161	};
1162	dq1_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0);
1163	dq2_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0);
1164	pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER;
1165	pthread_mutex_t lock_b = PTHREAD_MUTEX_INITIALIZER;
1166
1167	pthread_mutex_t *lockap = &lock_a, *lockbp = &lock_b;
1168
1169	dq1 = dispatch_queue_create("q1", dq1_attr);
1170	dq2 = dispatch_queue_create("q2", dq2_attr);
1171	sema_x = dispatch_semaphore_create(0);
1172
1173	pthread_mutex_lock(lockap);
1174	dispatch_async(dq1, ^{
1175		pthread_mutex_lock(lockbp);
1176		T_ASSERT_POSIX_SUCCESS(pthread_get_qos_class_np(pthread_self(), &main_qos, &main_relpri), "get qos class");
1177		T_LOG("The priority of q1 is %d\n", get_pri(mach_thread_self()));
1178		dispatch_semaphore_signal(sema_x);
1179		pthread_mutex_lock(lockap);
1180	});
1181	dispatch_semaphore_wait(sema_x, DISPATCH_TIME_FOREVER);
1182
1183	T_LOG("Async1 completed");
1184
1185	pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0);
1186	T_ASSERT_POSIX_SUCCESS(pthread_get_qos_class_np(pthread_self(), &main_qos, &main_relpri), "get qos class");
1187	T_LOG("The priority of main is %d\n", get_pri(mach_thread_self()));
1188	main_relpri = get_pri(mach_thread_self());
1189
1190	dispatch_async(dq2, ^{
1191		T_ASSERT_POSIX_SUCCESS(pthread_get_qos_class_np(pthread_self(), &main_qos, &main_relpri2), "get qos class");
1192		T_LOG("The priority of q2 is %d\n", get_pri(mach_thread_self()));
1193		dispatch_semaphore_signal(sema_x);
1194		pthread_mutex_lock(lockbp);
1195	});
1196	dispatch_semaphore_wait(sema_x, DISPATCH_TIME_FOREVER);
1197
1198	T_LOG("Async2 completed");
1199
1200	while (1) {
1201		main_afterpri = (int) get_user_promotion_basepri();
1202		if (main_relpri != main_afterpri) {
1203			T_LOG("Success with promotion pri is %d", main_afterpri);
1204			break;
1205		}
1206
1207		usleep(100);
1208	}
1209
1210	take_stackshot(&scenario, true, ^( void *ssbuf, size_t sslen) {
1211		parse_stackshot(PARSE_STACKSHOT_TURNSTILEINFO, ssbuf, sslen, nil);
1212	});
1213}
1214
1215
1216static void
1217expect_instrs_cycles_in_stackshot(void *ssbuf, size_t sslen)
1218{
1219	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
1220
1221	bool in_task = false;
1222	bool in_thread = false;
1223	bool saw_instrs_cycles = false;
1224	iter = kcdata_iter_next(iter);
1225
1226	KCDATA_ITER_FOREACH(iter) {
1227		switch (kcdata_iter_type(iter)) {
1228		case KCDATA_TYPE_CONTAINER_BEGIN:
1229			switch (kcdata_iter_container_type(iter)) {
1230			case STACKSHOT_KCCONTAINER_TASK:
1231				in_task = true;
1232				saw_instrs_cycles = false;
1233				break;
1234
1235			case STACKSHOT_KCCONTAINER_THREAD:
1236				in_thread = true;
1237				saw_instrs_cycles = false;
1238				break;
1239
1240			default:
1241				break;
1242			}
1243			break;
1244
1245		case STACKSHOT_KCTYPE_INSTRS_CYCLES:
1246			saw_instrs_cycles = true;
1247			break;
1248
1249		case KCDATA_TYPE_CONTAINER_END:
1250			if (in_thread) {
1251				T_QUIET; T_EXPECT_TRUE(saw_instrs_cycles,
1252						"saw instructions and cycles in thread");
1253				in_thread = false;
1254			} else if (in_task) {
1255				T_QUIET; T_EXPECT_TRUE(saw_instrs_cycles,
1256						"saw instructions and cycles in task");
1257				in_task = false;
1258			}
1259
1260		default:
1261			break;
1262		}
1263	}
1264}
1265
1266static void
1267skip_if_monotonic_unsupported(void)
1268{
1269	int supported = 0;
1270	size_t supported_size = sizeof(supported);
1271	int ret = sysctlbyname("kern.monotonic.supported", &supported,
1272			&supported_size, 0, 0);
1273	if (ret < 0 || !supported) {
1274		T_SKIP("monotonic is unsupported");
1275	}
1276}
1277
1278T_DECL(instrs_cycles, "test a getting instructions and cycles in stackshot", T_META_TAG_VM_PREFERRED)
1279{
1280	skip_if_monotonic_unsupported();
1281
1282	struct scenario scenario = {
1283		.name = "instrs-cycles",
1284		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_INSTRS_CYCLES
1285				| STACKSHOT_KCDATA_FORMAT),
1286	};
1287
1288	T_LOG("attempting to take stackshot with instructions and cycles");
1289	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1290		parse_stackshot(0, ssbuf, sslen, nil);
1291		expect_instrs_cycles_in_stackshot(ssbuf, sslen);
1292	});
1293}
1294
1295T_DECL(delta_instrs_cycles,
1296		"test delta stackshots with instructions and cycles", T_META_TAG_VM_PREFERRED)
1297{
1298	skip_if_monotonic_unsupported();
1299
1300	struct scenario scenario = {
1301		.name = "delta-instrs-cycles",
1302		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_INSTRS_CYCLES
1303				| STACKSHOT_KCDATA_FORMAT),
1304	};
1305
1306	T_LOG("taking full stackshot");
1307	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1308		uint64_t stackshot_time = stackshot_timestamp(ssbuf, sslen);
1309
1310		T_LOG("taking delta stackshot since time %" PRIu64, stackshot_time);
1311
1312		parse_stackshot(0, ssbuf, sslen, nil);
1313		expect_instrs_cycles_in_stackshot(ssbuf, sslen);
1314
1315		struct scenario delta_scenario = {
1316			.name = "delta-instrs-cycles-next",
1317			.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_INSTRS_CYCLES
1318					| STACKSHOT_KCDATA_FORMAT
1319					| STACKSHOT_COLLECT_DELTA_SNAPSHOT),
1320			.since_timestamp = stackshot_time,
1321		};
1322
1323		take_stackshot(&delta_scenario, false, ^(void *dssbuf, size_t dsslen) {
1324			parse_stackshot(PARSE_STACKSHOT_DELTA, dssbuf, dsslen, nil);
1325			expect_instrs_cycles_in_stackshot(dssbuf, dsslen);
1326		});
1327	});
1328}
1329
1330static void
1331check_thread_groups_supported()
1332{
1333	int err;
1334	int supported = 0;
1335	size_t supported_size = sizeof(supported);
1336	err = sysctlbyname("kern.thread_groups_supported", &supported, &supported_size, NULL, 0);
1337
1338	if (err || !supported)
1339		T_SKIP("thread groups not supported on this system");
1340}
1341
1342T_DECL(thread_groups, "test getting thread groups in stackshot", T_META_TAG_VM_PREFERRED)
1343{
1344	check_thread_groups_supported();
1345
1346	struct scenario scenario = {
1347		.name = "thread-groups",
1348		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_THREAD_GROUP
1349				| STACKSHOT_KCDATA_FORMAT),
1350	};
1351
1352	T_LOG("attempting to take stackshot with thread group flag");
1353	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1354		parse_thread_group_stackshot(ssbuf, sslen);
1355	});
1356}
1357
1358T_DECL(compactinfo, "test compactinfo inclusion", T_META_TAG_VM_PREFERRED)
1359{
1360	struct scenario scenario = {
1361		.name = "compactinfo",
1362		.target_pid = getpid(),
1363		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_SAVE_DYLD_COMPACTINFO
1364				| STACKSHOT_KCDATA_FORMAT),
1365	};
1366
1367	T_LOG("attempting to take stackshot with compactinfo flag");
1368	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1369		parse_stackshot(PARSE_STACKSHOT_COMPACTINFO | PARSE_STACKSHOT_TARGETPID, ssbuf, sslen, nil);
1370	});
1371}
1372
1373T_DECL(suspendinfo, "test task suspend info inclusion", T_META_TAG_VM_PREFERRED)
1374{
1375	struct scenario scenario = {
1376		.name = "suspendinfo",
1377		.target_pid = getpid(),
1378		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
1379	};
1380
1381	T_LOG("attempting to take stackshot with suspendinfo flag");
1382	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1383		parse_stackshot(PARSE_STACKSHOT_SUSPENDINFO | PARSE_STACKSHOT_TARGETPID, ssbuf, sslen, nil);
1384	});
1385}
1386
1387static NSMutableSet * find_driverkit_pids(io_registry_entry_t root) {
1388	NSMutableSet * driverkit_pids = [NSMutableSet setWithCapacity:3];
1389	io_registry_entry_t current = IO_OBJECT_NULL;
1390	io_iterator_t iter = IO_OBJECT_NULL;
1391
1392	T_EXPECT_MACH_SUCCESS(IORegistryEntryGetChildIterator(root, kIOServicePlane, &iter), "get registry iterator");
1393
1394	while ((current = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
1395		if (_IOObjectConformsTo(current, "IOUserServer", kIOClassNameOverrideNone)) {
1396			CFMutableDictionaryRef cfProperties = NULL;
1397			NSMutableDictionary * properties;
1398			NSString * client_creator_info;
1399			NSArray<NSString *> *creator_info_array;
1400			pid_t pid;
1401
1402			T_QUIET; T_EXPECT_MACH_SUCCESS(IORegistryEntryCreateCFProperties(current, &cfProperties, kCFAllocatorDefault, kNilOptions), "get properties");
1403			properties = CFBridgingRelease(cfProperties);
1404			T_QUIET; T_ASSERT_NOTNULL(properties, "properties is not null");
1405			client_creator_info = properties[@kIOUserClientCreatorKey];
1406			creator_info_array = [client_creator_info componentsSeparatedByString:@","];
1407			if ([creator_info_array[0] hasPrefix:@"pid"]) {
1408				NSArray<NSString *> *pid_info = [creator_info_array[0] componentsSeparatedByString:@" "];
1409				T_QUIET; T_ASSERT_EQ(pid_info.count, 2UL, "Get pid info components from %s", creator_info_array[0].UTF8String);
1410				pid = pid_info[1].intValue;
1411			} else {
1412				T_ASSERT_FAIL("No pid info in client creator info: %s", client_creator_info.UTF8String);
1413			}
1414			T_LOG("Found driver pid %d", pid);
1415			[driverkit_pids addObject:[NSNumber numberWithInt:pid]];
1416		} else {
1417			[driverkit_pids unionSet:find_driverkit_pids(current)];
1418		}
1419		IOObjectRelease(current);
1420	}
1421
1422	IOObjectRelease(iter);
1423	return driverkit_pids;
1424}
1425
1426T_DECL(driverkit, "test driverkit inclusion", T_META_TAG_VM_PREFERRED)
1427{
1428	struct scenario scenario = {
1429		.name = "driverkit",
1430		.target_kernel = true,
1431		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT
1432			    | STACKSHOT_INCLUDE_DRIVER_THREADS_IN_KERNEL),
1433	};
1434
1435	io_registry_entry_t root = IORegistryGetRootEntry(kIOMainPortDefault);
1436	NSMutableSet * driverkit_pids = find_driverkit_pids(root);
1437	IOObjectRelease(root);
1438
1439	T_LOG("expecting to find %lu driverkit processes", [driverkit_pids count]);
1440	T_LOG("attempting to take stackshot with STACKSHOT_INCLUDE_DRIVER_THREADS_IN_KERNEL flag");
1441	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1442		parse_stackshot(PARSE_STACKSHOT_DRIVERKIT | PARSE_STACKSHOT_TARGETPID, ssbuf, sslen, @{
1443			driverkit_found_key: ^(pid_t pid) {
1444				[driverkit_pids removeObject:[NSNumber numberWithInt:pid]];
1445		}});
1446	});
1447
1448	T_EXPECT_EQ([driverkit_pids count], (NSUInteger)0, "found expected number of driverkit processes");
1449}
1450
1451static void
1452parse_page_table_asid_stackshot(void **ssbuf, size_t sslen)
1453{
1454	bool seen_asid = false;
1455	bool seen_page_table_snapshot = false;
1456	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
1457	T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT,
1458			"buffer provided is a stackshot");
1459
1460	iter = kcdata_iter_next(iter);
1461	KCDATA_ITER_FOREACH(iter) {
1462		switch (kcdata_iter_type(iter)) {
1463		case KCDATA_TYPE_ARRAY: {
1464			T_QUIET;
1465			T_ASSERT_TRUE(kcdata_iter_array_valid(iter),
1466					"checked that array is valid");
1467
1468			if (kcdata_iter_array_elem_type(iter) != STACKSHOT_KCTYPE_PAGE_TABLES) {
1469				continue;
1470			}
1471
1472			T_ASSERT_FALSE(seen_page_table_snapshot, "check that we haven't yet seen a page table snapshot");
1473			seen_page_table_snapshot = true;
1474
1475			T_ASSERT_EQ((size_t) kcdata_iter_array_elem_size(iter), sizeof(uint64_t),
1476				"check that each element of the pagetable dump is the expected size");
1477
1478			uint64_t *pt_array = kcdata_iter_payload(iter);
1479			uint32_t elem_count = kcdata_iter_array_elem_count(iter);
1480			uint32_t j;
1481			bool nonzero_tte = false;
1482			for (j = 0; j < elem_count;) {
1483				T_QUIET; T_ASSERT_LE(j + 4, elem_count, "check for valid page table segment header");
1484				uint64_t pa = pt_array[j];
1485				uint64_t num_entries = pt_array[j + 1];
1486				uint64_t start_va = pt_array[j + 2];
1487				uint64_t end_va = pt_array[j + 3];
1488
1489				T_QUIET; T_ASSERT_NE(pa, (uint64_t) 0, "check that the pagetable physical address is non-zero");
1490				T_QUIET; T_ASSERT_EQ(pa % (num_entries * sizeof(uint64_t)), (uint64_t) 0, "check that the pagetable physical address is correctly aligned");
1491				T_QUIET; T_ASSERT_NE(num_entries, (uint64_t) 0, "check that a pagetable region has more than 0 entries");
1492				T_QUIET; T_ASSERT_LE(j + 4 + num_entries, (uint64_t) elem_count, "check for sufficient space in page table array");
1493				T_QUIET; T_ASSERT_GT(end_va, start_va, "check for valid VA bounds in page table segment header");
1494
1495				for (uint32_t k = j + 4; k < (j + 4 + num_entries); ++k) {
1496					if (pt_array[k] != 0) {
1497						nonzero_tte = true;
1498						T_QUIET; T_ASSERT_EQ((pt_array[k] >> 48) & 0xf, (uint64_t) 0, "check that bits[48:51] of arm64 TTE are clear");
1499						// L0-L2 table and non-compressed L3 block entries should always have bit 1 set; assumes L0-L2 blocks will not be used outside the kernel
1500						bool table = ((pt_array[k] & 0x2) != 0);
1501						if (table) {
1502							T_QUIET; T_ASSERT_NE(pt_array[k] & ((1ULL << 48) - 1) & ~((1ULL << 12) - 1), (uint64_t) 0, "check that arm64 TTE physical address is non-zero");
1503						} else { // should be a compressed PTE
1504							T_QUIET; T_ASSERT_NE(pt_array[k] & 0xC000000000000000ULL, (uint64_t) 0, "check that compressed PTE has at least one of bits [63:62] set");
1505							T_QUIET; T_ASSERT_EQ(pt_array[k] & ~0xC000000000000000ULL, (uint64_t) 0, "check that compressed PTE has no other bits besides [63:62] set");
1506						}
1507					}
1508				}
1509
1510				j += (4 + num_entries);
1511			}
1512			T_ASSERT_TRUE(nonzero_tte, "check that we saw at least one non-empty TTE");
1513			T_ASSERT_EQ(j, elem_count, "check that page table dump size matches extent of last header");
1514			break;
1515		}
1516		case STACKSHOT_KCTYPE_ASID: {
1517			T_ASSERT_FALSE(seen_asid, "check that we haven't yet seen an ASID");
1518			seen_asid = true;
1519		}
1520		}
1521	}
1522	T_ASSERT_TRUE(seen_page_table_snapshot, "check that we have seen a page table snapshot");
1523	T_ASSERT_TRUE(seen_asid, "check that we have seen an ASID");
1524}
1525
1526T_DECL(dump_page_tables, "test stackshot page table dumping support", T_META_TAG_VM_PREFERRED)
1527{
1528	struct scenario scenario = {
1529		.name = "asid-page-tables",
1530		.flags = (STACKSHOT_KCDATA_FORMAT | STACKSHOT_ASID | STACKSHOT_PAGE_TABLES),
1531		.size_hint = (9ull << 20), // 9 MB
1532		.target_pid = getpid(),
1533		.maybe_unsupported = true,
1534		.maybe_enomem = true,
1535	};
1536
1537	T_LOG("attempting to take stackshot with ASID and page table flags");
1538	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1539		parse_page_table_asid_stackshot(ssbuf, sslen);
1540	});
1541}
1542
1543static void stackshot_verify_current_proc_uuid_info(void **ssbuf, size_t sslen, uint64_t expected_offset, const struct proc_uniqidentifierinfo *proc_info_data)
1544{
1545	const uuid_t *current_uuid = (const uuid_t *)(&proc_info_data->p_uuid);
1546
1547	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
1548	T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT, "buffer provided is a stackshot");
1549
1550	iter = kcdata_iter_next(iter);
1551
1552	KCDATA_ITER_FOREACH(iter) {
1553		switch (kcdata_iter_type(iter)) {
1554			case KCDATA_TYPE_ARRAY: {
1555				T_QUIET; T_ASSERT_TRUE(kcdata_iter_array_valid(iter), "checked that array is valid");
1556				if (kcdata_iter_array_elem_type(iter) == KCDATA_TYPE_LIBRARY_LOADINFO64) {
1557					struct user64_dyld_uuid_info *info = (struct user64_dyld_uuid_info *) kcdata_iter_payload(iter);
1558					if (uuid_compare(*current_uuid, info->imageUUID) == 0) {
1559						T_ASSERT_EQ(expected_offset, info->imageLoadAddress, "found matching UUID with matching binary offset");
1560						return;
1561					}
1562				} else if (kcdata_iter_array_elem_type(iter) == KCDATA_TYPE_LIBRARY_LOADINFO) {
1563					struct user32_dyld_uuid_info *info = (struct user32_dyld_uuid_info *) kcdata_iter_payload(iter);
1564					if (uuid_compare(*current_uuid, info->imageUUID) == 0) {
1565						T_ASSERT_EQ(expected_offset, ((uint64_t) info->imageLoadAddress),  "found matching UUID with matching binary offset");
1566						return;
1567					}
1568				}
1569				break;
1570			}
1571			default:
1572				break;
1573		}
1574	}
1575
1576	T_FAIL("failed to find matching UUID in stackshot data");
1577}
1578
1579T_DECL(translated,
1580    "tests translated bit is set correctly",
1581    T_META_TAG_VM_PREFERRED,
1582    T_META_ENABLED(false /* rdar://133956022 */))
1583{
1584#if !(TARGET_OS_OSX && TARGET_CPU_ARM64)
1585	T_SKIP("Only valid on Apple silicon Macs")
1586#endif
1587	// Get path of stackshot_translated_child helper binary
1588	char path[PATH_MAX];
1589	uint32_t path_size = sizeof(path);
1590	T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
1591	char* binary_name = strrchr(path, '/');
1592	if (binary_name) binary_name++;
1593	T_QUIET; T_ASSERT_NOTNULL(binary_name, "Find basename in path '%s'", path);
1594	strlcpy(binary_name, "stackshot_translated_child", path_size - (binary_name - path));
1595	char *args[] = { path, NULL };
1596
1597	dispatch_source_t child_sig_src;
1598	dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
1599	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "exec child semaphore");
1600
1601	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
1602	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
1603
1604	signal(SIGUSR1, SIG_IGN);
1605	child_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
1606	T_QUIET; T_ASSERT_NOTNULL(child_sig_src, "dispatch_source_create (child_sig_src)");
1607
1608	dispatch_source_set_event_handler(child_sig_src, ^{ dispatch_semaphore_signal(child_ready_sem); });
1609	dispatch_activate(child_sig_src);
1610
1611	// Spawn child
1612	pid_t pid;
1613	T_LOG("spawning translated child");
1614	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawn(&pid, args[0], NULL, NULL, args, NULL), "spawned process '%s' with PID %d", args[0], pid);
1615
1616	// Wait for the the child to spawn up
1617	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
1618
1619	// Make sure the child is running and is translated
1620	int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1621	struct kinfo_proc process_info;
1622	size_t bufsize = sizeof(process_info);
1623	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &process_info, &bufsize, NULL, 0), "get translated child process info");
1624	T_QUIET; T_ASSERT_GT(bufsize, (size_t)0, "process info is not empty");
1625	T_QUIET; T_ASSERT_TRUE((process_info.kp_proc.p_flag & P_TRANSLATED), "KERN_PROC_PID reports child is translated");
1626
1627	T_LOG("capturing stackshot");
1628
1629	struct scenario scenario = {
1630		.name = "translated",
1631		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
1632				  | STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
1633	};
1634
1635	take_stackshot(&scenario, true, ^( void *ssbuf, size_t sslen) {
1636		parse_stackshot(PARSE_STACKSHOT_TRANSLATED, ssbuf, sslen, @{translated_child_pid_key: @(pid)});
1637	});
1638
1639    // Kill the child
1640    int status;
1641    T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(pid, SIGTERM), "kill translated child");
1642    T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on translated child");
1643
1644}
1645
1646T_DECL(proc_uuid_info, "tests that the main binary UUID for a proc is always populated", T_META_TAG_VM_PREFERRED)
1647{
1648	struct proc_uniqidentifierinfo proc_info_data = { };
1649	mach_msg_type_number_t      count;
1650	kern_return_t               kernel_status;
1651	task_dyld_info_data_t       task_dyld_info;
1652	struct dyld_all_image_infos *target_infos;
1653	int retval;
1654	bool found_image_in_image_infos = false;
1655	uint64_t expected_mach_header_offset = 0;
1656
1657	/* Find the UUID of our main binary */
1658	retval = proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO, 0, &proc_info_data, sizeof(proc_info_data));
1659	T_QUIET; T_EXPECT_POSIX_SUCCESS(retval, "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO");
1660	T_QUIET; T_ASSERT_EQ_INT(retval, (int) sizeof(proc_info_data), "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO returned data");
1661
1662	uuid_string_t str = {};
1663	uuid_unparse(*(uuid_t*)&proc_info_data.p_uuid, str);
1664	T_LOG("Found current UUID is %s", str);
1665
1666	/* Find the location of the dyld image info metadata */
1667	count = TASK_DYLD_INFO_COUNT;
1668	kernel_status = task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count);
1669	T_QUIET; T_ASSERT_EQ(kernel_status, KERN_SUCCESS, "retrieve task_info for TASK_DYLD_INFO");
1670
1671	target_infos = (struct dyld_all_image_infos *)task_dyld_info.all_image_info_addr;
1672
1673	/* Find our binary in the dyld image info array */
1674	for (int i = 0; i < (int) target_infos->uuidArrayCount; i++) {
1675		if (uuid_compare(target_infos->uuidArray[i].imageUUID, *(uuid_t*)&proc_info_data.p_uuid) == 0) {
1676			expected_mach_header_offset = (uint64_t) target_infos->uuidArray[i].imageLoadAddress;
1677			found_image_in_image_infos = true;
1678		}
1679	}
1680
1681	T_ASSERT_TRUE(found_image_in_image_infos, "found binary image in dyld image info list");
1682
1683	/* Overwrite the dyld image info data so the kernel has to fallback to the UUID stored in the proc structure */
1684	target_infos->uuidArrayCount = 0;
1685
1686	struct scenario scenario = {
1687		.name = "proc_uuid_info",
1688		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
1689		.target_pid = getpid(),
1690	};
1691
1692	T_LOG("attempting to take stackshot for current PID");
1693	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1694		stackshot_verify_current_proc_uuid_info(ssbuf, sslen, expected_mach_header_offset, &proc_info_data);
1695	});
1696}
1697
1698T_DECL(cseg_waitinfo, "test that threads stuck in the compressor report correct waitinfo", T_META_TAG_VM_PREFERRED)
1699{
1700	struct scenario scenario = {
1701		.name = "cseg_waitinfo",
1702		.quiet = false,
1703		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
1704	};
1705	__block uint64_t thread_id = 0;
1706
1707	dispatch_queue_t dq = dispatch_queue_create("com.apple.stackshot.cseg_waitinfo", NULL);
1708	dispatch_semaphore_t child_ok = dispatch_semaphore_create(0);
1709
1710	dispatch_async(dq, ^{
1711		pthread_threadid_np(NULL, &thread_id);
1712		dispatch_semaphore_signal(child_ok);
1713		int val = 1;
1714		T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.cseg_wedge_thread", NULL, NULL, &val, sizeof(val)), "wedge child thread");
1715	});
1716
1717	dispatch_semaphore_wait(child_ok, DISPATCH_TIME_FOREVER);
1718	sleep(1);
1719
1720	T_LOG("taking stackshot");
1721	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1722		int val = 1;
1723		T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.cseg_unwedge_thread", NULL, NULL, &val, sizeof(val)), "unwedge child thread");
1724		parse_stackshot(PARSE_STACKSHOT_WAITINFO_CSEG, ssbuf, sslen, @{cseg_expected_threadid_key: @(thread_id)});
1725	});
1726}
1727
1728static void
1729srp_send(
1730	mach_port_t send_port,
1731	mach_port_t reply_port,
1732	mach_port_t msg_port)
1733{
1734	kern_return_t ret = 0;
1735
1736	struct test_msg {
1737		mach_msg_header_t header;
1738		mach_msg_body_t body;
1739		mach_msg_port_descriptor_t port_descriptor;
1740	};
1741	struct test_msg send_msg = {
1742		.header = {
1743			.msgh_remote_port = send_port,
1744			.msgh_local_port  = reply_port,
1745			.msgh_bits        = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_COPY_SEND,
1746	    reply_port ? MACH_MSG_TYPE_MAKE_SEND_ONCE : 0,
1747	    MACH_MSG_TYPE_MOVE_SEND,
1748	    MACH_MSGH_BITS_COMPLEX),
1749			.msgh_id          = 0x100,
1750			.msgh_size        = sizeof(send_msg),
1751		},
1752		.body = {
1753			.msgh_descriptor_count = 1,
1754		},
1755		.port_descriptor = {
1756			.name        = msg_port,
1757			.disposition = MACH_MSG_TYPE_MOVE_RECEIVE,
1758			.type        = MACH_MSG_PORT_DESCRIPTOR,
1759		},
1760	};
1761
1762	if (msg_port == MACH_PORT_NULL) {
1763		send_msg.body.msgh_descriptor_count = 0;
1764	}
1765
1766	ret = mach_msg(&(send_msg.header),
1767	    MACH_SEND_MSG |
1768	    MACH_SEND_TIMEOUT |
1769	    MACH_SEND_OVERRIDE,
1770	    send_msg.header.msgh_size,
1771	    0,
1772	    MACH_PORT_NULL,
1773	    10000,
1774	    0);
1775
1776	T_ASSERT_MACH_SUCCESS(ret, "client mach_msg");
1777}
1778
1779T_HELPER_DECL(srp_client,
1780    "Client used for the special_reply_port test")
1781{
1782	pid_t ppid = getppid();
1783	dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
1784	dispatch_queue_t dq = dispatch_queue_create("client_signalqueue", NULL);
1785	dispatch_source_t sig_src;
1786
1787	mach_msg_return_t mr;
1788	mach_port_t service_port;
1789	mach_port_t conn_port;
1790	mach_port_t special_reply_port;
1791	mach_port_options_t opts = {
1792		.flags = MPO_INSERT_SEND_RIGHT,
1793	};
1794
1795	signal(SIGUSR1, SIG_IGN);
1796	sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dq);
1797
1798	dispatch_source_set_event_handler(sig_src, ^{
1799			dispatch_semaphore_signal(can_continue);
1800	});
1801	dispatch_activate(sig_src);
1802
1803	/* lookup the mach service port for the parent */
1804	kern_return_t kr = bootstrap_look_up(bootstrap_port,
1805	    SRP_SERVICE_NAME, &service_port);
1806	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "client bootstrap_look_up");
1807
1808	/* create the send-once right (special reply port) and message to send to the server */
1809	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &conn_port);
1810	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
1811
1812	special_reply_port = thread_get_special_reply_port();
1813	T_QUIET; T_ASSERT_TRUE(MACH_PORT_VALID(special_reply_port), "get_thread_special_reply_port");
1814
1815	/* send the message with the special reply port */
1816	srp_send(service_port, special_reply_port, conn_port);
1817
1818	/* signal the parent to continue */
1819	kill(ppid, SIGUSR1);
1820
1821	struct {
1822		mach_msg_header_t header;
1823		mach_msg_body_t body;
1824		mach_msg_port_descriptor_t port_descriptor;
1825	} rcv_msg = {
1826		.header =
1827		{
1828			.msgh_remote_port = MACH_PORT_NULL,
1829			.msgh_local_port  = special_reply_port,
1830			.msgh_size        = sizeof(rcv_msg),
1831		},
1832	};
1833
1834	/* wait on the reply from the parent (that we will never receive) */
1835	mr = mach_msg(&(rcv_msg.header),
1836			(MACH_RCV_MSG | MACH_RCV_SYNC_WAIT),
1837			0,
1838			rcv_msg.header.msgh_size,
1839			special_reply_port,
1840			MACH_MSG_TIMEOUT_NONE,
1841			service_port);
1842
1843	/* not expected to execute as parent will SIGKILL client... */
1844	T_LOG("client process exiting after sending message to parent (server)");
1845}
1846
1847enum srp_test_type {
1848	SRP_TEST_THREAD,	/* expect waiter on current thread */
1849	SRP_TEST_PID,		/* expect waiter on current PID */
1850	SRP_TEST_EITHER,	/* waiter could be on either */
1851};
1852
1853static void
1854check_srp_test(const char *name, enum srp_test_type ty)
1855{
1856	struct scenario scenario = {
1857		.name = name,
1858		.quiet = false,
1859		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
1860	};
1861	uint64_t thread_id = 0;
1862	pthread_threadid_np(NULL, &thread_id);
1863	if (ty == SRP_TEST_THREAD) {
1864		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1865			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1866					@{srp_expected_threadid_key: @(thread_id)});
1867		});
1868	} else if (ty == SRP_TEST_PID) {
1869		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1870			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1871					@{srp_expected_pid_key: @(getpid())});
1872		});
1873	} else {
1874		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1875			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1876					@{srp_expected_pid_key: @(getpid()), srp_expected_threadid_key: @(thread_id)});
1877		});
1878	}
1879
1880}
1881
1882
1883/*
1884 * Tests the stackshot wait info plumbing for synchronous IPC that doesn't use kevent on the server.
1885 *
1886 * (part 1): tests the scenario where a client sends a request that includes a special reply port
1887 *           to a server that doesn't receive the message and doesn't copy the send-once right
1888 *           into its address space as a result. for this case the special reply port is enqueued
1889 *           in a port and we check which task has that receive right and use that info. (rdar://60440338)
1890 * (part 2): tests the scenario where a client sends a request that includes a special reply port
1891 *           to a server that receives the message and copies in the send-once right, but doesn't
1892 *           reply to the client. for this case the special reply port is copied out and the kernel
1893 *           stashes the info about which task copied out the send once right. (rdar://60440592)
1894 * (part 3): tests the same as part 2, but uses kevents, which allow for
1895 *           priority inheritance
1896 */
1897T_DECL(special_reply_port, "test that tasks using special reply ports have correct waitinfo", T_META_TAG_VM_PREFERRED)
1898{
1899	dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
1900	dispatch_queue_t dq = dispatch_queue_create("signalqueue", NULL);
1901	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
1902	dispatch_source_t sig_src;
1903	char path[PATH_MAX];
1904	uint32_t path_size = sizeof(path);
1905	T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
1906	char *client_args[] = { path, "-n", "srp_client", NULL };
1907	pid_t client_pid;
1908	int sp_ret;
1909	kern_return_t kr;
1910	mach_port_t port;
1911
1912	/* setup the signal handler in the parent (server) */
1913	T_LOG("setup sig handlers");
1914	signal(SIGUSR1, SIG_IGN);
1915	sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dq);
1916
1917	dispatch_source_set_event_handler(sig_src, ^{
1918			dispatch_semaphore_signal(can_continue);
1919	});
1920	dispatch_activate(sig_src);
1921
1922	/* register with the mach service name so the client can lookup and send a message to the parent (server) */
1923	T_LOG("Server about to check in");
1924	kr = bootstrap_check_in(bootstrap_port, SRP_SERVICE_NAME, &port);
1925	T_ASSERT_MACH_SUCCESS(kr, "server bootstrap_check_in");
1926
1927	T_LOG("Launching client");
1928	sp_ret = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
1929	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", client_args[0], client_pid);
1930	T_LOG("Spawned client as PID %d", client_pid);
1931
1932	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
1933	T_LOG("Ready to take stackshot, but waiting 1s for the coast to clear");
1934
1935	/*
1936	 * can_continue indicates the client has signaled us, but we want to make
1937	 * sure they've actually blocked sending their mach message.  It's cheesy, but
1938	 * sleep() works for this.
1939	 */
1940	sleep(1);
1941
1942	/*
1943	 * take the stackshot without calling receive to verify that the stackshot wait
1944	 * info shows our (the server) thread for the scenario where the server has yet to
1945	 * receive the message.
1946	 */
1947	T_LOG("Taking stackshot for part 1 coverage");
1948	check_srp_test("srp", SRP_TEST_THREAD);
1949
1950	/*
1951	 * receive the message from the client (which should copy the send once right into
1952	 * our address space).
1953	 */
1954	struct {
1955		mach_msg_header_t header;
1956		mach_msg_body_t body;
1957		mach_msg_port_descriptor_t port_descriptor;
1958	} rcv_msg = {
1959		.header =
1960		{
1961			.msgh_remote_port = MACH_PORT_NULL,
1962			.msgh_local_port  = port,
1963			.msgh_size        = sizeof(rcv_msg),
1964		},
1965	};
1966
1967	T_LOG("server: starting sync receive\n");
1968
1969	mach_msg_return_t mr;
1970	mr = mach_msg(&(rcv_msg.header),
1971			(MACH_RCV_MSG | MACH_RCV_TIMEOUT),
1972			0,
1973			4096,
1974			port,
1975			10000,
1976			MACH_PORT_NULL);
1977	T_QUIET; T_ASSERT_MACH_SUCCESS(mr, "mach_msg() recieve of message from client");
1978
1979	/*
1980	 * take the stackshot to verify that the stackshot wait info shows our (the server) PID
1981	 * for the scenario where the server has received the message and copied in the send-once right.
1982	 */
1983	T_LOG("Taking stackshot for part 2 coverage");
1984	check_srp_test("srp", SRP_TEST_PID);
1985
1986	/* cleanup - kill the client */
1987	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
1988	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
1989
1990	// do it again, but using kevents
1991	T_LOG("Launching client");
1992	sp_ret = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
1993	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", client_args[0], client_pid);
1994	T_LOG("Spawned client as PID %d", client_pid);
1995
1996	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
1997	T_LOG("Ready to take stackshot, but waiting 1s for the coast to clear");
1998
1999	/*
2000	 * can_continue indicates the client has signaled us, but we want to make
2001	 * sure they've actually blocked sending their mach message.  It's cheesy, but
2002	 * sleep() works for this.
2003	 */
2004	sleep(1);
2005
2006	dispatch_mach_t dispatch_mach = dispatch_mach_create(SRP_SERVICE_NAME, machdq,
2007	    ^(dispatch_mach_reason_t reason,
2008	      dispatch_mach_msg_t message,
2009	      mach_error_t error __unused) {
2010		switch (reason) {
2011		case DISPATCH_MACH_MESSAGE_RECEIVED: {
2012			size_t size = 0;
2013			mach_msg_header_t *msg __unused = dispatch_mach_msg_get_msg(message, &size);
2014			T_LOG("server: recieved %ld byte message", size);
2015			check_srp_test("turnstile_port_thread", SRP_TEST_THREAD);
2016			T_LOG("server: letting client go");
2017			// drop the message on the ground, we'll kill the client later
2018			dispatch_semaphore_signal(can_continue);
2019			break;
2020		}
2021		default:
2022			break;
2023		}
2024	});
2025
2026	dispatch_mach_connect(dispatch_mach, port, MACH_PORT_NULL, NULL);
2027
2028	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
2029
2030	/* cleanup - kill the client */
2031	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
2032	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
2033}
2034
2035T_HELPER_DECL(throtlled_sp_client,
2036	"client that uses a connection port to send a message to a server")
2037{
2038	mach_port_t conn_port, service_port, reply_port, *stash;
2039	mach_msg_type_number_t stash_cnt = 0;
2040
2041	kern_return_t kr = mach_ports_lookup(mach_task_self(), &stash, &stash_cnt);
2042	T_ASSERT_MACH_SUCCESS(kr, "mach_ports_lookup");
2043
2044	service_port = stash[0];
2045	T_ASSERT_TRUE(MACH_PORT_VALID(service_port), "valid service port");
2046	mig_deallocate((vm_address_t)stash, stash_cnt * sizeof(stash[0]));
2047
2048	mach_port_options_t opts = {
2049		.flags = MPO_INSERT_SEND_RIGHT
2050			| MPO_CONNECTION_PORT,
2051		.service_port_name = service_port,
2052	};
2053
2054	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &conn_port);
2055	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
2056
2057	mach_port_options_t opts2 = {
2058		.flags = MPO_REPLY_PORT
2059	};
2060	kr = mach_port_construct(mach_task_self(), &opts2, 0ull, &reply_port);
2061	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
2062
2063	/* XPC-like check-in message */
2064	struct {
2065		mach_msg_header_t header;
2066		mach_msg_port_descriptor_t recvp;
2067		mach_msg_port_descriptor_t sendp;
2068	} checkin_message = {
2069		.header =
2070		{
2071			.msgh_remote_port = service_port,
2072			.msgh_local_port = MACH_PORT_NULL,
2073			.msgh_size = sizeof(checkin_message),
2074			.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0),
2075		},
2076		.recvp =
2077		{
2078			.type = MACH_MSG_PORT_DESCRIPTOR,
2079			.name = conn_port,
2080			.disposition = MACH_MSG_TYPE_MOVE_RECEIVE,
2081		},
2082		.sendp =
2083		{
2084			.type = MACH_MSG_PORT_DESCRIPTOR,
2085			.name = reply_port,
2086			.disposition = MACH_MSG_TYPE_MAKE_SEND,
2087		}
2088	};
2089	dispatch_mach_msg_t dmsg = dispatch_mach_msg_create((mach_msg_header_t *)&checkin_message, sizeof(checkin_message),
2090		DISPATCH_MACH_MSG_DESTRUCTOR_DEFAULT, NULL);
2091
2092	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
2093	dispatch_mach_t dchannel = dispatch_mach_create(THROTTLED_SERVICE_NAME, machdq,
2094		^(dispatch_mach_reason_t reason,
2095	      dispatch_mach_msg_t message __unused,
2096	      mach_error_t error __unused) {
2097		switch (reason) {
2098			case DISPATCH_MACH_CONNECTED:
2099				T_LOG("mach channel connected");
2100				break;
2101			case DISPATCH_MACH_MESSAGE_SENT:
2102				T_LOG("sent mach message");
2103				break;
2104			default:
2105				T_ASSERT_FAIL("Unexpected reply to channel reason %lu", reason);
2106		}
2107	});
2108	dispatch_mach_connect(dchannel, reply_port, service_port, dmsg);
2109	dispatch_release(dmsg);
2110
2111	struct {
2112		mach_msg_header_t header;
2113		uint64_t request_id;
2114	} request = {
2115		.header =
2116		{
2117			.msgh_size = sizeof(request),
2118			.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE),
2119		},
2120		.request_id = 1,
2121	};
2122	dispatch_mach_msg_t dmsg2 = dispatch_mach_msg_create((mach_msg_header_t *)&request, sizeof(request),
2123		DISPATCH_MACH_MSG_DESTRUCTOR_DEFAULT, NULL);
2124
2125	dispatch_mach_reason_t reason;
2126	mach_error_t error;
2127
2128	/* send the check-in message and the request message */
2129	dispatch_mach_msg_t dreply = dispatch_mach_send_with_result_and_wait_for_reply(dchannel,
2130			dmsg2, 0, DISPATCH_MACH_SEND_DEFAULT, &reason, &error);
2131	dispatch_release(dmsg2);
2132
2133	/* not expected to execute as parent will SIGKILL client */
2134	T_ASSERT_FAIL("client process exiting after receiving %s reply", dreply ? "non-null" : "null");
2135}
2136
2137static void
2138check_throttled_sp(const char *test_name, uint64_t context, bool is_throttled)
2139{
2140	struct scenario scenario = {
2141		.name = test_name,
2142		.quiet = false,
2143		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
2144	};
2145
2146	T_LOG("taking stackshot %s", test_name);
2147	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2148		parse_stackshot(PARSE_STACKSHOT_THROTTLED_SP, ssbuf, sslen,
2149					@{sp_throttled_expected_ctxt_key: @(context),
2150					sp_throttled_expect_flag: @(is_throttled)});
2151	});
2152}
2153
2154/* Take stackshot when a client is blocked on the service port of a process, in the scenario when
2155 * the process with the receive right for the service port is:
2156 *     (a) Monitoring the service port using kevents
2157 *     (b) Not monitoring the service port
2158 */
2159T_DECL(throttled_sp,
2160	"test that service port throttled flag is propagated to the stackshot correctly", T_META_TAG_VM_PREFERRED)
2161{
2162	mach_port_t service_port;
2163	__block dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
2164
2165	char path[PATH_MAX];
2166	uint32_t path_size = sizeof(path);
2167	T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
2168	char *client_args[] = { path, "-n", "throtlled_sp_client", NULL };
2169
2170	__block	uint64_t thread_id = 0;
2171	pid_t client_pid;
2172	int mark_throttled;
2173
2174	struct mach_service_port_info sp_info = {};
2175	strcpy(sp_info.mspi_string_name, THROTTLED_SERVICE_NAME);
2176	sp_info.mspi_domain_type = (uint8_t)1;
2177	kern_return_t kr;
2178
2179	mach_port_options_t opts = {
2180		.flags = MPO_SERVICE_PORT | MPO_INSERT_SEND_RIGHT | MPO_CONTEXT_AS_GUARD | MPO_STRICT | MPO_TEMPOWNER,
2181		.service_port_info = &sp_info,
2182	};
2183
2184	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &service_port);
2185	T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct %u", service_port);
2186
2187	/* Setup a dispatch source to monitor the service port similar to how launchd does. */
2188	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
2189	dispatch_source_t mach_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, service_port,
2190		DISPATCH_MACH_RECV_SYNC_PEEK, machdq);
2191	dispatch_source_set_event_handler(mach_src, ^{
2192		pthread_threadid_np(NULL, &thread_id);
2193		dispatch_semaphore_signal(can_continue);
2194	});
2195	dispatch_activate(mach_src);
2196
2197	/* Stash the port in task to make sure child also gets it */
2198	kr = mach_ports_register(mach_task_self(), &service_port, 1);
2199	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_ports_register service port");
2200
2201	mark_throttled = 1;
2202	kr = mach_port_set_attributes(mach_task_self(), service_port, MACH_PORT_SERVICE_THROTTLED, (mach_port_info_t)(&mark_throttled),
2203	           MACH_PORT_SERVICE_THROTTLED_COUNT);
2204	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mark service port as throttled");
2205
2206	int rc = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
2207	T_QUIET; T_ASSERT_POSIX_ZERO(rc, "spawned process '%s' with PID %d", client_args[0], client_pid);
2208	T_LOG("Spawned client as PID %d", client_pid);
2209
2210	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
2211
2212	/* The service port has received the check-in message. Take stackshot for scenario (a). */
2213	check_throttled_sp("throttled_service_port_monitored", thread_id, true);
2214
2215	/* This simulates a throttled spawn when the service port is no longer monitored. */
2216	dispatch_source_cancel(mach_src);
2217
2218	/* Take stackshot for scenario (b) */
2219	check_throttled_sp("throttled_service_port_unmonitored", (uint64_t)getpid(), true);
2220
2221	mark_throttled = 0;
2222	kr = mach_port_set_attributes(mach_task_self(), service_port, MACH_PORT_SERVICE_THROTTLED, (mach_port_info_t)(&mark_throttled),
2223	           MACH_PORT_SERVICE_THROTTLED_COUNT);
2224	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "unmark service port as throttled");
2225
2226	/* Throttled flag should not be set when the port is not throttled. */
2227	check_throttled_sp("unthrottled_service_port_unmonitored", (uint64_t)getpid(), false);
2228
2229	/* cleanup - kill the client */
2230	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
2231	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
2232}
2233
2234
2235char *const clpcctrl_path = "/usr/local/bin/clpcctrl";
2236
2237static void
2238run_clpcctrl(char *const argv[]) {
2239	posix_spawnattr_t sattr;
2240	pid_t pid;
2241	int wstatus;
2242
2243	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawn(&pid, argv[0], NULL, NULL, argv, NULL), "spawn clpcctrl");
2244	T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &wstatus, 0), "wait for clpcctrl");
2245	T_QUIET; T_ASSERT_TRUE(WIFEXITED(wstatus), "clpcctrl exited normally");
2246	T_QUIET; T_ASSERT_POSIX_ZERO(WEXITSTATUS(wstatus), "clpcctrl exited successfully");
2247
2248	uint64_t sched_recommended_cores = 1;
2249	size_t sched_recommended_cores_sz = sizeof(uint64_t);
2250	T_QUIET; T_ASSERT_POSIX_SUCCESS(
2251	    sysctlbyname("kern.sched_recommended_cores", &sched_recommended_cores, &sched_recommended_cores_sz, NULL, 0),
2252	    "get kern.sched_recommended_cores");
2253	T_LOG("Recommended cores: 0x%llx", sched_recommended_cores);
2254}
2255
2256static void
2257restore_clpcctrl() {
2258	run_clpcctrl((char *const []) { clpcctrl_path, "-d", NULL });
2259}
2260
2261#define CLUSTER_TYPE_SMP 0
2262#define CLUSTER_TYPE_E 1
2263#define CLUSTER_TYPE_P 2
2264
2265void test_stackshot_cpu_info(void *ssbuf, size_t sslen, int exp_cpus, NSArray *exp_cluster_types) {
2266	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2267	bool seen = false;
2268	int singlethread_override = 0;
2269	size_t singlethread_override_sz = sizeof(singlethread_override);
2270	T_QUIET; T_ASSERT_POSIX_SUCCESS(
2271		sysctlbyname("kern.stackshot_single_thread", &singlethread_override, &singlethread_override_sz, NULL, 0),
2272		"get kern.stackshot_single_thread");
2273	if (singlethread_override) {
2274		T_LOG("skipping cpu count/type check due to single-thread override (kern.stackshot_single_thread=1)");
2275		return;
2276	}
2277
2278	KCDATA_ITER_FOREACH(iter) {
2279		if ((kcdata_iter_type(iter) != KCDATA_TYPE_ARRAY) || (kcdata_iter_array_elem_type(iter) != STACKSHOT_KCTYPE_LATENCY_INFO_CPU)) {
2280			continue;
2281		}
2282
2283		seen = true;
2284
2285		/* Check ncpus */
2286		int ncpus = kcdata_iter_array_elem_count(iter);
2287		if (exp_cpus != -1) {
2288			T_QUIET; T_ASSERT_EQ(exp_cpus, ncpus, "Expected number of CPUs matches number of CPUs used for stackshot");
2289		}
2290
2291		if (exp_cluster_types == nil) {
2292			continue;
2293		}
2294
2295		/* Check cluster types */
2296		struct stackshot_latency_cpu *latencies = (struct stackshot_latency_cpu *) kcdata_iter_payload(iter);
2297		for (int i = 0; i < ncpus; i++) {
2298			NSNumber *cluster_type = [NSNumber numberWithInt:latencies[i].cluster_type];
2299			T_QUIET; T_ASSERT_TRUE([exp_cluster_types containsObject:cluster_type], "Type of CPU cluster in expected CPU cluster types");
2300		}
2301	}
2302
2303	T_QUIET; T_ASSERT_TRUE(seen || !is_development_kernel(), "Seen CPU latency info or is release kernel");
2304}
2305
2306void test_stackshot_with_clpcctrl(char *const name, char *const argv[], int exp_cpus, NSArray *exp_cluster_types) {
2307	T_LOG("Stackshot CLPC scenario %s", name);
2308	run_clpcctrl(argv);
2309	struct scenario scenario = {
2310		.name = name,
2311		.flags = (STACKSHOT_KCDATA_FORMAT | STACKSHOT_SAVE_LOADINFO |
2312			STACKSHOT_THREAD_WAITINFO | STACKSHOT_GET_GLOBAL_MEM_STATS)
2313	};
2314	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2315		parse_stackshot(0, ssbuf, sslen, nil);
2316		test_stackshot_cpu_info(ssbuf, sslen, exp_cpus, exp_cluster_types);
2317	});
2318}
2319
2320T_DECL(core_masks,
2321	"test that stackshot works under various core masks on ARM systems",
2322	T_META_REQUIRES_SYSCTL_EQ("hw.optional.arm64", 1),
2323	T_META_REQUIRES_SYSCTL_NE("kern.kasan.available", 1), /* rdar://115577993 */
2324	XNU_T_META_REQUIRES_DEVELOPMENT_KERNEL,
2325	T_META_REQUIRE_NOT_VIRTUALIZED,
2326	T_META_RUN_CONCURRENTLY(false),
2327	T_META_TAG_VM_NOT_ELIGIBLE,
2328	T_META_ENABLED(!TARGET_OS_VISION)) // disable for visionOS: device may not be stable with many cores masked off (127904530)
2329{
2330	/*
2331	 * Make sure we're not in a release kernel
2332	 * (cannot check with T_META; only one sysctl T_META at a time will work)
2333	 */
2334	if (!is_development_kernel()) {
2335		T_SKIP("test was not run because kernel is release; cannot set core masks");
2336		return;
2337	}
2338
2339	/*
2340	 * rdar://115577993 - CLPC compiles as release in KASAN-variant builds,
2341	 * preventing clpcctrl from working. For now, skip this. (Cannot check
2342	 * with T_META; only one sysctl T_META at a time will work)
2343	 */
2344	int kasan_avail = 0;
2345	size_t kasan_avail_sz = sizeof(kasan_avail);
2346	sysctlbyname("kern.kasan.available", &kasan_avail, &kasan_avail_sz, NULL, 0);
2347	if (kasan_avail) {
2348		T_SKIP("test was not run because kernel is KASAN; cannot set core masks (see rdar://115577993)");
2349		return;
2350	}
2351
2352
2353	T_ATEND(restore_clpcctrl);
2354
2355	/* Test with 1 and 2 CPUs for basic functionality */
2356	test_stackshot_with_clpcctrl(
2357		"core_masks_1cpu", (char *const[]) {clpcctrl_path, "-c", "1", NULL},
2358		1, nil);
2359
2360	test_stackshot_with_clpcctrl(
2361		"core_masks_2cpus", (char *const[]) {clpcctrl_path, "-c", "2", NULL},
2362		2, nil);
2363
2364	/* Check nperflevels to see if we're on an AMP system */
2365	int nperflevels = 1;
2366	size_t nperflevels_sz = sizeof(int);
2367	T_ASSERT_POSIX_SUCCESS(
2368	    sysctlbyname("hw.nperflevels", &nperflevels, &nperflevels_sz, NULL, 0),
2369	    "get hw.nperflevels");
2370	if (nperflevels == 1) {
2371		T_LOG("On SMP system, skipping stackshot core_masks AMP tests");
2372		return;
2373	}
2374
2375	T_QUIET; T_ASSERT_EQ(nperflevels, 2, "nperflevels is 1 or 2");
2376	T_LOG("On AMP system, performing stackshot core_masks AMP tests");
2377
2378	/* Perform AMP tests with different cluster types active */
2379	test_stackshot_with_clpcctrl(
2380		"core_masks_amp_allcpus",
2381		(char *const[]) {clpcctrl_path, "-C", "all", NULL},
2382		-1, @[@CLUSTER_TYPE_E, @CLUSTER_TYPE_P]);
2383
2384	test_stackshot_with_clpcctrl(
2385		"core_masks_amp_ecpus",
2386		(char *const[]) {clpcctrl_path, "-C", "e", NULL},
2387		-1, @[@CLUSTER_TYPE_E]);
2388
2389	test_stackshot_with_clpcctrl(
2390		"core_masks_amp_pcpus",
2391		(char *const[]) {clpcctrl_path, "-C", "p", NULL},
2392		-1, @[@CLUSTER_TYPE_P]);
2393}
2394
2395#pragma mark performance tests
2396
2397#define SHOULD_REUSE_SIZE_HINT 0x01
2398#define SHOULD_USE_DELTA       0x02
2399#define SHOULD_TARGET_SELF     0x04
2400
2401static void
2402stackshot_perf(unsigned int options)
2403{
2404	struct scenario scenario = {
2405		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
2406			| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
2407	};
2408
2409	dt_stat_t size = dt_stat_create("bytes", "size");
2410	dt_stat_time_t duration = dt_stat_time_create("duration");
2411	scenario.timer = duration;
2412
2413	if (options & SHOULD_TARGET_SELF) {
2414		scenario.target_pid = getpid();
2415	}
2416
2417	while (!dt_stat_stable(duration) || !dt_stat_stable(size)) {
2418		__block uint64_t last_time = 0;
2419		__block uint32_t size_hint = 0;
2420		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2421			dt_stat_add(size, (double)sslen);
2422			last_time = stackshot_timestamp(ssbuf, sslen);
2423			size_hint = (uint32_t)sslen;
2424		});
2425		if (options & SHOULD_USE_DELTA) {
2426			scenario.since_timestamp = last_time;
2427			scenario.flags |= STACKSHOT_COLLECT_DELTA_SNAPSHOT;
2428		}
2429		if (options & SHOULD_REUSE_SIZE_HINT) {
2430			scenario.size_hint = size_hint;
2431		}
2432	}
2433
2434	dt_stat_finalize(duration);
2435	dt_stat_finalize(size);
2436}
2437
2438static void
2439stackshot_flag_perf_noclobber(uint64_t flag, char *flagname)
2440{
2441	struct scenario scenario = {
2442		.quiet = true,
2443		.flags = (flag | STACKSHOT_KCDATA_FORMAT),
2444	};
2445
2446	dt_stat_t duration = dt_stat_create("nanoseconds per thread", "%s_duration", flagname);
2447	dt_stat_t size = dt_stat_create("bytes per thread", "%s_size", flagname);
2448	T_LOG("Testing \"%s\" = 0x%" PRIx64, flagname, flag);
2449
2450	while (!dt_stat_stable(duration) || !dt_stat_stable(size)) {
2451		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2452			kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2453			unsigned long no_threads = 0;
2454			mach_timebase_info_data_t timebase = {0, 0};
2455			uint64_t stackshot_duration = 0;
2456			int found = 0;
2457			T_QUIET; T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT, "stackshot buffer");
2458
2459			KCDATA_ITER_FOREACH(iter) {
2460				switch(kcdata_iter_type(iter)) {
2461					case STACKSHOT_KCTYPE_THREAD_SNAPSHOT: {
2462						found |= 1;
2463						no_threads ++;
2464						break;
2465					}
2466					case STACKSHOT_KCTYPE_STACKSHOT_DURATION: {
2467						struct stackshot_duration *ssd = kcdata_iter_payload(iter);
2468						stackshot_duration = ssd->stackshot_duration;
2469						found |= 2;
2470						break;
2471					}
2472					case KCDATA_TYPE_TIMEBASE: {
2473						found |= 4;
2474						mach_timebase_info_data_t *tb = kcdata_iter_payload(iter);
2475						memcpy(&timebase, tb, sizeof(timebase));
2476						break;
2477					}
2478				}
2479			}
2480
2481			T_QUIET; T_ASSERT_EQ(found, 0x7, "found everything needed");
2482
2483			uint64_t ns = (stackshot_duration * timebase.numer) / timebase.denom;
2484			uint64_t per_thread_ns = ns / no_threads;
2485			uint64_t per_thread_size = sslen / no_threads;
2486
2487			dt_stat_add(duration, per_thread_ns);
2488			dt_stat_add(size, per_thread_size);
2489		});
2490	}
2491
2492	dt_stat_finalize(duration);
2493	dt_stat_finalize(size);
2494}
2495
2496static void
2497stackshot_flag_perf(uint64_t flag, char *flagname)
2498{
2499	/*
2500	 * STACKSHOT_NO_IO_STATS disables data collection, so set it for
2501	 * more accurate perfdata collection.
2502	 */
2503	flag |= STACKSHOT_NO_IO_STATS;
2504
2505	stackshot_flag_perf_noclobber(flag, flagname);
2506}
2507
2508
2509T_DECL(flag_perf, "test stackshot performance with different flags set", T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2510{
2511	stackshot_flag_perf_noclobber(STACKSHOT_NO_IO_STATS, "baseline");
2512	stackshot_flag_perf_noclobber(0, "io_stats");
2513
2514	stackshot_flag_perf(STACKSHOT_THREAD_WAITINFO, "thread_waitinfo");
2515	stackshot_flag_perf(STACKSHOT_GET_DQ, "get_dq");
2516	stackshot_flag_perf(STACKSHOT_SAVE_LOADINFO, "save_loadinfo");
2517	stackshot_flag_perf(STACKSHOT_GET_GLOBAL_MEM_STATS, "get_global_mem_stats");
2518	stackshot_flag_perf(STACKSHOT_SAVE_KEXT_LOADINFO, "save_kext_loadinfo");
2519	stackshot_flag_perf(STACKSHOT_SAVE_IMP_DONATION_PIDS, "save_imp_donation_pids");
2520	stackshot_flag_perf(STACKSHOT_ENABLE_BT_FAULTING, "enable_bt_faulting");
2521	stackshot_flag_perf(STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT, "collect_sharedcache_layout");
2522	stackshot_flag_perf(STACKSHOT_ENABLE_UUID_FAULTING, "enable_uuid_faulting");
2523	stackshot_flag_perf(STACKSHOT_THREAD_GROUP, "thread_group");
2524	stackshot_flag_perf(STACKSHOT_SAVE_JETSAM_COALITIONS, "save_jetsam_coalitions");
2525	stackshot_flag_perf(STACKSHOT_INSTRS_CYCLES, "instrs_cycles");
2526	stackshot_flag_perf(STACKSHOT_ASID, "asid");
2527	stackshot_flag_perf(STACKSHOT_EXCLAVES, "all_exclaves");
2528	stackshot_flag_perf(STACKSHOT_EXCLAVES | STACKSHOT_ASID, "all_exclaves_and_asid");
2529	stackshot_flag_perf(STACKSHOT_SKIP_EXCLAVES, "skip_exclaves");
2530}
2531
2532T_DECL(perf_no_size_hint, "test stackshot performance with no size hint",
2533		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2534{
2535	stackshot_perf(0);
2536}
2537
2538T_DECL(perf_size_hint, "test stackshot performance with size hint",
2539		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2540{
2541	stackshot_perf(SHOULD_REUSE_SIZE_HINT);
2542}
2543
2544T_DECL(perf_process, "test stackshot performance targeted at process",
2545		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2546{
2547	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_TARGET_SELF);
2548}
2549
2550T_DECL(perf_delta, "test delta stackshot performance",
2551		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2552{
2553	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA);
2554}
2555
2556T_DECL(perf_delta_no_exclaves, "test delta stackshot performance without Exclaves",
2557	    T_META_REQUIRES_SYSCTL_EQ("kern.exclaves_status", 1),
2558		T_META_REQUIRES_SYSCTL_EQ("kern.exclaves_inspection_status", 1),
2559		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2560{
2561	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA | STACKSHOT_SKIP_EXCLAVES);
2562}
2563
2564T_DECL(perf_delta_process, "test delta stackshot performance targeted at a process",
2565		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2566{
2567	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA | SHOULD_TARGET_SELF);
2568}
2569
2570T_DECL(stackshot_entitlement_report_test, "test stackshot entitlement report", T_META_TAG_VM_PREFERRED)
2571{
2572	int sysctlValue = 1;
2573	T_ASSERT_POSIX_SUCCESS(
2574	    sysctlbyname("debug.stackshot_entitlement_send_batch", NULL, NULL, &sysctlValue, sizeof(sysctlValue)),
2575	    "set debug.stackshot_entitlement_send_batch=1");
2576	// having a way to verify that the coreanalytics event was received would be even better
2577	// See rdar://74197197
2578	T_PASS("entitlement test ran");
2579}
2580
2581static void
2582expect_os_build_version_in_stackshot(void *ssbuf, size_t sslen)
2583{
2584	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2585
2586	bool saw_os_build_version = false;
2587	iter = kcdata_iter_next(iter);
2588
2589	KCDATA_ITER_FOREACH(iter) {
2590		switch (kcdata_iter_type(iter)) {
2591		case STACKSHOT_KCTYPE_OS_BUILD_VERSION:
2592			saw_os_build_version = true;
2593			T_LOG("Found os build version in stackshot: %s", kcdata_iter_payload(iter));
2594			return;
2595
2596		default:
2597			break;
2598		}
2599	}
2600
2601	T_ASSERT_FAIL("didn't see os build version in stackshot");
2602}
2603
2604T_DECL(os_build_version, "test stackshot contains os build version", T_META_TAG_VM_PREFERRED)
2605{
2606
2607	struct scenario scenario = {
2608		.name = "os-build-version",
2609		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
2610	};
2611
2612	T_LOG("attempting to take stackshot with an os build version");
2613	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2614		expect_os_build_version_in_stackshot(ssbuf, sslen);
2615	});
2616}
2617
2618static uint64_t
2619stackshot_timestamp(void *ssbuf, size_t sslen)
2620{
2621	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2622
2623	uint32_t type = kcdata_iter_type(iter);
2624	if (type != KCDATA_BUFFER_BEGIN_STACKSHOT && type != KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT) {
2625		T_ASSERT_FAIL("invalid kcdata type %u", kcdata_iter_type(iter));
2626	}
2627
2628	iter = kcdata_iter_find_type(iter, KCDATA_TYPE_MACH_ABSOLUTE_TIME);
2629	T_QUIET;
2630	T_ASSERT_TRUE(kcdata_iter_valid(iter), "timestamp found in stackshot");
2631
2632	return *(uint64_t *)kcdata_iter_payload(iter);
2633}
2634
2635#define TEST_THREAD_NAME "stackshot_test_thread"
2636
2637static void
2638parse_thread_group_stackshot(void **ssbuf, size_t sslen)
2639{
2640	bool seen_thread_group_snapshot = false;
2641	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2642	T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT,
2643			"buffer provided is a stackshot");
2644
2645	NSMutableSet *thread_groups = [[NSMutableSet alloc] init];
2646
2647	iter = kcdata_iter_next(iter);
2648	KCDATA_ITER_FOREACH(iter) {
2649		switch (kcdata_iter_type(iter)) {
2650		case KCDATA_TYPE_ARRAY: {
2651			T_QUIET;
2652			T_ASSERT_TRUE(kcdata_iter_array_valid(iter),
2653					"checked that array is valid");
2654
2655			if (kcdata_iter_array_elem_type(iter) != STACKSHOT_KCTYPE_THREAD_GROUP_SNAPSHOT) {
2656				continue;
2657			}
2658
2659			seen_thread_group_snapshot = true;
2660
2661			if (kcdata_iter_array_elem_size(iter) >= sizeof(struct thread_group_snapshot_v3)) {
2662				struct thread_group_snapshot_v3 *tgs_array = kcdata_iter_payload(iter);
2663				for (uint32_t j = 0; j < kcdata_iter_array_elem_count(iter); j++) {
2664					struct thread_group_snapshot_v3 *tgs = tgs_array + j;
2665					[thread_groups addObject:@(tgs->tgs_id)];
2666				}
2667			}
2668			else {
2669				struct thread_group_snapshot *tgs_array = kcdata_iter_payload(iter);
2670				for (uint32_t j = 0; j < kcdata_iter_array_elem_count(iter); j++) {
2671					struct thread_group_snapshot *tgs = tgs_array + j;
2672					[thread_groups addObject:@(tgs->tgs_id)];
2673				}
2674			}
2675			break;
2676		}
2677		}
2678	}
2679	KCDATA_ITER_FOREACH(iter) {
2680		NSError *error = nil;
2681
2682		switch (kcdata_iter_type(iter)) {
2683
2684		case KCDATA_TYPE_CONTAINER_BEGIN: {
2685			T_QUIET;
2686			T_ASSERT_TRUE(kcdata_iter_container_valid(iter),
2687					"checked that container is valid");
2688
2689			if (kcdata_iter_container_type(iter) != STACKSHOT_KCCONTAINER_THREAD) {
2690				break;
2691			}
2692
2693			NSDictionary *container = parseKCDataContainer(&iter, &error);
2694			T_QUIET; T_ASSERT_NOTNULL(container, "parsed thread container from stackshot");
2695			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing container");
2696
2697			int tg = [container[@"thread_snapshots"][@"thread_group"] intValue];
2698
2699			T_ASSERT_TRUE([thread_groups containsObject:@(tg)], "check that the thread group the thread is in exists");
2700
2701			break;
2702		};
2703
2704		}
2705	}
2706	T_ASSERT_TRUE(seen_thread_group_snapshot, "check that we have seen a thread group snapshot");
2707}
2708
2709static void
2710verify_stackshot_sharedcache_layout(struct dyld_uuid_info_64 *uuids, uint32_t uuid_count)
2711{
2712	uuid_t cur_shared_cache_uuid;
2713	__block uint32_t lib_index = 0, libs_found = 0;
2714
2715	_dyld_get_shared_cache_uuid(cur_shared_cache_uuid);
2716	int result = dyld_shared_cache_iterate_text(cur_shared_cache_uuid, ^(const dyld_shared_cache_dylib_text_info* info) {
2717			T_QUIET; T_ASSERT_LT(lib_index, uuid_count, "dyld_shared_cache_iterate_text exceeded number of libraries returned by kernel");
2718
2719			libs_found++;
2720			struct dyld_uuid_info_64 *cur_stackshot_uuid_entry = &uuids[lib_index];
2721			T_QUIET; T_ASSERT_EQ(memcmp(info->dylibUuid, cur_stackshot_uuid_entry->imageUUID, sizeof(info->dylibUuid)), 0,
2722					"dyld returned UUID doesn't match kernel returned UUID");
2723			T_QUIET; T_ASSERT_EQ(info->loadAddressUnslid, cur_stackshot_uuid_entry->imageLoadAddress,
2724					"dyld returned load address doesn't match kernel returned load address");
2725			lib_index++;
2726		});
2727
2728	T_ASSERT_EQ(result, 0, "iterate shared cache layout");
2729	T_ASSERT_EQ(libs_found, uuid_count, "dyld iterator returned same number of libraries as kernel");
2730
2731	T_LOG("verified %d libraries from dyld shared cache", libs_found);
2732}
2733
2734static void
2735check_shared_cache_uuid(uuid_t imageUUID)
2736{
2737	static uuid_t shared_cache_uuid;
2738	static dispatch_once_t read_shared_cache_uuid;
2739
2740	dispatch_once(&read_shared_cache_uuid, ^{
2741		T_QUIET;
2742		T_ASSERT_TRUE(_dyld_get_shared_cache_uuid(shared_cache_uuid), "retrieve current shared cache UUID");
2743	});
2744	T_QUIET; T_ASSERT_EQ(uuid_compare(shared_cache_uuid, imageUUID), 0,
2745			"dyld returned UUID doesn't match kernel returned UUID for system shared cache");
2746}
2747
2748/*
2749 * extra dictionary contains data relevant for the given flags:
2750 * PARSE_STACKSHOT_ZOMBIE:   zombie_child_pid_key -> @(pid)
2751 * PARSE_STACKSHOT_POSTEXEC: postexec_child_unique_pid_key -> @(unique_pid)
2752 */
2753static void
2754parse_stackshot(uint64_t stackshot_parsing_flags, void *ssbuf, size_t sslen, NSDictionary *extra)
2755{
2756	bool delta = (stackshot_parsing_flags & PARSE_STACKSHOT_DELTA);
2757	bool expect_sharedcache_child = (stackshot_parsing_flags & PARSE_STACKSHOT_SHAREDCACHE_FLAGS);
2758	bool expect_zombie_child = (stackshot_parsing_flags & PARSE_STACKSHOT_ZOMBIE);
2759	bool expect_postexec_child = (stackshot_parsing_flags & PARSE_STACKSHOT_POSTEXEC);
2760	bool expect_cseg_waitinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_WAITINFO_CSEG);
2761	bool expect_translated_child = (stackshot_parsing_flags & PARSE_STACKSHOT_TRANSLATED);
2762	bool expect_shared_cache_layout = false;
2763	bool expect_shared_cache_uuid = !delta;
2764	bool expect_dispatch_queue_label = (stackshot_parsing_flags & PARSE_STACKSHOT_DISPATCH_QUEUE_LABEL);
2765	bool expect_turnstile_lock = (stackshot_parsing_flags & PARSE_STACKSHOT_TURNSTILEINFO);
2766	bool expect_srp_waitinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_WAITINFO_SRP);
2767	bool expect_sp_throttled = (stackshot_parsing_flags & PARSE_STACKSHOT_THROTTLED_SP);
2768	bool expect_exec_inprogress = (stackshot_parsing_flags & PARSE_STACKSHOT_EXEC_INPROGRESS);
2769	bool expect_transitioning_task = (stackshot_parsing_flags & PARSE_STACKSHOT_TRANSITIONING);
2770	bool expect_asyncstack = (stackshot_parsing_flags & PARSE_STACKSHOT_ASYNCSTACK);
2771	bool expect_driverkit = (stackshot_parsing_flags & PARSE_STACKSHOT_DRIVERKIT);
2772	bool expect_suspendinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_SUSPENDINFO);
2773	bool found_zombie_child = false, found_postexec_child = false, found_shared_cache_layout = false, found_shared_cache_uuid = false;
2774	bool found_translated_child = false, found_transitioning_task = false;
2775	bool found_dispatch_queue_label = false, found_turnstile_lock = false;
2776	bool found_cseg_waitinfo = false, found_srp_waitinfo = false;
2777	bool found_sharedcache_child = false, found_sharedcache_badflags = false, found_sharedcache_self = false;
2778	bool found_asyncstack = false;
2779	bool found_throttled_service = false;
2780	bool found_exclaves = false;
2781	bool expect_single_task = (stackshot_parsing_flags & PARSE_STACKSHOT_TARGETPID);
2782	uint64_t srp_expected_threadid = 0;
2783	pid_t zombie_child_pid = -1, srp_expected_pid = -1, sharedcache_child_pid = -1, throttled_service_ctx = -1;
2784	pid_t translated_child_pid = -1, transistioning_task_pid = -1;
2785	bool sharedcache_child_sameaddr = false, is_throttled = false;
2786	uint64_t postexec_child_unique_pid = 0, cseg_expected_threadid = 0;
2787	uint64_t sharedcache_child_flags = 0, sharedcache_self_flags = 0;
2788	uint64_t asyncstack_threadid = 0;
2789	NSArray *asyncstack_stack = nil;
2790	char *inflatedBufferBase = NULL;
2791	pid_t exec_inprogress_pid = -1;
2792	void (^exec_inprogress_cb)(uint64_t, uint64_t) = NULL;
2793	int exec_inprogress_found = 0;
2794	uint64_t exec_inprogress_containerid = 0;
2795	void (^driverkit_cb)(pid_t) = NULL;
2796	NSMutableDictionary *sharedCaches = [NSMutableDictionary new];
2797	uint64_t expected_num_threads = 0, expected_num_tasks = 0, found_percpu_threads = 0, found_tasks = 0, found_percpu_tasks = 0;
2798	NSMutableSet *seen_tasks = [NSMutableSet new];
2799
2800	if (expect_shared_cache_uuid) {
2801		uuid_t shared_cache_uuid;
2802		if (!_dyld_get_shared_cache_uuid(shared_cache_uuid)) {
2803			T_LOG("Skipping verifying shared cache UUID in stackshot data because not running with a shared cache");
2804			expect_shared_cache_uuid = false;
2805		}
2806	}
2807
2808	if (stackshot_parsing_flags & PARSE_STACKSHOT_SHAREDCACHE_LAYOUT) {
2809		size_t shared_cache_length = 0;
2810		const void *cache_header = _dyld_get_shared_cache_range(&shared_cache_length);
2811		T_QUIET; T_ASSERT_NOTNULL(cache_header, "current process running with shared cache");
2812		T_QUIET; T_ASSERT_GT(shared_cache_length, sizeof(struct _dyld_cache_header), "valid shared cache length populated by _dyld_get_shared_cache_range");
2813
2814		if (_dyld_shared_cache_is_locally_built()) {
2815			T_LOG("device running with locally built shared cache, expect shared cache layout");
2816			expect_shared_cache_layout = true;
2817		} else {
2818			T_LOG("device running with B&I built shared-cache, no shared cache layout expected");
2819		}
2820	}
2821
2822	if (expect_sharedcache_child) {
2823		NSNumber* pid_num = extra[sharedcache_child_pid_key];
2824		NSNumber* sameaddr_num = extra[sharedcache_child_sameaddr_key];
2825		T_QUIET; T_ASSERT_NOTNULL(pid_num, "sharedcache child pid provided");
2826		T_QUIET; T_ASSERT_NOTNULL(sameaddr_num, "sharedcache child addrsame provided");
2827		sharedcache_child_pid = [pid_num intValue];
2828		T_QUIET; T_ASSERT_GT(sharedcache_child_pid, 0, "sharedcache child pid greater than zero");
2829		sharedcache_child_sameaddr = [sameaddr_num intValue];
2830		T_QUIET; T_ASSERT_GE([sameaddr_num intValue], 0, "sharedcache child sameaddr is boolean (0 or 1)");
2831		T_QUIET; T_ASSERT_LE([sameaddr_num intValue], 1, "sharedcache child sameaddr is boolean (0 or 1)");
2832	}
2833
2834    if (expect_transitioning_task) {
2835        NSNumber* pid_num = extra[transitioning_pid_key];
2836        T_ASSERT_NOTNULL(pid_num, "transitioning task pid provided");
2837        transistioning_task_pid = [pid_num intValue];
2838    }
2839
2840	if (expect_zombie_child) {
2841		NSNumber* pid_num = extra[zombie_child_pid_key];
2842		T_QUIET; T_ASSERT_NOTNULL(pid_num, "zombie child pid provided");
2843		zombie_child_pid = [pid_num intValue];
2844		T_QUIET; T_ASSERT_GT(zombie_child_pid, 0, "zombie child pid greater than zero");
2845	}
2846
2847	if (expect_postexec_child) {
2848		NSNumber* unique_pid_num = extra[postexec_child_unique_pid_key];
2849		T_QUIET; T_ASSERT_NOTNULL(unique_pid_num, "postexec child unique pid provided");
2850		postexec_child_unique_pid = [unique_pid_num unsignedLongLongValue];
2851		T_QUIET; T_ASSERT_GT(postexec_child_unique_pid, 0ull, "postexec child unique pid greater than zero");
2852	}
2853
2854	if (expect_cseg_waitinfo) {
2855		NSNumber* tid_num = extra[cseg_expected_threadid_key];
2856		T_QUIET; T_ASSERT_NOTNULL(tid_num, "cseg's expected thread id provided");
2857		cseg_expected_threadid = tid_num.unsignedLongValue;
2858		T_QUIET; T_ASSERT_GT(cseg_expected_threadid, UINT64_C(0), "compressor segment thread is present");
2859	}
2860
2861	if (expect_srp_waitinfo) {
2862		NSNumber* threadid_num = extra[srp_expected_threadid_key];
2863		NSNumber* pid_num = extra[srp_expected_pid_key];
2864		T_QUIET; T_ASSERT_TRUE(threadid_num != nil || pid_num != nil, "expected SRP threadid or pid");
2865		if (threadid_num != nil) {
2866			srp_expected_threadid = [threadid_num unsignedLongLongValue];
2867			T_QUIET; T_ASSERT_GT(srp_expected_threadid, 0ull, "srp_expected_threadid greater than zero");
2868		}
2869		if (pid_num != nil) {
2870			srp_expected_pid = [pid_num intValue];
2871			T_QUIET; T_ASSERT_GT(srp_expected_pid, 0, "srp_expected_pid greater than zero");
2872		}
2873		T_LOG("looking for SRP pid: %d threadid: %llu", srp_expected_pid, srp_expected_threadid);
2874	}
2875
2876	if (expect_sp_throttled) {
2877		NSNumber* ctx = extra[sp_throttled_expected_ctxt_key];
2878		T_QUIET; T_ASSERT_TRUE(ctx != nil, "expected pid");
2879		throttled_service_ctx = [ctx intValue];
2880		T_QUIET; T_ASSERT_GT(throttled_service_ctx, 0, "expected pid greater than zero");
2881
2882		NSNumber *throttled = extra[sp_throttled_expect_flag];
2883		T_QUIET; T_ASSERT_TRUE(throttled != nil, "expected flag value");
2884		is_throttled = ([throttled intValue] != 0);
2885
2886		T_LOG("Looking for service with ctxt: %d, thottled:%d", throttled_service_ctx, is_throttled);
2887	}
2888
2889	if (expect_translated_child) {
2890		NSNumber* pid_num = extra[translated_child_pid_key];
2891		T_QUIET; T_ASSERT_NOTNULL(pid_num, "translated child pid provided");
2892		translated_child_pid = [pid_num intValue];
2893		T_QUIET; T_ASSERT_GT(translated_child_pid, 0, "translated child pid greater than zero");
2894	}
2895	if (expect_exec_inprogress) {
2896		NSNumber* pid_num = extra[exec_inprogress_pid_key];
2897		T_QUIET; T_ASSERT_NOTNULL(pid_num, "exec inprogress pid provided");
2898		exec_inprogress_pid = [pid_num intValue];
2899		T_QUIET; T_ASSERT_GT(exec_inprogress_pid, 0, "exec inprogress pid greater than zero");
2900
2901		exec_inprogress_cb = extra[exec_inprogress_found_key];
2902		T_QUIET; T_ASSERT_NOTNULL(exec_inprogress_cb, "exec inprogress found callback provided");
2903	}
2904	if (expect_driverkit) {
2905		driverkit_cb = extra[driverkit_found_key];
2906		T_QUIET; T_ASSERT_NOTNULL(driverkit_cb, "driverkit found callback provided");
2907	}
2908
2909	if (expect_asyncstack) {
2910		NSNumber* threadid_id = extra[asyncstack_expected_threadid_key];
2911		T_QUIET; T_ASSERT_NOTNULL(threadid_id, "asyncstack threadid provided");
2912		asyncstack_threadid = [threadid_id unsignedLongLongValue];
2913		asyncstack_stack = extra[asyncstack_expected_stack_key];
2914		T_QUIET; T_ASSERT_NOTNULL(asyncstack_stack, "asyncstack expected stack provided");
2915	}
2916
2917	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2918	if (delta) {
2919		T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT,
2920				"buffer provided is a delta stackshot");
2921
2922			iter = kcdata_iter_next(iter);
2923	} else {
2924		if (kcdata_iter_type(iter) != KCDATA_BUFFER_BEGIN_COMPRESSED) {
2925			T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT,
2926					"buffer provided is a stackshot");
2927
2928			iter = kcdata_iter_next(iter);
2929		} else {
2930			/* we are dealing with a compressed buffer */
2931			iter = kcdata_iter_next(iter);
2932			uint64_t compression_type = 0, totalout = 0, totalin = 0;
2933
2934			uint64_t *data;
2935			char *desc;
2936			for (int i = 0; i < 3; i ++) {
2937				kcdata_iter_get_data_with_desc(iter, &desc, (void **)&data, NULL);
2938				if (strcmp(desc, "kcd_c_type") == 0) {
2939					compression_type = *data;
2940				} else if (strcmp(desc, "kcd_c_totalout") == 0){
2941					totalout = *data;
2942				} else if (strcmp(desc, "kcd_c_totalin") == 0){
2943					totalin = *data;
2944				}
2945
2946				iter = kcdata_iter_next(iter);
2947			}
2948
2949			T_ASSERT_EQ(compression_type, UINT64_C(1), "zlib compression is used");
2950			T_ASSERT_GT(totalout, UINT64_C(0), "successfully gathered how long the compressed buffer is");
2951			T_ASSERT_GT(totalin, UINT64_C(0), "successfully gathered how long the uncompressed buffer will be at least");
2952
2953			/* progress to the next kcdata item */
2954			T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT, "compressed stackshot found");
2955
2956			char *bufferBase = kcdata_iter_payload(iter);
2957
2958			/*
2959			 * zlib is used, allocate a buffer based on the metadata, plus
2960			 * extra scratch space (+12.5%) in case totalin was inconsistent
2961			 */
2962			size_t inflatedBufferSize = totalin + (totalin >> 3);
2963			inflatedBufferBase = malloc(inflatedBufferSize);
2964			T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(inflatedBufferBase, "allocated temporary output buffer");
2965
2966			z_stream zs;
2967			memset(&zs, 0, sizeof(zs));
2968			T_QUIET; T_ASSERT_EQ(inflateInit(&zs), Z_OK, "inflateInit OK");
2969			zs.next_in = (unsigned char *)bufferBase;
2970			T_QUIET; T_ASSERT_LE(totalout, (uint64_t)UINT_MAX, "stackshot is not too large");
2971			zs.avail_in = (uInt)totalout;
2972			zs.next_out = (unsigned char *)inflatedBufferBase;
2973			T_QUIET; T_ASSERT_LE(inflatedBufferSize, (size_t)UINT_MAX, "output region is not too large");
2974			zs.avail_out = (uInt)inflatedBufferSize;
2975			T_ASSERT_EQ(inflate(&zs, Z_FINISH), Z_STREAM_END, "inflated buffer");
2976			inflateEnd(&zs);
2977
2978			T_ASSERT_EQ((uint64_t)zs.total_out, totalin, "expected number of bytes inflated");
2979
2980			/* copy the data after the compressed area */
2981			T_QUIET; T_ASSERT_GE((void *)bufferBase, ssbuf,
2982					"base of compressed stackshot is after the returned stackshot buffer");
2983			size_t header_size = (size_t)(bufferBase - (char *)ssbuf);
2984			size_t data_after_compressed_size = sslen - totalout - header_size;
2985			T_QUIET; T_ASSERT_LE(data_after_compressed_size,
2986					inflatedBufferSize - zs.total_out,
2987					"footer fits in the buffer");
2988			memcpy(inflatedBufferBase + zs.total_out,
2989					bufferBase + totalout,
2990					data_after_compressed_size);
2991
2992			iter = kcdata_iter(inflatedBufferBase, inflatedBufferSize);
2993		}
2994	}
2995
2996	KCDATA_ITER_FOREACH(iter) {
2997		NSError *error = nil;
2998
2999		switch (kcdata_iter_type(iter)) {
3000		case KCDATA_TYPE_ARRAY: {
3001			T_QUIET;
3002			T_ASSERT_TRUE(kcdata_iter_array_valid(iter),
3003					"checked that array is valid");
3004
3005			NSMutableDictionary *array = parseKCDataArray(iter, &error);
3006			T_QUIET; T_ASSERT_NOTNULL(array, "parsed array from stackshot");
3007			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing array");
3008
3009			if (kcdata_iter_array_elem_type(iter) == STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT) {
3010				struct dyld_uuid_info_64 *shared_cache_uuids = kcdata_iter_payload(iter);
3011				uint32_t uuid_count = kcdata_iter_array_elem_count(iter);
3012				T_ASSERT_NOTNULL(shared_cache_uuids, "parsed shared cache layout array");
3013				T_ASSERT_GT(uuid_count, 0, "returned valid number of UUIDs from shared cache");
3014				verify_stackshot_sharedcache_layout(shared_cache_uuids, uuid_count);
3015				found_shared_cache_layout = true;
3016			}
3017
3018			break;
3019		}
3020		case KCDATA_TYPE_CONTAINER_BEGIN: {
3021			T_QUIET;
3022			T_ASSERT_TRUE(kcdata_iter_container_valid(iter),
3023					"checked that container is valid");
3024
3025			uint64_t containerid = kcdata_iter_container_id(iter);
3026			uint32_t container_type = kcdata_iter_container_type(iter);
3027
3028			if (container_type == STACKSHOT_KCCONTAINER_SHAREDCACHE) {
3029				NSDictionary *container = parseKCDataContainer(&iter, &error);
3030				T_QUIET; T_ASSERT_NOTNULL(container, "parsed sharedcache container from stackshot");
3031				T_QUIET; T_ASSERT_NULL(error, "error unset after parsing sharedcache container");
3032				T_QUIET; T_EXPECT_EQ(sharedCaches[@(containerid)], nil, "sharedcache containerid %lld should be unique", containerid);
3033				sharedCaches[@(containerid)] = container;
3034				break;
3035			}
3036
3037			if (container_type == STACKSHOT_KCCONTAINER_EXCLAVES) {
3038				found_exclaves = true;
3039				break;
3040			}
3041
3042			/*
3043			 * treat containers other than tasks/transitioning_tasks
3044			 * as expanded in-line.
3045			 */
3046			if (container_type != STACKSHOT_KCCONTAINER_TASK &&
3047			    container_type != STACKSHOT_KCCONTAINER_TRANSITIONING_TASK) {
3048				T_LOG("container skipped: %d", container_type);
3049				break;
3050			}
3051			NSDictionary *container = parseKCDataContainer(&iter, &error);
3052			T_QUIET; T_ASSERT_NOTNULL(container, "parsed task/transitioning_task container from stackshot");
3053			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing container");
3054
3055			found_tasks++;
3056
3057			NSDictionary* task_snapshot = container[@"task_snapshots"][@"task_snapshot"];
3058			NSDictionary* task_delta_snapshot = container[@"task_snapshots"][@"task_delta_snapshot"];
3059			NSDictionary* transitioning_task_snapshot = container[@"transitioning_task_snapshots"][@"transitioning_task_snapshot"];
3060
3061			NSNumber *task_pid = NULL;
3062			if (task_snapshot) {
3063				task_pid = task_snapshot[@"ts_unique_pid"];
3064			} else if(task_delta_snapshot) {
3065				task_pid = task_snapshot[@"tds_unique_pid"];
3066			} else if(transitioning_task_snapshot) {
3067				task_pid = transitioning_task_snapshot[@"tts_pid"];
3068			}
3069
3070			if (task_pid && [seen_tasks containsObject:task_pid]) {
3071				T_QUIET; T_ASSERT_FALSE([seen_tasks containsObject:task_pid], "No duplicate PIDs in stackshot");
3072				[seen_tasks addObject:task_pid];
3073			}
3074
3075			/*
3076			 * Having processed the container, we now only check it
3077			 * if it's the correct type.
3078			 */
3079			if ((!expect_transitioning_task && (container_type != STACKSHOT_KCCONTAINER_TASK)) ||
3080			    (expect_transitioning_task && (container_type != STACKSHOT_KCCONTAINER_TRANSITIONING_TASK))) {
3081				break;
3082			}
3083			if (!expect_transitioning_task) {
3084			    	T_QUIET; T_ASSERT_TRUE(!!task_snapshot != !!task_delta_snapshot, "Either task_snapshot xor task_delta_snapshot provided");
3085			}
3086
3087			if (expect_dispatch_queue_label && !found_dispatch_queue_label) {
3088				for (id thread_key in container[@"task_snapshots"][@"thread_snapshots"]) {
3089					NSMutableDictionary *thread = container[@"task_snapshots"][@"thread_snapshots"][thread_key];
3090					NSString *dql = thread[@"dispatch_queue_label"];
3091
3092					if ([dql isEqualToString:@TEST_STACKSHOT_QUEUE_LABEL]) {
3093						found_dispatch_queue_label = true;
3094						break;
3095					}
3096				}
3097			}
3098
3099			if (expect_transitioning_task && !found_transitioning_task) {
3100				if (transitioning_task_snapshot) {
3101					uint64_t the_pid = [transitioning_task_snapshot[@"tts_pid"] unsignedLongLongValue];
3102					if (the_pid == (uint64_t)transistioning_task_pid) {
3103					    found_transitioning_task = true;
3104
3105					    T_PASS("FOUND Transitioning task %llu has a transitioning task snapshot", (uint64_t) transistioning_task_pid);
3106					    break;
3107					}
3108				}
3109			}
3110
3111			if (expect_postexec_child && !found_postexec_child) {
3112				if (task_snapshot) {
3113					uint64_t unique_pid = [task_snapshot[@"ts_unique_pid"] unsignedLongLongValue];
3114					if (unique_pid == postexec_child_unique_pid) {
3115						found_postexec_child = true;
3116
3117						T_PASS("post-exec child %llu has a task snapshot", postexec_child_unique_pid);
3118
3119						break;
3120					}
3121				}
3122
3123				if (task_delta_snapshot) {
3124					uint64_t unique_pid = [task_delta_snapshot[@"tds_unique_pid"] unsignedLongLongValue];
3125					if (unique_pid == postexec_child_unique_pid) {
3126						found_postexec_child = true;
3127
3128						T_FAIL("post-exec child %llu shouldn't have a delta task snapshot", postexec_child_unique_pid);
3129
3130						break;
3131					}
3132				}
3133			}
3134
3135			int pid = [task_snapshot[@"ts_pid"] intValue];
3136
3137			if (pid && expect_shared_cache_uuid && !found_shared_cache_uuid) {
3138				id ptr = container[@"task_snapshots"][@"shared_cache_dyld_load_info"];
3139				if (ptr) {
3140					id uuid = ptr[@"imageUUID"];
3141
3142					uint8_t uuid_p[16];
3143					for (unsigned int i = 0; i < 16; i ++) {
3144						NSNumber *uuidByte = uuid[i];
3145						uuid_p[i] = (uint8_t)uuidByte.charValue;
3146					}
3147
3148					check_shared_cache_uuid(uuid_p);
3149
3150					uint64_t baseAddress = (uint64_t)((NSNumber *)ptr[@"imageSlidBaseAddress"]).longLongValue;
3151					uint64_t firstMapping = (uint64_t)((NSNumber *)ptr[@"sharedCacheSlidFirstMapping"]).longLongValue;
3152
3153					T_EXPECT_LE(baseAddress, firstMapping,
3154						"in per-task shared_cache_dyld_load_info, "
3155						"baseAddress <= firstMapping");
3156					T_EXPECT_GE(baseAddress + (7ull << 32) + (1ull << 29),
3157						firstMapping,
3158						"in per-task shared_cache_dyld_load_info, "
3159						"baseAddress + 28.5gig >= firstMapping");
3160
3161					size_t shared_cache_len;
3162					const void *addr = _dyld_get_shared_cache_range(&shared_cache_len);
3163					T_EXPECT_EQ((uint64_t)addr, firstMapping,
3164							"SlidFirstMapping should match shared_cache_range");
3165
3166					/*
3167					 * check_shared_cache_uuid() will assert on failure, so if
3168					 * we get here, then we have found the shared cache UUID
3169					 * and it's correct
3170					 */
3171					found_shared_cache_uuid = true;
3172				}
3173			}
3174
3175			if (expect_sharedcache_child) {
3176				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3177				uint64_t sharedregion_flags = (task_flags & (kTaskSharedRegionNone | kTaskSharedRegionSystem | kTaskSharedRegionOther));
3178				id sharedregion_info = container[@"task_snapshots"][@"shared_cache_dyld_load_info"];
3179				id sharedcache_id = container[@"task_snapshots"][@"sharedCacheID"];
3180				if (!found_sharedcache_badflags) {
3181					T_QUIET; T_EXPECT_NE(sharedregion_flags, 0ll, "one of the kTaskSharedRegion flags should be set on all tasks");
3182					bool multiple = (sharedregion_flags & (sharedregion_flags - 1)) != 0;
3183					T_QUIET; T_EXPECT_FALSE(multiple, "only one kTaskSharedRegion flag should be set on each task");
3184					found_sharedcache_badflags = (sharedregion_flags == 0 || multiple);
3185				}
3186				if (pid == 0) {
3187					T_ASSERT_EQ(sharedregion_flags, (uint64_t)kTaskSharedRegionNone, "Kernel proc (pid 0) should have no shared region");
3188				} else if (pid == sharedcache_child_pid) {
3189					found_sharedcache_child = true;
3190					sharedcache_child_flags = sharedregion_flags;
3191				} else if (pid == getpid()) {
3192					found_sharedcache_self = true;
3193					sharedcache_self_flags = sharedregion_flags;
3194				}
3195				if (sharedregion_flags == kTaskSharedRegionOther && !(task_flags & kTaskSharedRegionInfoUnavailable)) {
3196					T_QUIET; T_EXPECT_NOTNULL(sharedregion_info, "kTaskSharedRegionOther should have a shared_cache_dyld_load_info struct");
3197					T_QUIET; T_EXPECT_NOTNULL(sharedcache_id, "kTaskSharedRegionOther should have a sharedCacheID");
3198					if (sharedcache_id != nil) {
3199						T_QUIET; T_EXPECT_NOTNULL(sharedCaches[sharedcache_id], "sharedCacheID %d should exist", [sharedcache_id intValue]);
3200					}
3201				} else {
3202					T_QUIET; T_EXPECT_NULL(sharedregion_info, "non-kTaskSharedRegionOther should have no shared_cache_dyld_load_info struct");
3203					T_QUIET; T_EXPECT_NULL(sharedcache_id, "non-kTaskSharedRegionOther should have no sharedCacheID");
3204				}
3205			}
3206
3207			if (expect_zombie_child && (pid == zombie_child_pid)) {
3208				found_zombie_child = true;
3209
3210				expected_num_tasks += 1;
3211
3212				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3213				T_ASSERT_TRUE((task_flags & kTerminatedSnapshot) == kTerminatedSnapshot, "child zombie marked as terminated");
3214
3215				continue;
3216			}
3217
3218			if (expect_translated_child && (pid == translated_child_pid)) {
3219				found_translated_child = true;
3220
3221				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3222				T_EXPECT_BITS_SET(task_flags, kTaskIsTranslated, "child marked as translated");
3223
3224				continue;
3225			}
3226			if (expect_exec_inprogress && (pid == exec_inprogress_pid || pid == -exec_inprogress_pid)) {
3227				exec_inprogress_found++;
3228				T_LOG("found exec task with pid %d, instance %d", pid, exec_inprogress_found);
3229				T_QUIET; T_ASSERT_LE(exec_inprogress_found, 2, "no more than two with the expected pid");
3230				if (exec_inprogress_found == 2) {
3231					T_LOG("found 2 tasks with pid %d", exec_inprogress_pid);
3232					exec_inprogress_cb(containerid, exec_inprogress_containerid);
3233				} else {
3234					exec_inprogress_containerid = containerid;
3235				}
3236			}
3237			if (expect_driverkit && driverkit_cb != NULL) {
3238				driverkit_cb(pid);
3239			}
3240			if (expect_cseg_waitinfo) {
3241				NSArray *winfos = container[@"task_snapshots"][@"thread_waitinfo"];
3242
3243				for (id i in winfos) {
3244					NSNumber *waitType = i[@"wait_type"];
3245					NSNumber *owner = i[@"owner"];
3246					if (waitType.intValue == kThreadWaitCompressor &&
3247							owner.unsignedLongValue == cseg_expected_threadid) {
3248						found_cseg_waitinfo = true;
3249						break;
3250					}
3251				}
3252			}
3253
3254			if (expect_srp_waitinfo) {
3255				NSArray *tinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3256				NSArray *winfos = container[@"task_snapshots"][@"thread_waitinfo"];
3257				for (id i in tinfos) {
3258					if (!found_srp_waitinfo) {
3259						bool found_thread = false;
3260						bool found_pid = false;
3261						if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_THREAD) &&
3262						    [i[@"turnstile_context"] unsignedLongLongValue] == srp_expected_threadid &&
3263						    srp_expected_threadid != 0) {
3264							found_thread = true;
3265						}
3266						if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_BLOCKED_ON_TASK) &&
3267						    [i[@"turnstile_context"] intValue] == srp_expected_pid &&
3268						    srp_expected_pid != -1) {
3269							found_pid = true;
3270						}
3271						if (found_pid || found_thread) {
3272							T_LOG("found SRP %s %lld waiter: %d", (found_thread ? "thread" : "pid"),
3273							    [i[@"turnstile_context"] unsignedLongLongValue], [i[@"waiter"] intValue]);
3274							/* we found something that is blocking the correct threadid */
3275							for (id j in winfos) {
3276								if ([j[@"waiter"] intValue] == [i[@"waiter"] intValue] &&
3277								    [j[@"wait_type"] intValue] == kThreadWaitPortReceive) {
3278									found_srp_waitinfo = true;
3279									T_EXPECT_EQ([j[@"wait_flags"] intValue], STACKSHOT_WAITINFO_FLAGS_SPECIALREPLY,
3280									    "SRP waitinfo should be marked as a special reply");
3281									break;
3282								}
3283							}
3284
3285							if (found_srp_waitinfo) {
3286								break;
3287							}
3288						}
3289					}
3290				}
3291			}
3292
3293			if (expect_sp_throttled) {
3294				NSArray *tinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3295				for (id i in tinfos) {
3296					if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_PORTFLAGS)
3297						&& [i[@"turnstile_context"] intValue] == throttled_service_ctx) {
3298						int portlabel_id = [i[@"portlabel_id"] intValue];
3299						T_LOG("[pid:%d] Turnstile (flags = 0x%x, ctx = %d, portlabel_id = %d)", pid,
3300							[i[@"turnstile_flags"] intValue], [i[@"turnstile_context"] intValue], portlabel_id);
3301						for (id portid in container[@"task_snapshots"][@"portlabels"]) {
3302							if (portlabel_id != [portid intValue]) {
3303								continue;
3304							}
3305
3306							NSMutableDictionary *portlabel = container[@"task_snapshots"][@"portlabels"][portid];
3307							T_ASSERT_TRUE(portlabel != nil, "Found portlabel id: %d", [portid intValue]);
3308							NSString *portlabel_name = portlabel[@"portlabel_name"];
3309							T_EXPECT_TRUE(portlabel_name != nil, "Found portlabel %s", portlabel_name.UTF8String);
3310							T_EXPECT_EQ_STR(portlabel_name.UTF8String, THROTTLED_SERVICE_NAME, "throttled service port name matches");
3311							T_EXPECT_EQ(([portlabel[@"portlabel_flags"] intValue] & STACKSHOT_PORTLABEL_THROTTLED) != 0,
3312								is_throttled, "Port %s throttled", is_throttled ? "is" : "isn't");
3313							found_throttled_service = true;
3314							break;
3315						}
3316					}
3317
3318					if (found_throttled_service) {
3319						break;
3320					}
3321				}
3322			}
3323
3324			if (expect_suspendinfo) {
3325				// TODO: rdar://112563110
3326			}
3327
3328
3329			if (pid != getpid()) {
3330				break;
3331			}
3332
3333			T_EXPECT_EQ_STR(current_process_name(),
3334					[task_snapshot[@"ts_p_comm"] UTF8String],
3335					"current process name matches in stackshot");
3336
3337			uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3338			T_ASSERT_BITS_NOTSET(task_flags, kTerminatedSnapshot, "current process not marked as terminated");
3339			T_ASSERT_BITS_NOTSET(task_flags, kTaskIsTranslated, "current process not marked as translated");
3340
3341			T_QUIET;
3342			T_EXPECT_LE(pid, [task_snapshot[@"ts_unique_pid"] intValue],
3343					"unique pid is greater than pid");
3344
3345			NSDictionary* task_cpu_architecture = container[@"task_snapshots"][@"task_cpu_architecture"];
3346			T_QUIET; T_ASSERT_NOTNULL(task_cpu_architecture[@"cputype"], "have cputype");
3347			T_QUIET; T_ASSERT_NOTNULL(task_cpu_architecture[@"cpusubtype"], "have cputype");
3348			int cputype = [task_cpu_architecture[@"cputype"] intValue];
3349			int cpusubtype = [task_cpu_architecture[@"cpusubtype"] intValue];
3350
3351			struct proc_archinfo archinfo;
3352			int retval = proc_pidinfo(pid, PROC_PIDARCHINFO, 0, &archinfo, sizeof(archinfo));
3353			T_QUIET; T_WITH_ERRNO; T_ASSERT_GT(retval, 0, "proc_pidinfo(PROC_PIDARCHINFO) returned a value > 0");
3354			T_QUIET; T_ASSERT_EQ(retval, (int)sizeof(struct proc_archinfo), "proc_pidinfo call for PROC_PIDARCHINFO returned expected size");
3355			T_QUIET; T_EXPECT_EQ(cputype, archinfo.p_cputype, "cpu type is correct");
3356			T_QUIET; T_EXPECT_EQ(cpusubtype, archinfo.p_cpusubtype, "cpu subtype is correct");
3357
3358			NSDictionary * codesigning_info = container[@"task_snapshots"][@"stackshot_task_codesigning_info"];
3359			T_QUIET; T_ASSERT_NOTNULL(codesigning_info[@"csflags"], "have csflags");
3360			uint64_t flags = [codesigning_info[@"csflags"] unsignedLongLongValue];
3361			T_QUIET; T_EXPECT_GT(flags, 0, "nonzero csflags");
3362
3363			T_QUIET; T_ASSERT_NOTNULL(container[@"task_snapshots"][@"jetsam_coalition"], "have jetsam coalition");
3364			uint64_t jetsam_coalition = [container[@"task_snapshots"][@"jetsam_coalition"] unsignedLongLongValue];
3365			T_QUIET; T_EXPECT_GT(jetsam_coalition, 0, "nonzero jetsam coalition");
3366
3367			bool found_main_thread = false;
3368			uint64_t main_thread_id = -1ULL;
3369			bool found_null_kernel_frame = false;
3370			for (id thread_key in container[@"task_snapshots"][@"thread_snapshots"]) {
3371				NSMutableDictionary *thread = container[@"task_snapshots"][@"thread_snapshots"][thread_key];
3372				NSDictionary *thread_snap = thread[@"thread_snapshot"];
3373
3374				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_thread_id"] intValue], 0,
3375						"thread ID of thread in current task is valid");
3376				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_base_priority"] intValue], 0,
3377						"base priority of thread in current task is valid");
3378				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_sched_priority"] intValue], 0,
3379						"scheduling priority of thread in current task is valid");
3380
3381				NSString *pth_name = thread[@"pth_name"];
3382				if (pth_name != nil && [pth_name isEqualToString:@TEST_THREAD_NAME]) {
3383					found_main_thread = true;
3384					main_thread_id = [thread_snap[@"ths_thread_id"] unsignedLongLongValue];
3385
3386					T_QUIET; T_EXPECT_GT([thread_snap[@"ths_total_syscalls"] intValue], 0,
3387							"total syscalls of current thread is valid");
3388
3389					NSDictionary *cpu_times = thread[@"cpu_times"];
3390					T_EXPECT_GE([cpu_times[@"runnable_time"] intValue],
3391							[cpu_times[@"system_time"] intValue] +
3392							[cpu_times[@"user_time"] intValue],
3393							"runnable time of current thread is valid");
3394				}
3395				if (!found_null_kernel_frame) {
3396					for (NSNumber *frame in thread[@"kernel_frames"]) {
3397						if (frame.unsignedLongValue == 0) {
3398							found_null_kernel_frame = true;
3399							break;
3400						}
3401					}
3402				}
3403				if (expect_asyncstack && !found_asyncstack &&
3404				    asyncstack_threadid == [thread_snap[@"ths_thread_id"] unsignedLongLongValue]) {
3405					found_asyncstack = true;
3406					NSArray* async_stack = thread[@"user_async_stack_frames"];
3407					NSNumber* start_idx = thread[@"user_async_start_index"];
3408					NSArray* user_stack = thread[@"user_stack_frames"];
3409					T_QUIET; T_ASSERT_NOTNULL(async_stack, "async thread %#llx has user_async_stack_frames", asyncstack_threadid);
3410					T_QUIET; T_ASSERT_NOTNULL(start_idx, "async thread %#llx has user_async_start_index", asyncstack_threadid);
3411					T_QUIET; T_ASSERT_NOTNULL(user_stack, "async thread %#llx has user_stack_frames", asyncstack_threadid);
3412					T_QUIET; T_ASSERT_EQ(async_stack.count, asyncstack_stack.count,
3413						"actual async_stack count == expected async_stack count");
3414					for (size_t i = 0; i < async_stack.count; i++) {
3415						T_EXPECT_EQ([async_stack[i][@"lr"] unsignedLongLongValue],
3416							[asyncstack_stack[i] unsignedLongLongValue], "frame %zu matches", i);
3417					}
3418				}
3419			}
3420			T_EXPECT_TRUE(found_main_thread, "found main thread for current task in stackshot");
3421			T_EXPECT_FALSE(found_null_kernel_frame, "should not see any NULL kernel frames");
3422
3423			if (expect_turnstile_lock && !found_turnstile_lock) {
3424				NSArray *tsinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3425
3426				for (id i in tsinfos) {
3427					if ([i[@"turnstile_context"] unsignedLongLongValue] == main_thread_id) {
3428						found_turnstile_lock = true;
3429						break;
3430					}
3431				}
3432			}
3433			break;
3434		}
3435		case STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO: {
3436			// Legacy shared cache info
3437			struct dyld_shared_cache_loadinfo *payload = kcdata_iter_payload(iter);
3438			T_ASSERT_EQ((size_t)kcdata_iter_size(iter), sizeof(*payload), "valid dyld_shared_cache_loadinfo struct");
3439
3440			check_shared_cache_uuid(payload->sharedCacheUUID);
3441
3442			T_EXPECT_LE(payload->sharedCacheUnreliableSlidBaseAddress,
3443				payload->sharedCacheSlidFirstMapping,
3444				"SlidBaseAddress <= SlidFirstMapping");
3445			T_EXPECT_GE(payload->sharedCacheUnreliableSlidBaseAddress + (7ull << 32) + (1ull << 29),
3446				payload->sharedCacheSlidFirstMapping,
3447				"SlidFirstMapping should be within 28.5gigs of SlidBaseAddress");
3448
3449			size_t shared_cache_len;
3450			const void *addr = _dyld_get_shared_cache_range(&shared_cache_len);
3451			T_EXPECT_EQ((uint64_t)addr, payload->sharedCacheSlidFirstMapping,
3452			    "SlidFirstMapping should match shared_cache_range");
3453
3454			/*
3455			 * check_shared_cache_uuid() asserts on failure, so we must have
3456			 * found the shared cache UUID to be correct.
3457			 */
3458			found_shared_cache_uuid = true;
3459			break;
3460		}
3461		case KCDATA_TYPE_UINT64_DESC: {
3462			char     *desc;
3463			uint64_t *data;
3464			uint32_t  size;
3465			kcdata_iter_get_data_with_desc(iter, &desc, &data, &size);
3466
3467			if (strcmp(desc, "stackshot_tasks_count") == 0) {
3468				expected_num_tasks = *data;
3469			} else if (strcmp(desc, "stackshot_threads_count") == 0) {
3470				expected_num_threads = *data;
3471			}
3472
3473			break;
3474		}
3475		case STACKSHOT_KCTYPE_LATENCY_INFO_CPU: {
3476			struct stackshot_latency_cpu *cpu_latency = kcdata_iter_payload(iter);
3477			found_percpu_tasks += cpu_latency->tasks_processed;
3478			found_percpu_threads += cpu_latency->threads_processed;
3479			break;
3480		}
3481		}
3482	}
3483
3484	if (expect_sharedcache_child) {
3485		T_QUIET; T_ASSERT_TRUE(found_sharedcache_child, "found sharedcache child in kcdata");
3486		T_QUIET; T_ASSERT_TRUE(found_sharedcache_self, "found self in kcdata");
3487		if (found_sharedcache_child && found_sharedcache_self) {
3488			T_QUIET; T_ASSERT_NE(sharedcache_child_flags, (uint64_t)kTaskSharedRegionNone, "sharedcache child should have shared region");
3489			T_QUIET; T_ASSERT_NE(sharedcache_self_flags, (uint64_t)kTaskSharedRegionNone, "sharedcache: self should have shared region");
3490			if (sharedcache_self_flags == kTaskSharedRegionSystem && !sharedcache_child_sameaddr) {
3491				/* If we're in the system shared region, and the child has a different address, child must have an Other shared region */
3492				T_ASSERT_EQ(sharedcache_child_flags, (uint64_t)kTaskSharedRegionOther,
3493				    "sharedcache child should have Other shared region");
3494			}
3495		}
3496	}
3497
3498	if (expect_transitioning_task) {
3499		T_QUIET; T_ASSERT_TRUE(found_transitioning_task, "found transitioning_task child in kcdata");
3500	}
3501
3502	if (expect_exec_inprogress) {
3503		T_QUIET; T_ASSERT_GT(exec_inprogress_found, 0, "found at least 1 task for execing process");
3504	}
3505
3506	if (expect_zombie_child) {
3507		T_QUIET; T_ASSERT_TRUE(found_zombie_child, "found zombie child in kcdata");
3508	}
3509
3510	if (expect_postexec_child) {
3511		T_QUIET; T_ASSERT_TRUE(found_postexec_child, "found post-exec child in kcdata");
3512	}
3513
3514	if (expect_translated_child) {
3515		T_QUIET; T_ASSERT_TRUE(found_translated_child, "found translated child in kcdata");
3516	}
3517
3518	if (expect_shared_cache_layout) {
3519		T_QUIET; T_ASSERT_TRUE(found_shared_cache_layout, "shared cache layout found in kcdata");
3520	}
3521
3522	if (expect_shared_cache_uuid) {
3523		T_QUIET; T_ASSERT_TRUE(found_shared_cache_uuid, "shared cache UUID found in kcdata");
3524	}
3525
3526	if (expect_dispatch_queue_label) {
3527		T_QUIET; T_ASSERT_TRUE(found_dispatch_queue_label, "dispatch queue label found in kcdata");
3528	}
3529
3530	if (expect_turnstile_lock) {
3531		T_QUIET; T_ASSERT_TRUE(found_turnstile_lock, "found expected deadlock");
3532	}
3533
3534	if (expect_cseg_waitinfo) {
3535		T_QUIET; T_ASSERT_TRUE(found_cseg_waitinfo, "found c_seg waitinfo");
3536	}
3537
3538	if (expect_srp_waitinfo) {
3539		T_QUIET; T_ASSERT_TRUE(found_srp_waitinfo, "found special reply port waitinfo");
3540	}
3541
3542	if (expect_sp_throttled) {
3543		T_QUIET; T_ASSERT_TRUE(found_throttled_service, "found the throttled service");
3544	}
3545
3546	if (expect_asyncstack) {
3547		T_QUIET; T_ASSERT_TRUE(found_asyncstack, "found async stack threadid");
3548	}
3549
3550	if ([extra objectForKey:no_exclaves_key] != nil) {
3551		T_QUIET; T_ASSERT_FALSE(found_exclaves, "did not find any Exclaves data");
3552	}
3553
3554
3555	bool check_counts = !delta && !found_transitioning_task && !expect_single_task && !expect_driverkit;
3556
3557	if (check_counts && (expected_num_threads != 0) && (found_percpu_threads != 0)) {
3558		/* If the task counts below check out, we can be sure that the per-cpu reported thread counts are accurate. */
3559		T_QUIET; T_ASSERT_EQ_ULLONG(found_percpu_threads, expected_num_threads, "number of threads reported by CPUs matches expected count");
3560	}
3561
3562	if (check_counts && (expected_num_tasks != 0)) {
3563		T_QUIET; T_ASSERT_EQ_ULLONG(found_tasks, expected_num_tasks, "number of tasks in kcdata matches expected count");
3564		if (found_percpu_tasks != 0) {
3565			T_QUIET; T_ASSERT_EQ_ULLONG(found_percpu_tasks, expected_num_tasks, "number of tasks reported by CPUs matches expected count");
3566		}
3567	}
3568
3569	T_ASSERT_FALSE(KCDATA_ITER_FOREACH_FAILED(iter), "successfully iterated kcdata");
3570
3571	free(inflatedBufferBase);
3572}
3573
3574static const char *
3575current_process_name(void)
3576{
3577	static char name[64];
3578
3579	if (!name[0]) {
3580		int ret = proc_name(getpid(), name, sizeof(name));
3581		T_QUIET;
3582		T_ASSERT_POSIX_SUCCESS(ret, "proc_name failed for current process");
3583	}
3584
3585	return name;
3586}
3587
3588static void
3589initialize_thread(void)
3590{
3591	int ret = pthread_setname_np(TEST_THREAD_NAME);
3592	T_QUIET;
3593	T_ASSERT_POSIX_ZERO(ret, "set thread name to %s", TEST_THREAD_NAME);
3594}
3595
3596T_DECL(dirty_buffer, "test that stackshot works with a dirty input buffer from kernel", T_META_TAG_VM_PREFERRED)
3597{
3598	const char *test_sysctl = "stackshot_dirty_buffer";
3599	int64_t result;
3600
3601	T_LOG("running sysctl to trigger kernel-driven stackshot");
3602	result = run_sysctl_test(test_sysctl, 0);
3603	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3604}
3605
3606T_DECL(kernel_initiated, "smoke test that stackshot works with kernel-initiated stackshots", T_META_TAG_VM_PREFERRED)
3607{
3608	const char *test_sysctl = "stackshot_kernel_initiator";
3609	int64_t result;
3610	__block bool did_get_stackshot = false;
3611
3612	initialize_thread(); // must run before the stackshots to keep parse_stackshot happy
3613
3614	T_LOG("running sysctl to trigger kernel-driven stackshot type 1");
3615	result = run_sysctl_test(test_sysctl, 1);
3616	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3617
3618	T_LOG("running sysctl to trigger kernel-driven stackshot type 2");
3619	result = run_sysctl_test(test_sysctl, 2);
3620	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3621
3622	struct scenario scenario = {
3623		.name = "from_kernel_initiated",
3624		.flags = STACKSHOT_RETRIEVE_EXISTING_BUFFER,
3625	};
3626
3627	T_LOG("attempting to fetch stored in-kernel stackshot");
3628	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
3629		T_ASSERT_NOTNULL(ssbuf, "non-null kernel stackshot");
3630		T_ASSERT_GT(sslen, 0, "non-zero stackshot size");
3631		parse_stackshot(0, ssbuf, sslen, nil);
3632		did_get_stackshot = true;
3633	});
3634
3635	T_ASSERT_TRUE(did_get_stackshot, "got stackshot from kernel type 2");
3636}
3637