xref: /xnu-11215.41.3/tests/stackshot_tests.m (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
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, "tests translated bit is set correctly", T_META_TAG_VM_PREFERRED)
1580{
1581#if !(TARGET_OS_OSX && TARGET_CPU_ARM64)
1582	T_SKIP("Only valid on Apple silicon Macs")
1583#endif
1584	// Get path of stackshot_translated_child helper binary
1585	char path[PATH_MAX];
1586	uint32_t path_size = sizeof(path);
1587	T_QUIET; T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
1588	char* binary_name = strrchr(path, '/');
1589	if (binary_name) binary_name++;
1590	T_QUIET; T_ASSERT_NOTNULL(binary_name, "Find basename in path '%s'", path);
1591	strlcpy(binary_name, "stackshot_translated_child", path_size - (binary_name - path));
1592	char *args[] = { path, NULL };
1593
1594	dispatch_source_t child_sig_src;
1595	dispatch_semaphore_t child_ready_sem = dispatch_semaphore_create(0);
1596	T_QUIET; T_ASSERT_NOTNULL(child_ready_sem, "exec child semaphore");
1597
1598	dispatch_queue_t signal_processing_q = dispatch_queue_create("signal processing queue", NULL);
1599	T_QUIET; T_ASSERT_NOTNULL(signal_processing_q, "signal processing queue");
1600
1601	signal(SIGUSR1, SIG_IGN);
1602	child_sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, signal_processing_q);
1603	T_QUIET; T_ASSERT_NOTNULL(child_sig_src, "dispatch_source_create (child_sig_src)");
1604
1605	dispatch_source_set_event_handler(child_sig_src, ^{ dispatch_semaphore_signal(child_ready_sem); });
1606	dispatch_activate(child_sig_src);
1607
1608	// Spawn child
1609	pid_t pid;
1610	T_LOG("spawning translated child");
1611	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawn(&pid, args[0], NULL, NULL, args, NULL), "spawned process '%s' with PID %d", args[0], pid);
1612
1613	// Wait for the the child to spawn up
1614	dispatch_semaphore_wait(child_ready_sem, DISPATCH_TIME_FOREVER);
1615
1616	// Make sure the child is running and is translated
1617	int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1618	struct kinfo_proc process_info;
1619	size_t bufsize = sizeof(process_info);
1620	T_QUIET; T_ASSERT_POSIX_SUCCESS(sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &process_info, &bufsize, NULL, 0), "get translated child process info");
1621	T_QUIET; T_ASSERT_GT(bufsize, (size_t)0, "process info is not empty");
1622	T_QUIET; T_ASSERT_TRUE((process_info.kp_proc.p_flag & P_TRANSLATED), "KERN_PROC_PID reports child is translated");
1623
1624	T_LOG("capturing stackshot");
1625
1626	struct scenario scenario = {
1627		.name = "translated",
1628		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
1629				  | STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
1630	};
1631
1632	take_stackshot(&scenario, true, ^( void *ssbuf, size_t sslen) {
1633		parse_stackshot(PARSE_STACKSHOT_TRANSLATED, ssbuf, sslen, @{translated_child_pid_key: @(pid)});
1634	});
1635
1636    // Kill the child
1637    int status;
1638    T_QUIET; T_ASSERT_POSIX_SUCCESS(kill(pid, SIGTERM), "kill translated child");
1639    T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &status, 0), "waitpid on translated child");
1640
1641}
1642
1643T_DECL(proc_uuid_info, "tests that the main binary UUID for a proc is always populated", T_META_TAG_VM_PREFERRED)
1644{
1645	struct proc_uniqidentifierinfo proc_info_data = { };
1646	mach_msg_type_number_t      count;
1647	kern_return_t               kernel_status;
1648	task_dyld_info_data_t       task_dyld_info;
1649	struct dyld_all_image_infos *target_infos;
1650	int retval;
1651	bool found_image_in_image_infos = false;
1652	uint64_t expected_mach_header_offset = 0;
1653
1654	/* Find the UUID of our main binary */
1655	retval = proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO, 0, &proc_info_data, sizeof(proc_info_data));
1656	T_QUIET; T_EXPECT_POSIX_SUCCESS(retval, "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO");
1657	T_QUIET; T_ASSERT_EQ_INT(retval, (int) sizeof(proc_info_data), "proc_pidinfo PROC_PIDUNIQIDENTIFIERINFO returned data");
1658
1659	uuid_string_t str = {};
1660	uuid_unparse(*(uuid_t*)&proc_info_data.p_uuid, str);
1661	T_LOG("Found current UUID is %s", str);
1662
1663	/* Find the location of the dyld image info metadata */
1664	count = TASK_DYLD_INFO_COUNT;
1665	kernel_status = task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count);
1666	T_QUIET; T_ASSERT_EQ(kernel_status, KERN_SUCCESS, "retrieve task_info for TASK_DYLD_INFO");
1667
1668	target_infos = (struct dyld_all_image_infos *)task_dyld_info.all_image_info_addr;
1669
1670	/* Find our binary in the dyld image info array */
1671	for (int i = 0; i < (int) target_infos->uuidArrayCount; i++) {
1672		if (uuid_compare(target_infos->uuidArray[i].imageUUID, *(uuid_t*)&proc_info_data.p_uuid) == 0) {
1673			expected_mach_header_offset = (uint64_t) target_infos->uuidArray[i].imageLoadAddress;
1674			found_image_in_image_infos = true;
1675		}
1676	}
1677
1678	T_ASSERT_TRUE(found_image_in_image_infos, "found binary image in dyld image info list");
1679
1680	/* Overwrite the dyld image info data so the kernel has to fallback to the UUID stored in the proc structure */
1681	target_infos->uuidArrayCount = 0;
1682
1683	struct scenario scenario = {
1684		.name = "proc_uuid_info",
1685		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
1686		.target_pid = getpid(),
1687	};
1688
1689	T_LOG("attempting to take stackshot for current PID");
1690	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1691		stackshot_verify_current_proc_uuid_info(ssbuf, sslen, expected_mach_header_offset, &proc_info_data);
1692	});
1693}
1694
1695T_DECL(cseg_waitinfo, "test that threads stuck in the compressor report correct waitinfo", T_META_TAG_VM_PREFERRED)
1696{
1697	struct scenario scenario = {
1698		.name = "cseg_waitinfo",
1699		.quiet = false,
1700		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
1701	};
1702	__block uint64_t thread_id = 0;
1703
1704	dispatch_queue_t dq = dispatch_queue_create("com.apple.stackshot.cseg_waitinfo", NULL);
1705	dispatch_semaphore_t child_ok = dispatch_semaphore_create(0);
1706
1707	dispatch_async(dq, ^{
1708		pthread_threadid_np(NULL, &thread_id);
1709		dispatch_semaphore_signal(child_ok);
1710		int val = 1;
1711		T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.cseg_wedge_thread", NULL, NULL, &val, sizeof(val)), "wedge child thread");
1712	});
1713
1714	dispatch_semaphore_wait(child_ok, DISPATCH_TIME_FOREVER);
1715	sleep(1);
1716
1717	T_LOG("taking stackshot");
1718	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1719		int val = 1;
1720		T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.cseg_unwedge_thread", NULL, NULL, &val, sizeof(val)), "unwedge child thread");
1721		parse_stackshot(PARSE_STACKSHOT_WAITINFO_CSEG, ssbuf, sslen, @{cseg_expected_threadid_key: @(thread_id)});
1722	});
1723}
1724
1725static void
1726srp_send(
1727	mach_port_t send_port,
1728	mach_port_t reply_port,
1729	mach_port_t msg_port)
1730{
1731	kern_return_t ret = 0;
1732
1733	struct test_msg {
1734		mach_msg_header_t header;
1735		mach_msg_body_t body;
1736		mach_msg_port_descriptor_t port_descriptor;
1737	};
1738	struct test_msg send_msg = {
1739		.header = {
1740			.msgh_remote_port = send_port,
1741			.msgh_local_port  = reply_port,
1742			.msgh_bits        = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_COPY_SEND,
1743	    reply_port ? MACH_MSG_TYPE_MAKE_SEND_ONCE : 0,
1744	    MACH_MSG_TYPE_MOVE_SEND,
1745	    MACH_MSGH_BITS_COMPLEX),
1746			.msgh_id          = 0x100,
1747			.msgh_size        = sizeof(send_msg),
1748		},
1749		.body = {
1750			.msgh_descriptor_count = 1,
1751		},
1752		.port_descriptor = {
1753			.name        = msg_port,
1754			.disposition = MACH_MSG_TYPE_MOVE_RECEIVE,
1755			.type        = MACH_MSG_PORT_DESCRIPTOR,
1756		},
1757	};
1758
1759	if (msg_port == MACH_PORT_NULL) {
1760		send_msg.body.msgh_descriptor_count = 0;
1761	}
1762
1763	ret = mach_msg(&(send_msg.header),
1764	    MACH_SEND_MSG |
1765	    MACH_SEND_TIMEOUT |
1766	    MACH_SEND_OVERRIDE,
1767	    send_msg.header.msgh_size,
1768	    0,
1769	    MACH_PORT_NULL,
1770	    10000,
1771	    0);
1772
1773	T_ASSERT_MACH_SUCCESS(ret, "client mach_msg");
1774}
1775
1776T_HELPER_DECL(srp_client,
1777    "Client used for the special_reply_port test")
1778{
1779	pid_t ppid = getppid();
1780	dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
1781	dispatch_queue_t dq = dispatch_queue_create("client_signalqueue", NULL);
1782	dispatch_source_t sig_src;
1783
1784	mach_msg_return_t mr;
1785	mach_port_t service_port;
1786	mach_port_t conn_port;
1787	mach_port_t special_reply_port;
1788	mach_port_options_t opts = {
1789		.flags = MPO_INSERT_SEND_RIGHT,
1790	};
1791
1792	signal(SIGUSR1, SIG_IGN);
1793	sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dq);
1794
1795	dispatch_source_set_event_handler(sig_src, ^{
1796			dispatch_semaphore_signal(can_continue);
1797	});
1798	dispatch_activate(sig_src);
1799
1800	/* lookup the mach service port for the parent */
1801	kern_return_t kr = bootstrap_look_up(bootstrap_port,
1802	    SRP_SERVICE_NAME, &service_port);
1803	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "client bootstrap_look_up");
1804
1805	/* create the send-once right (special reply port) and message to send to the server */
1806	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &conn_port);
1807	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
1808
1809	special_reply_port = thread_get_special_reply_port();
1810	T_QUIET; T_ASSERT_TRUE(MACH_PORT_VALID(special_reply_port), "get_thread_special_reply_port");
1811
1812	/* send the message with the special reply port */
1813	srp_send(service_port, special_reply_port, conn_port);
1814
1815	/* signal the parent to continue */
1816	kill(ppid, SIGUSR1);
1817
1818	struct {
1819		mach_msg_header_t header;
1820		mach_msg_body_t body;
1821		mach_msg_port_descriptor_t port_descriptor;
1822	} rcv_msg = {
1823		.header =
1824		{
1825			.msgh_remote_port = MACH_PORT_NULL,
1826			.msgh_local_port  = special_reply_port,
1827			.msgh_size        = sizeof(rcv_msg),
1828		},
1829	};
1830
1831	/* wait on the reply from the parent (that we will never receive) */
1832	mr = mach_msg(&(rcv_msg.header),
1833			(MACH_RCV_MSG | MACH_RCV_SYNC_WAIT),
1834			0,
1835			rcv_msg.header.msgh_size,
1836			special_reply_port,
1837			MACH_MSG_TIMEOUT_NONE,
1838			service_port);
1839
1840	/* not expected to execute as parent will SIGKILL client... */
1841	T_LOG("client process exiting after sending message to parent (server)");
1842}
1843
1844enum srp_test_type {
1845	SRP_TEST_THREAD,	/* expect waiter on current thread */
1846	SRP_TEST_PID,		/* expect waiter on current PID */
1847	SRP_TEST_EITHER,	/* waiter could be on either */
1848};
1849
1850static void
1851check_srp_test(const char *name, enum srp_test_type ty)
1852{
1853	struct scenario scenario = {
1854		.name = name,
1855		.quiet = false,
1856		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
1857	};
1858	uint64_t thread_id = 0;
1859	pthread_threadid_np(NULL, &thread_id);
1860	if (ty == SRP_TEST_THREAD) {
1861		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1862			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1863					@{srp_expected_threadid_key: @(thread_id)});
1864		});
1865	} else if (ty == SRP_TEST_PID) {
1866		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1867			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1868					@{srp_expected_pid_key: @(getpid())});
1869		});
1870	} else {
1871		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
1872			parse_stackshot(PARSE_STACKSHOT_WAITINFO_SRP, ssbuf, sslen,
1873					@{srp_expected_pid_key: @(getpid()), srp_expected_threadid_key: @(thread_id)});
1874		});
1875	}
1876
1877}
1878
1879
1880/*
1881 * Tests the stackshot wait info plumbing for synchronous IPC that doesn't use kevent on the server.
1882 *
1883 * (part 1): tests the scenario where a client sends a request that includes a special reply port
1884 *           to a server that doesn't receive the message and doesn't copy the send-once right
1885 *           into its address space as a result. for this case the special reply port is enqueued
1886 *           in a port and we check which task has that receive right and use that info. (rdar://60440338)
1887 * (part 2): tests the scenario where a client sends a request that includes a special reply port
1888 *           to a server that receives the message and copies in the send-once right, but doesn't
1889 *           reply to the client. for this case the special reply port is copied out and the kernel
1890 *           stashes the info about which task copied out the send once right. (rdar://60440592)
1891 * (part 3): tests the same as part 2, but uses kevents, which allow for
1892 *           priority inheritance
1893 */
1894T_DECL(special_reply_port, "test that tasks using special reply ports have correct waitinfo", T_META_TAG_VM_PREFERRED)
1895{
1896	dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
1897	dispatch_queue_t dq = dispatch_queue_create("signalqueue", NULL);
1898	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
1899	dispatch_source_t sig_src;
1900	char path[PATH_MAX];
1901	uint32_t path_size = sizeof(path);
1902	T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
1903	char *client_args[] = { path, "-n", "srp_client", NULL };
1904	pid_t client_pid;
1905	int sp_ret;
1906	kern_return_t kr;
1907	mach_port_t port;
1908
1909	/* setup the signal handler in the parent (server) */
1910	T_LOG("setup sig handlers");
1911	signal(SIGUSR1, SIG_IGN);
1912	sig_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGUSR1, 0, dq);
1913
1914	dispatch_source_set_event_handler(sig_src, ^{
1915			dispatch_semaphore_signal(can_continue);
1916	});
1917	dispatch_activate(sig_src);
1918
1919	/* register with the mach service name so the client can lookup and send a message to the parent (server) */
1920	T_LOG("Server about to check in");
1921	kr = bootstrap_check_in(bootstrap_port, SRP_SERVICE_NAME, &port);
1922	T_ASSERT_MACH_SUCCESS(kr, "server bootstrap_check_in");
1923
1924	T_LOG("Launching client");
1925	sp_ret = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
1926	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", client_args[0], client_pid);
1927	T_LOG("Spawned client as PID %d", client_pid);
1928
1929	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
1930	T_LOG("Ready to take stackshot, but waiting 1s for the coast to clear");
1931
1932	/*
1933	 * can_continue indicates the client has signaled us, but we want to make
1934	 * sure they've actually blocked sending their mach message.  It's cheesy, but
1935	 * sleep() works for this.
1936	 */
1937	sleep(1);
1938
1939	/*
1940	 * take the stackshot without calling receive to verify that the stackshot wait
1941	 * info shows our (the server) thread for the scenario where the server has yet to
1942	 * receive the message.
1943	 */
1944	T_LOG("Taking stackshot for part 1 coverage");
1945	check_srp_test("srp", SRP_TEST_THREAD);
1946
1947	/*
1948	 * receive the message from the client (which should copy the send once right into
1949	 * our address space).
1950	 */
1951	struct {
1952		mach_msg_header_t header;
1953		mach_msg_body_t body;
1954		mach_msg_port_descriptor_t port_descriptor;
1955	} rcv_msg = {
1956		.header =
1957		{
1958			.msgh_remote_port = MACH_PORT_NULL,
1959			.msgh_local_port  = port,
1960			.msgh_size        = sizeof(rcv_msg),
1961		},
1962	};
1963
1964	T_LOG("server: starting sync receive\n");
1965
1966	mach_msg_return_t mr;
1967	mr = mach_msg(&(rcv_msg.header),
1968			(MACH_RCV_MSG | MACH_RCV_TIMEOUT),
1969			0,
1970			4096,
1971			port,
1972			10000,
1973			MACH_PORT_NULL);
1974	T_QUIET; T_ASSERT_MACH_SUCCESS(mr, "mach_msg() recieve of message from client");
1975
1976	/*
1977	 * take the stackshot to verify that the stackshot wait info shows our (the server) PID
1978	 * for the scenario where the server has received the message and copied in the send-once right.
1979	 */
1980	T_LOG("Taking stackshot for part 2 coverage");
1981	check_srp_test("srp", SRP_TEST_PID);
1982
1983	/* cleanup - kill the client */
1984	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
1985	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
1986
1987	// do it again, but using kevents
1988	T_LOG("Launching client");
1989	sp_ret = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
1990	T_QUIET; T_ASSERT_POSIX_ZERO(sp_ret, "spawned process '%s' with PID %d", client_args[0], client_pid);
1991	T_LOG("Spawned client as PID %d", client_pid);
1992
1993	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
1994	T_LOG("Ready to take stackshot, but waiting 1s for the coast to clear");
1995
1996	/*
1997	 * can_continue indicates the client has signaled us, but we want to make
1998	 * sure they've actually blocked sending their mach message.  It's cheesy, but
1999	 * sleep() works for this.
2000	 */
2001	sleep(1);
2002
2003	dispatch_mach_t dispatch_mach = dispatch_mach_create(SRP_SERVICE_NAME, machdq,
2004	    ^(dispatch_mach_reason_t reason,
2005	      dispatch_mach_msg_t message,
2006	      mach_error_t error __unused) {
2007		switch (reason) {
2008		case DISPATCH_MACH_MESSAGE_RECEIVED: {
2009			size_t size = 0;
2010			mach_msg_header_t *msg __unused = dispatch_mach_msg_get_msg(message, &size);
2011			T_LOG("server: recieved %ld byte message", size);
2012			check_srp_test("turnstile_port_thread", SRP_TEST_THREAD);
2013			T_LOG("server: letting client go");
2014			// drop the message on the ground, we'll kill the client later
2015			dispatch_semaphore_signal(can_continue);
2016			break;
2017		}
2018		default:
2019			break;
2020		}
2021	});
2022
2023	dispatch_mach_connect(dispatch_mach, port, MACH_PORT_NULL, NULL);
2024
2025	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
2026
2027	/* cleanup - kill the client */
2028	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
2029	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
2030}
2031
2032T_HELPER_DECL(throtlled_sp_client,
2033	"client that uses a connection port to send a message to a server")
2034{
2035	mach_port_t conn_port, service_port, reply_port, *stash;
2036	mach_msg_type_number_t stash_cnt = 0;
2037
2038	kern_return_t kr = mach_ports_lookup(mach_task_self(), &stash, &stash_cnt);
2039	T_ASSERT_MACH_SUCCESS(kr, "mach_ports_lookup");
2040
2041	service_port = stash[0];
2042	T_ASSERT_TRUE(MACH_PORT_VALID(service_port), "valid service port");
2043	mig_deallocate((vm_address_t)stash, stash_cnt * sizeof(stash[0]));
2044
2045	mach_port_options_t opts = {
2046		.flags = MPO_INSERT_SEND_RIGHT
2047			| MPO_CONNECTION_PORT,
2048		.service_port_name = service_port,
2049	};
2050
2051	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &conn_port);
2052	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
2053
2054	mach_port_options_t opts2 = {
2055		.flags = MPO_REPLY_PORT
2056	};
2057	kr = mach_port_construct(mach_task_self(), &opts2, 0ull, &reply_port);
2058	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
2059
2060	/* XPC-like check-in message */
2061	struct {
2062		mach_msg_header_t header;
2063		mach_msg_port_descriptor_t recvp;
2064		mach_msg_port_descriptor_t sendp;
2065	} checkin_message = {
2066		.header =
2067		{
2068			.msgh_remote_port = service_port,
2069			.msgh_local_port = MACH_PORT_NULL,
2070			.msgh_size = sizeof(checkin_message),
2071			.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0),
2072		},
2073		.recvp =
2074		{
2075			.type = MACH_MSG_PORT_DESCRIPTOR,
2076			.name = conn_port,
2077			.disposition = MACH_MSG_TYPE_MOVE_RECEIVE,
2078		},
2079		.sendp =
2080		{
2081			.type = MACH_MSG_PORT_DESCRIPTOR,
2082			.name = reply_port,
2083			.disposition = MACH_MSG_TYPE_MAKE_SEND,
2084		}
2085	};
2086	dispatch_mach_msg_t dmsg = dispatch_mach_msg_create((mach_msg_header_t *)&checkin_message, sizeof(checkin_message),
2087		DISPATCH_MACH_MSG_DESTRUCTOR_DEFAULT, NULL);
2088
2089	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
2090	dispatch_mach_t dchannel = dispatch_mach_create(THROTTLED_SERVICE_NAME, machdq,
2091		^(dispatch_mach_reason_t reason,
2092	      dispatch_mach_msg_t message __unused,
2093	      mach_error_t error __unused) {
2094		switch (reason) {
2095			case DISPATCH_MACH_CONNECTED:
2096				T_LOG("mach channel connected");
2097				break;
2098			case DISPATCH_MACH_MESSAGE_SENT:
2099				T_LOG("sent mach message");
2100				break;
2101			default:
2102				T_ASSERT_FAIL("Unexpected reply to channel reason %lu", reason);
2103		}
2104	});
2105	dispatch_mach_connect(dchannel, reply_port, service_port, dmsg);
2106	dispatch_release(dmsg);
2107
2108	struct {
2109		mach_msg_header_t header;
2110		uint64_t request_id;
2111	} request = {
2112		.header =
2113		{
2114			.msgh_size = sizeof(request),
2115			.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE),
2116		},
2117		.request_id = 1,
2118	};
2119	dispatch_mach_msg_t dmsg2 = dispatch_mach_msg_create((mach_msg_header_t *)&request, sizeof(request),
2120		DISPATCH_MACH_MSG_DESTRUCTOR_DEFAULT, NULL);
2121
2122	dispatch_mach_reason_t reason;
2123	mach_error_t error;
2124
2125	/* send the check-in message and the request message */
2126	dispatch_mach_msg_t dreply = dispatch_mach_send_with_result_and_wait_for_reply(dchannel,
2127			dmsg2, 0, DISPATCH_MACH_SEND_DEFAULT, &reason, &error);
2128	dispatch_release(dmsg2);
2129
2130	/* not expected to execute as parent will SIGKILL client */
2131	T_ASSERT_FAIL("client process exiting after receiving %s reply", dreply ? "non-null" : "null");
2132}
2133
2134static void
2135check_throttled_sp(const char *test_name, uint64_t context, bool is_throttled)
2136{
2137	struct scenario scenario = {
2138		.name = test_name,
2139		.quiet = false,
2140		.flags = (STACKSHOT_THREAD_WAITINFO | STACKSHOT_KCDATA_FORMAT),
2141	};
2142
2143	T_LOG("taking stackshot %s", test_name);
2144	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2145		parse_stackshot(PARSE_STACKSHOT_THROTTLED_SP, ssbuf, sslen,
2146					@{sp_throttled_expected_ctxt_key: @(context),
2147					sp_throttled_expect_flag: @(is_throttled)});
2148	});
2149}
2150
2151/* Take stackshot when a client is blocked on the service port of a process, in the scenario when
2152 * the process with the receive right for the service port is:
2153 *     (a) Monitoring the service port using kevents
2154 *     (b) Not monitoring the service port
2155 */
2156T_DECL(throttled_sp,
2157	"test that service port throttled flag is propagated to the stackshot correctly", T_META_TAG_VM_PREFERRED)
2158{
2159	mach_port_t service_port;
2160	__block dispatch_semaphore_t can_continue  = dispatch_semaphore_create(0);
2161
2162	char path[PATH_MAX];
2163	uint32_t path_size = sizeof(path);
2164	T_ASSERT_POSIX_ZERO(_NSGetExecutablePath(path, &path_size), "_NSGetExecutablePath");
2165	char *client_args[] = { path, "-n", "throtlled_sp_client", NULL };
2166
2167	__block	uint64_t thread_id = 0;
2168	pid_t client_pid;
2169	int mark_throttled;
2170
2171	struct mach_service_port_info sp_info = {};
2172	strcpy(sp_info.mspi_string_name, THROTTLED_SERVICE_NAME);
2173	sp_info.mspi_domain_type = (uint8_t)1;
2174	kern_return_t kr;
2175
2176	mach_port_options_t opts = {
2177		.flags = MPO_SERVICE_PORT | MPO_INSERT_SEND_RIGHT | MPO_CONTEXT_AS_GUARD | MPO_STRICT | MPO_TEMPOWNER,
2178		.service_port_info = &sp_info,
2179	};
2180
2181	kr = mach_port_construct(mach_task_self(), &opts, 0ull, &service_port);
2182	T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct %u", service_port);
2183
2184	/* Setup a dispatch source to monitor the service port similar to how launchd does. */
2185	dispatch_queue_t machdq = dispatch_queue_create("machqueue", NULL);
2186	dispatch_source_t mach_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, service_port,
2187		DISPATCH_MACH_RECV_SYNC_PEEK, machdq);
2188	dispatch_source_set_event_handler(mach_src, ^{
2189		pthread_threadid_np(NULL, &thread_id);
2190		dispatch_semaphore_signal(can_continue);
2191	});
2192	dispatch_activate(mach_src);
2193
2194	/* Stash the port in task to make sure child also gets it */
2195	kr = mach_ports_register(mach_task_self(), &service_port, 1);
2196	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_ports_register service port");
2197
2198	mark_throttled = 1;
2199	kr = mach_port_set_attributes(mach_task_self(), service_port, MACH_PORT_SERVICE_THROTTLED, (mach_port_info_t)(&mark_throttled),
2200	           MACH_PORT_SERVICE_THROTTLED_COUNT);
2201	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mark service port as throttled");
2202
2203	int rc = posix_spawn(&client_pid, client_args[0], NULL, NULL, client_args, NULL);
2204	T_QUIET; T_ASSERT_POSIX_ZERO(rc, "spawned process '%s' with PID %d", client_args[0], client_pid);
2205	T_LOG("Spawned client as PID %d", client_pid);
2206
2207	dispatch_semaphore_wait(can_continue, DISPATCH_TIME_FOREVER);
2208
2209	/* The service port has received the check-in message. Take stackshot for scenario (a). */
2210	check_throttled_sp("throttled_service_port_monitored", thread_id, true);
2211
2212	/* This simulates a throttled spawn when the service port is no longer monitored. */
2213	dispatch_source_cancel(mach_src);
2214
2215	/* Take stackshot for scenario (b) */
2216	check_throttled_sp("throttled_service_port_unmonitored", (uint64_t)getpid(), true);
2217
2218	mark_throttled = 0;
2219	kr = mach_port_set_attributes(mach_task_self(), service_port, MACH_PORT_SERVICE_THROTTLED, (mach_port_info_t)(&mark_throttled),
2220	           MACH_PORT_SERVICE_THROTTLED_COUNT);
2221	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "unmark service port as throttled");
2222
2223	/* Throttled flag should not be set when the port is not throttled. */
2224	check_throttled_sp("unthrottled_service_port_unmonitored", (uint64_t)getpid(), false);
2225
2226	/* cleanup - kill the client */
2227	T_ASSERT_POSIX_SUCCESS(kill(client_pid, SIGKILL), "killing client");
2228	T_ASSERT_POSIX_SUCCESS(waitpid(client_pid, NULL, 0), "waiting for the client to exit");
2229}
2230
2231
2232char *const clpcctrl_path = "/usr/local/bin/clpcctrl";
2233
2234static void
2235run_clpcctrl(char *const argv[]) {
2236	posix_spawnattr_t sattr;
2237	pid_t pid;
2238	int wstatus;
2239
2240	T_QUIET; T_ASSERT_POSIX_ZERO(posix_spawn(&pid, argv[0], NULL, NULL, argv, NULL), "spawn clpcctrl");
2241	T_QUIET; T_ASSERT_POSIX_SUCCESS(waitpid(pid, &wstatus, 0), "wait for clpcctrl");
2242	T_QUIET; T_ASSERT_TRUE(WIFEXITED(wstatus), "clpcctrl exited normally");
2243	T_QUIET; T_ASSERT_POSIX_ZERO(WEXITSTATUS(wstatus), "clpcctrl exited successfully");
2244
2245	uint64_t sched_recommended_cores = 1;
2246	size_t sched_recommended_cores_sz = sizeof(uint64_t);
2247	T_QUIET; T_ASSERT_POSIX_SUCCESS(
2248	    sysctlbyname("kern.sched_recommended_cores", &sched_recommended_cores, &sched_recommended_cores_sz, NULL, 0),
2249	    "get kern.sched_recommended_cores");
2250	T_LOG("Recommended cores: 0x%llx", sched_recommended_cores);
2251}
2252
2253static void
2254restore_clpcctrl() {
2255	run_clpcctrl((char *const []) { clpcctrl_path, "-d", NULL });
2256}
2257
2258#define CLUSTER_TYPE_SMP 0
2259#define CLUSTER_TYPE_E 1
2260#define CLUSTER_TYPE_P 2
2261
2262void test_stackshot_cpu_info(void *ssbuf, size_t sslen, int exp_cpus, NSArray *exp_cluster_types) {
2263	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2264	bool seen = false;
2265	int singlethread_override = 0;
2266	size_t singlethread_override_sz = sizeof(singlethread_override);
2267	T_QUIET; T_ASSERT_POSIX_SUCCESS(
2268		sysctlbyname("kern.stackshot_single_thread", &singlethread_override, &singlethread_override_sz, NULL, 0),
2269		"get kern.stackshot_single_thread");
2270	if (singlethread_override) {
2271		T_LOG("skipping cpu count/type check due to single-thread override (kern.stackshot_single_thread=1)");
2272		return;
2273	}
2274
2275	KCDATA_ITER_FOREACH(iter) {
2276		if ((kcdata_iter_type(iter) != KCDATA_TYPE_ARRAY) || (kcdata_iter_array_elem_type(iter) != STACKSHOT_KCTYPE_LATENCY_INFO_CPU)) {
2277			continue;
2278		}
2279
2280		seen = true;
2281
2282		/* Check ncpus */
2283		int ncpus = kcdata_iter_array_elem_count(iter);
2284		if (exp_cpus != -1) {
2285			T_QUIET; T_ASSERT_EQ(exp_cpus, ncpus, "Expected number of CPUs matches number of CPUs used for stackshot");
2286		}
2287
2288		if (exp_cluster_types == nil) {
2289			continue;
2290		}
2291
2292		/* Check cluster types */
2293		struct stackshot_latency_cpu *latencies = (struct stackshot_latency_cpu *) kcdata_iter_payload(iter);
2294		for (int i = 0; i < ncpus; i++) {
2295			NSNumber *cluster_type = [NSNumber numberWithInt:latencies[i].cluster_type];
2296			T_QUIET; T_ASSERT_TRUE([exp_cluster_types containsObject:cluster_type], "Type of CPU cluster in expected CPU cluster types");
2297		}
2298	}
2299
2300	T_QUIET; T_ASSERT_TRUE(seen || !is_development_kernel(), "Seen CPU latency info or is release kernel");
2301}
2302
2303void test_stackshot_with_clpcctrl(char *const name, char *const argv[], int exp_cpus, NSArray *exp_cluster_types) {
2304	T_LOG("Stackshot CLPC scenario %s", name);
2305	run_clpcctrl(argv);
2306	struct scenario scenario = {
2307		.name = name,
2308		.flags = (STACKSHOT_KCDATA_FORMAT | STACKSHOT_SAVE_LOADINFO |
2309			STACKSHOT_THREAD_WAITINFO | STACKSHOT_GET_GLOBAL_MEM_STATS)
2310	};
2311	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2312		parse_stackshot(0, ssbuf, sslen, nil);
2313		test_stackshot_cpu_info(ssbuf, sslen, exp_cpus, exp_cluster_types);
2314	});
2315}
2316
2317T_DECL(core_masks,
2318	"test that stackshot works under various core masks on ARM systems",
2319	T_META_REQUIRES_SYSCTL_EQ("hw.optional.arm64", 1),
2320	T_META_REQUIRES_SYSCTL_NE("kern.kasan.available", 1), /* rdar://115577993 */
2321	XNU_T_META_REQUIRES_DEVELOPMENT_KERNEL,
2322	T_META_REQUIRE_NOT_VIRTUALIZED,
2323	T_META_RUN_CONCURRENTLY(false),
2324	T_META_TAG_VM_NOT_ELIGIBLE,
2325	T_META_ENABLED(!TARGET_OS_VISION)) // disable for visionOS: device may not be stable with many cores masked off (127904530)
2326{
2327	/*
2328	 * Make sure we're not in a release kernel
2329	 * (cannot check with T_META; only one sysctl T_META at a time will work)
2330	 */
2331	if (!is_development_kernel()) {
2332		T_SKIP("test was not run because kernel is release; cannot set core masks");
2333		return;
2334	}
2335
2336	/*
2337	 * rdar://115577993 - CLPC compiles as release in KASAN-variant builds,
2338	 * preventing clpcctrl from working. For now, skip this. (Cannot check
2339	 * with T_META; only one sysctl T_META at a time will work)
2340	 */
2341	int kasan_avail = 0;
2342	size_t kasan_avail_sz = sizeof(kasan_avail);
2343	sysctlbyname("kern.kasan.available", &kasan_avail, &kasan_avail_sz, NULL, 0);
2344	if (kasan_avail) {
2345		T_SKIP("test was not run because kernel is KASAN; cannot set core masks (see rdar://115577993)");
2346		return;
2347	}
2348
2349
2350	T_ATEND(restore_clpcctrl);
2351
2352	/* Test with 1 and 2 CPUs for basic functionality */
2353	test_stackshot_with_clpcctrl(
2354		"core_masks_1cpu", (char *const[]) {clpcctrl_path, "-c", "1", NULL},
2355		1, nil);
2356
2357	test_stackshot_with_clpcctrl(
2358		"core_masks_2cpus", (char *const[]) {clpcctrl_path, "-c", "2", NULL},
2359		2, nil);
2360
2361	/* Check nperflevels to see if we're on an AMP system */
2362	int nperflevels = 1;
2363	size_t nperflevels_sz = sizeof(int);
2364	T_ASSERT_POSIX_SUCCESS(
2365	    sysctlbyname("hw.nperflevels", &nperflevels, &nperflevels_sz, NULL, 0),
2366	    "get hw.nperflevels");
2367	if (nperflevels == 1) {
2368		T_LOG("On SMP system, skipping stackshot core_masks AMP tests");
2369		return;
2370	}
2371
2372	T_QUIET; T_ASSERT_EQ(nperflevels, 2, "nperflevels is 1 or 2");
2373	T_LOG("On AMP system, performing stackshot core_masks AMP tests");
2374
2375	/* Perform AMP tests with different cluster types active */
2376	test_stackshot_with_clpcctrl(
2377		"core_masks_amp_allcpus",
2378		(char *const[]) {clpcctrl_path, "-C", "all", NULL},
2379		-1, @[@CLUSTER_TYPE_E, @CLUSTER_TYPE_P]);
2380
2381	test_stackshot_with_clpcctrl(
2382		"core_masks_amp_ecpus",
2383		(char *const[]) {clpcctrl_path, "-C", "e", NULL},
2384		-1, @[@CLUSTER_TYPE_E]);
2385
2386	test_stackshot_with_clpcctrl(
2387		"core_masks_amp_pcpus",
2388		(char *const[]) {clpcctrl_path, "-C", "p", NULL},
2389		-1, @[@CLUSTER_TYPE_P]);
2390}
2391
2392#pragma mark performance tests
2393
2394#define SHOULD_REUSE_SIZE_HINT 0x01
2395#define SHOULD_USE_DELTA       0x02
2396#define SHOULD_TARGET_SELF     0x04
2397
2398static void
2399stackshot_perf(unsigned int options)
2400{
2401	struct scenario scenario = {
2402		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_GET_GLOBAL_MEM_STATS
2403			| STACKSHOT_SAVE_IMP_DONATION_PIDS | STACKSHOT_KCDATA_FORMAT),
2404	};
2405
2406	dt_stat_t size = dt_stat_create("bytes", "size");
2407	dt_stat_time_t duration = dt_stat_time_create("duration");
2408	scenario.timer = duration;
2409
2410	if (options & SHOULD_TARGET_SELF) {
2411		scenario.target_pid = getpid();
2412	}
2413
2414	while (!dt_stat_stable(duration) || !dt_stat_stable(size)) {
2415		__block uint64_t last_time = 0;
2416		__block uint32_t size_hint = 0;
2417		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2418			dt_stat_add(size, (double)sslen);
2419			last_time = stackshot_timestamp(ssbuf, sslen);
2420			size_hint = (uint32_t)sslen;
2421		});
2422		if (options & SHOULD_USE_DELTA) {
2423			scenario.since_timestamp = last_time;
2424			scenario.flags |= STACKSHOT_COLLECT_DELTA_SNAPSHOT;
2425		}
2426		if (options & SHOULD_REUSE_SIZE_HINT) {
2427			scenario.size_hint = size_hint;
2428		}
2429	}
2430
2431	dt_stat_finalize(duration);
2432	dt_stat_finalize(size);
2433}
2434
2435static void
2436stackshot_flag_perf_noclobber(uint64_t flag, char *flagname)
2437{
2438	struct scenario scenario = {
2439		.quiet = true,
2440		.flags = (flag | STACKSHOT_KCDATA_FORMAT),
2441	};
2442
2443	dt_stat_t duration = dt_stat_create("nanoseconds per thread", "%s_duration", flagname);
2444	dt_stat_t size = dt_stat_create("bytes per thread", "%s_size", flagname);
2445	T_LOG("Testing \"%s\" = 0x%" PRIx64, flagname, flag);
2446
2447	while (!dt_stat_stable(duration) || !dt_stat_stable(size)) {
2448		take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2449			kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2450			unsigned long no_threads = 0;
2451			mach_timebase_info_data_t timebase = {0, 0};
2452			uint64_t stackshot_duration = 0;
2453			int found = 0;
2454			T_QUIET; T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT, "stackshot buffer");
2455
2456			KCDATA_ITER_FOREACH(iter) {
2457				switch(kcdata_iter_type(iter)) {
2458					case STACKSHOT_KCTYPE_THREAD_SNAPSHOT: {
2459						found |= 1;
2460						no_threads ++;
2461						break;
2462					}
2463					case STACKSHOT_KCTYPE_STACKSHOT_DURATION: {
2464						struct stackshot_duration *ssd = kcdata_iter_payload(iter);
2465						stackshot_duration = ssd->stackshot_duration;
2466						found |= 2;
2467						break;
2468					}
2469					case KCDATA_TYPE_TIMEBASE: {
2470						found |= 4;
2471						mach_timebase_info_data_t *tb = kcdata_iter_payload(iter);
2472						memcpy(&timebase, tb, sizeof(timebase));
2473						break;
2474					}
2475				}
2476			}
2477
2478			T_QUIET; T_ASSERT_EQ(found, 0x7, "found everything needed");
2479
2480			uint64_t ns = (stackshot_duration * timebase.numer) / timebase.denom;
2481			uint64_t per_thread_ns = ns / no_threads;
2482			uint64_t per_thread_size = sslen / no_threads;
2483
2484			dt_stat_add(duration, per_thread_ns);
2485			dt_stat_add(size, per_thread_size);
2486		});
2487	}
2488
2489	dt_stat_finalize(duration);
2490	dt_stat_finalize(size);
2491}
2492
2493static void
2494stackshot_flag_perf(uint64_t flag, char *flagname)
2495{
2496	/*
2497	 * STACKSHOT_NO_IO_STATS disables data collection, so set it for
2498	 * more accurate perfdata collection.
2499	 */
2500	flag |= STACKSHOT_NO_IO_STATS;
2501
2502	stackshot_flag_perf_noclobber(flag, flagname);
2503}
2504
2505
2506T_DECL(flag_perf, "test stackshot performance with different flags set", T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2507{
2508	stackshot_flag_perf_noclobber(STACKSHOT_NO_IO_STATS, "baseline");
2509	stackshot_flag_perf_noclobber(0, "io_stats");
2510
2511	stackshot_flag_perf(STACKSHOT_THREAD_WAITINFO, "thread_waitinfo");
2512	stackshot_flag_perf(STACKSHOT_GET_DQ, "get_dq");
2513	stackshot_flag_perf(STACKSHOT_SAVE_LOADINFO, "save_loadinfo");
2514	stackshot_flag_perf(STACKSHOT_GET_GLOBAL_MEM_STATS, "get_global_mem_stats");
2515	stackshot_flag_perf(STACKSHOT_SAVE_KEXT_LOADINFO, "save_kext_loadinfo");
2516	stackshot_flag_perf(STACKSHOT_SAVE_IMP_DONATION_PIDS, "save_imp_donation_pids");
2517	stackshot_flag_perf(STACKSHOT_ENABLE_BT_FAULTING, "enable_bt_faulting");
2518	stackshot_flag_perf(STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT, "collect_sharedcache_layout");
2519	stackshot_flag_perf(STACKSHOT_ENABLE_UUID_FAULTING, "enable_uuid_faulting");
2520	stackshot_flag_perf(STACKSHOT_THREAD_GROUP, "thread_group");
2521	stackshot_flag_perf(STACKSHOT_SAVE_JETSAM_COALITIONS, "save_jetsam_coalitions");
2522	stackshot_flag_perf(STACKSHOT_INSTRS_CYCLES, "instrs_cycles");
2523	stackshot_flag_perf(STACKSHOT_ASID, "asid");
2524	stackshot_flag_perf(STACKSHOT_EXCLAVES, "all_exclaves");
2525	stackshot_flag_perf(STACKSHOT_EXCLAVES | STACKSHOT_ASID, "all_exclaves_and_asid");
2526	stackshot_flag_perf(STACKSHOT_SKIP_EXCLAVES, "skip_exclaves");
2527}
2528
2529T_DECL(perf_no_size_hint, "test stackshot performance with no size hint",
2530		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2531{
2532	stackshot_perf(0);
2533}
2534
2535T_DECL(perf_size_hint, "test stackshot performance with size hint",
2536		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2537{
2538	stackshot_perf(SHOULD_REUSE_SIZE_HINT);
2539}
2540
2541T_DECL(perf_process, "test stackshot performance targeted at process",
2542		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2543{
2544	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_TARGET_SELF);
2545}
2546
2547T_DECL(perf_delta, "test delta stackshot performance",
2548		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2549{
2550	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA);
2551}
2552
2553T_DECL(perf_delta_no_exclaves, "test delta stackshot performance without Exclaves",
2554	    T_META_REQUIRES_SYSCTL_EQ("kern.exclaves_status", 1),
2555		T_META_REQUIRES_SYSCTL_EQ("kern.exclaves_inspection_status", 1),
2556		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2557{
2558	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA | STACKSHOT_SKIP_EXCLAVES);
2559}
2560
2561T_DECL(perf_delta_process, "test delta stackshot performance targeted at a process",
2562		T_META_TAG_PERF, T_META_TAG_VM_NOT_ELIGIBLE)
2563{
2564	stackshot_perf(SHOULD_REUSE_SIZE_HINT | SHOULD_USE_DELTA | SHOULD_TARGET_SELF);
2565}
2566
2567T_DECL(stackshot_entitlement_report_test, "test stackshot entitlement report", T_META_TAG_VM_PREFERRED)
2568{
2569	int sysctlValue = 1;
2570	T_ASSERT_POSIX_SUCCESS(
2571	    sysctlbyname("debug.stackshot_entitlement_send_batch", NULL, NULL, &sysctlValue, sizeof(sysctlValue)),
2572	    "set debug.stackshot_entitlement_send_batch=1");
2573	// having a way to verify that the coreanalytics event was received would be even better
2574	// See rdar://74197197
2575	T_PASS("entitlement test ran");
2576}
2577
2578static void
2579expect_os_build_version_in_stackshot(void *ssbuf, size_t sslen)
2580{
2581	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2582
2583	bool saw_os_build_version = false;
2584	iter = kcdata_iter_next(iter);
2585
2586	KCDATA_ITER_FOREACH(iter) {
2587		switch (kcdata_iter_type(iter)) {
2588		case STACKSHOT_KCTYPE_OS_BUILD_VERSION:
2589			saw_os_build_version = true;
2590			T_LOG("Found os build version in stackshot: %s", kcdata_iter_payload(iter));
2591			return;
2592
2593		default:
2594			break;
2595		}
2596	}
2597
2598	T_ASSERT_FAIL("didn't see os build version in stackshot");
2599}
2600
2601T_DECL(os_build_version, "test stackshot contains os build version", T_META_TAG_VM_PREFERRED)
2602{
2603
2604	struct scenario scenario = {
2605		.name = "os-build-version",
2606		.flags = (STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT),
2607	};
2608
2609	T_LOG("attempting to take stackshot with an os build version");
2610	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
2611		expect_os_build_version_in_stackshot(ssbuf, sslen);
2612	});
2613}
2614
2615static uint64_t
2616stackshot_timestamp(void *ssbuf, size_t sslen)
2617{
2618	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2619
2620	uint32_t type = kcdata_iter_type(iter);
2621	if (type != KCDATA_BUFFER_BEGIN_STACKSHOT && type != KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT) {
2622		T_ASSERT_FAIL("invalid kcdata type %u", kcdata_iter_type(iter));
2623	}
2624
2625	iter = kcdata_iter_find_type(iter, KCDATA_TYPE_MACH_ABSOLUTE_TIME);
2626	T_QUIET;
2627	T_ASSERT_TRUE(kcdata_iter_valid(iter), "timestamp found in stackshot");
2628
2629	return *(uint64_t *)kcdata_iter_payload(iter);
2630}
2631
2632#define TEST_THREAD_NAME "stackshot_test_thread"
2633
2634static void
2635parse_thread_group_stackshot(void **ssbuf, size_t sslen)
2636{
2637	bool seen_thread_group_snapshot = false;
2638	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2639	T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT,
2640			"buffer provided is a stackshot");
2641
2642	NSMutableSet *thread_groups = [[NSMutableSet alloc] init];
2643
2644	iter = kcdata_iter_next(iter);
2645	KCDATA_ITER_FOREACH(iter) {
2646		switch (kcdata_iter_type(iter)) {
2647		case KCDATA_TYPE_ARRAY: {
2648			T_QUIET;
2649			T_ASSERT_TRUE(kcdata_iter_array_valid(iter),
2650					"checked that array is valid");
2651
2652			if (kcdata_iter_array_elem_type(iter) != STACKSHOT_KCTYPE_THREAD_GROUP_SNAPSHOT) {
2653				continue;
2654			}
2655
2656			seen_thread_group_snapshot = true;
2657
2658			if (kcdata_iter_array_elem_size(iter) >= sizeof(struct thread_group_snapshot_v3)) {
2659				struct thread_group_snapshot_v3 *tgs_array = kcdata_iter_payload(iter);
2660				for (uint32_t j = 0; j < kcdata_iter_array_elem_count(iter); j++) {
2661					struct thread_group_snapshot_v3 *tgs = tgs_array + j;
2662					[thread_groups addObject:@(tgs->tgs_id)];
2663				}
2664			}
2665			else {
2666				struct thread_group_snapshot *tgs_array = kcdata_iter_payload(iter);
2667				for (uint32_t j = 0; j < kcdata_iter_array_elem_count(iter); j++) {
2668					struct thread_group_snapshot *tgs = tgs_array + j;
2669					[thread_groups addObject:@(tgs->tgs_id)];
2670				}
2671			}
2672			break;
2673		}
2674		}
2675	}
2676	KCDATA_ITER_FOREACH(iter) {
2677		NSError *error = nil;
2678
2679		switch (kcdata_iter_type(iter)) {
2680
2681		case KCDATA_TYPE_CONTAINER_BEGIN: {
2682			T_QUIET;
2683			T_ASSERT_TRUE(kcdata_iter_container_valid(iter),
2684					"checked that container is valid");
2685
2686			if (kcdata_iter_container_type(iter) != STACKSHOT_KCCONTAINER_THREAD) {
2687				break;
2688			}
2689
2690			NSDictionary *container = parseKCDataContainer(&iter, &error);
2691			T_QUIET; T_ASSERT_NOTNULL(container, "parsed thread container from stackshot");
2692			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing container");
2693
2694			int tg = [container[@"thread_snapshots"][@"thread_group"] intValue];
2695
2696			T_ASSERT_TRUE([thread_groups containsObject:@(tg)], "check that the thread group the thread is in exists");
2697
2698			break;
2699		};
2700
2701		}
2702	}
2703	T_ASSERT_TRUE(seen_thread_group_snapshot, "check that we have seen a thread group snapshot");
2704}
2705
2706static void
2707verify_stackshot_sharedcache_layout(struct dyld_uuid_info_64 *uuids, uint32_t uuid_count)
2708{
2709	uuid_t cur_shared_cache_uuid;
2710	__block uint32_t lib_index = 0, libs_found = 0;
2711
2712	_dyld_get_shared_cache_uuid(cur_shared_cache_uuid);
2713	int result = dyld_shared_cache_iterate_text(cur_shared_cache_uuid, ^(const dyld_shared_cache_dylib_text_info* info) {
2714			T_QUIET; T_ASSERT_LT(lib_index, uuid_count, "dyld_shared_cache_iterate_text exceeded number of libraries returned by kernel");
2715
2716			libs_found++;
2717			struct dyld_uuid_info_64 *cur_stackshot_uuid_entry = &uuids[lib_index];
2718			T_QUIET; T_ASSERT_EQ(memcmp(info->dylibUuid, cur_stackshot_uuid_entry->imageUUID, sizeof(info->dylibUuid)), 0,
2719					"dyld returned UUID doesn't match kernel returned UUID");
2720			T_QUIET; T_ASSERT_EQ(info->loadAddressUnslid, cur_stackshot_uuid_entry->imageLoadAddress,
2721					"dyld returned load address doesn't match kernel returned load address");
2722			lib_index++;
2723		});
2724
2725	T_ASSERT_EQ(result, 0, "iterate shared cache layout");
2726	T_ASSERT_EQ(libs_found, uuid_count, "dyld iterator returned same number of libraries as kernel");
2727
2728	T_LOG("verified %d libraries from dyld shared cache", libs_found);
2729}
2730
2731static void
2732check_shared_cache_uuid(uuid_t imageUUID)
2733{
2734	static uuid_t shared_cache_uuid;
2735	static dispatch_once_t read_shared_cache_uuid;
2736
2737	dispatch_once(&read_shared_cache_uuid, ^{
2738		T_QUIET;
2739		T_ASSERT_TRUE(_dyld_get_shared_cache_uuid(shared_cache_uuid), "retrieve current shared cache UUID");
2740	});
2741	T_QUIET; T_ASSERT_EQ(uuid_compare(shared_cache_uuid, imageUUID), 0,
2742			"dyld returned UUID doesn't match kernel returned UUID for system shared cache");
2743}
2744
2745/*
2746 * extra dictionary contains data relevant for the given flags:
2747 * PARSE_STACKSHOT_ZOMBIE:   zombie_child_pid_key -> @(pid)
2748 * PARSE_STACKSHOT_POSTEXEC: postexec_child_unique_pid_key -> @(unique_pid)
2749 */
2750static void
2751parse_stackshot(uint64_t stackshot_parsing_flags, void *ssbuf, size_t sslen, NSDictionary *extra)
2752{
2753	bool delta = (stackshot_parsing_flags & PARSE_STACKSHOT_DELTA);
2754	bool expect_sharedcache_child = (stackshot_parsing_flags & PARSE_STACKSHOT_SHAREDCACHE_FLAGS);
2755	bool expect_zombie_child = (stackshot_parsing_flags & PARSE_STACKSHOT_ZOMBIE);
2756	bool expect_postexec_child = (stackshot_parsing_flags & PARSE_STACKSHOT_POSTEXEC);
2757	bool expect_cseg_waitinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_WAITINFO_CSEG);
2758	bool expect_translated_child = (stackshot_parsing_flags & PARSE_STACKSHOT_TRANSLATED);
2759	bool expect_shared_cache_layout = false;
2760	bool expect_shared_cache_uuid = !delta;
2761	bool expect_dispatch_queue_label = (stackshot_parsing_flags & PARSE_STACKSHOT_DISPATCH_QUEUE_LABEL);
2762	bool expect_turnstile_lock = (stackshot_parsing_flags & PARSE_STACKSHOT_TURNSTILEINFO);
2763	bool expect_srp_waitinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_WAITINFO_SRP);
2764	bool expect_sp_throttled = (stackshot_parsing_flags & PARSE_STACKSHOT_THROTTLED_SP);
2765	bool expect_exec_inprogress = (stackshot_parsing_flags & PARSE_STACKSHOT_EXEC_INPROGRESS);
2766	bool expect_transitioning_task = (stackshot_parsing_flags & PARSE_STACKSHOT_TRANSITIONING);
2767	bool expect_asyncstack = (stackshot_parsing_flags & PARSE_STACKSHOT_ASYNCSTACK);
2768	bool expect_driverkit = (stackshot_parsing_flags & PARSE_STACKSHOT_DRIVERKIT);
2769	bool expect_suspendinfo = (stackshot_parsing_flags & PARSE_STACKSHOT_SUSPENDINFO);
2770	bool found_zombie_child = false, found_postexec_child = false, found_shared_cache_layout = false, found_shared_cache_uuid = false;
2771	bool found_translated_child = false, found_transitioning_task = false;
2772	bool found_dispatch_queue_label = false, found_turnstile_lock = false;
2773	bool found_cseg_waitinfo = false, found_srp_waitinfo = false;
2774	bool found_sharedcache_child = false, found_sharedcache_badflags = false, found_sharedcache_self = false;
2775	bool found_asyncstack = false;
2776	bool found_throttled_service = false;
2777	bool found_exclaves = false;
2778	bool expect_single_task = (stackshot_parsing_flags & PARSE_STACKSHOT_TARGETPID);
2779	uint64_t srp_expected_threadid = 0;
2780	pid_t zombie_child_pid = -1, srp_expected_pid = -1, sharedcache_child_pid = -1, throttled_service_ctx = -1;
2781	pid_t translated_child_pid = -1, transistioning_task_pid = -1;
2782	bool sharedcache_child_sameaddr = false, is_throttled = false;
2783	uint64_t postexec_child_unique_pid = 0, cseg_expected_threadid = 0;
2784	uint64_t sharedcache_child_flags = 0, sharedcache_self_flags = 0;
2785	uint64_t asyncstack_threadid = 0;
2786	NSArray *asyncstack_stack = nil;
2787	char *inflatedBufferBase = NULL;
2788	pid_t exec_inprogress_pid = -1;
2789	void (^exec_inprogress_cb)(uint64_t, uint64_t) = NULL;
2790	int exec_inprogress_found = 0;
2791	uint64_t exec_inprogress_containerid = 0;
2792	void (^driverkit_cb)(pid_t) = NULL;
2793	NSMutableDictionary *sharedCaches = [NSMutableDictionary new];
2794	uint64_t expected_num_threads = 0, expected_num_tasks = 0, found_percpu_threads = 0, found_tasks = 0, found_percpu_tasks = 0;
2795	NSMutableSet *seen_tasks = [NSMutableSet new];
2796
2797	if (expect_shared_cache_uuid) {
2798		uuid_t shared_cache_uuid;
2799		if (!_dyld_get_shared_cache_uuid(shared_cache_uuid)) {
2800			T_LOG("Skipping verifying shared cache UUID in stackshot data because not running with a shared cache");
2801			expect_shared_cache_uuid = false;
2802		}
2803	}
2804
2805	if (stackshot_parsing_flags & PARSE_STACKSHOT_SHAREDCACHE_LAYOUT) {
2806		size_t shared_cache_length = 0;
2807		const void *cache_header = _dyld_get_shared_cache_range(&shared_cache_length);
2808		T_QUIET; T_ASSERT_NOTNULL(cache_header, "current process running with shared cache");
2809		T_QUIET; T_ASSERT_GT(shared_cache_length, sizeof(struct _dyld_cache_header), "valid shared cache length populated by _dyld_get_shared_cache_range");
2810
2811		if (_dyld_shared_cache_is_locally_built()) {
2812			T_LOG("device running with locally built shared cache, expect shared cache layout");
2813			expect_shared_cache_layout = true;
2814		} else {
2815			T_LOG("device running with B&I built shared-cache, no shared cache layout expected");
2816		}
2817	}
2818
2819	if (expect_sharedcache_child) {
2820		NSNumber* pid_num = extra[sharedcache_child_pid_key];
2821		NSNumber* sameaddr_num = extra[sharedcache_child_sameaddr_key];
2822		T_QUIET; T_ASSERT_NOTNULL(pid_num, "sharedcache child pid provided");
2823		T_QUIET; T_ASSERT_NOTNULL(sameaddr_num, "sharedcache child addrsame provided");
2824		sharedcache_child_pid = [pid_num intValue];
2825		T_QUIET; T_ASSERT_GT(sharedcache_child_pid, 0, "sharedcache child pid greater than zero");
2826		sharedcache_child_sameaddr = [sameaddr_num intValue];
2827		T_QUIET; T_ASSERT_GE([sameaddr_num intValue], 0, "sharedcache child sameaddr is boolean (0 or 1)");
2828		T_QUIET; T_ASSERT_LE([sameaddr_num intValue], 1, "sharedcache child sameaddr is boolean (0 or 1)");
2829	}
2830
2831    if (expect_transitioning_task) {
2832        NSNumber* pid_num = extra[transitioning_pid_key];
2833        T_ASSERT_NOTNULL(pid_num, "transitioning task pid provided");
2834        transistioning_task_pid = [pid_num intValue];
2835    }
2836
2837	if (expect_zombie_child) {
2838		NSNumber* pid_num = extra[zombie_child_pid_key];
2839		T_QUIET; T_ASSERT_NOTNULL(pid_num, "zombie child pid provided");
2840		zombie_child_pid = [pid_num intValue];
2841		T_QUIET; T_ASSERT_GT(zombie_child_pid, 0, "zombie child pid greater than zero");
2842	}
2843
2844	if (expect_postexec_child) {
2845		NSNumber* unique_pid_num = extra[postexec_child_unique_pid_key];
2846		T_QUIET; T_ASSERT_NOTNULL(unique_pid_num, "postexec child unique pid provided");
2847		postexec_child_unique_pid = [unique_pid_num unsignedLongLongValue];
2848		T_QUIET; T_ASSERT_GT(postexec_child_unique_pid, 0ull, "postexec child unique pid greater than zero");
2849	}
2850
2851	if (expect_cseg_waitinfo) {
2852		NSNumber* tid_num = extra[cseg_expected_threadid_key];
2853		T_QUIET; T_ASSERT_NOTNULL(tid_num, "cseg's expected thread id provided");
2854		cseg_expected_threadid = tid_num.unsignedLongValue;
2855		T_QUIET; T_ASSERT_GT(cseg_expected_threadid, UINT64_C(0), "compressor segment thread is present");
2856	}
2857
2858	if (expect_srp_waitinfo) {
2859		NSNumber* threadid_num = extra[srp_expected_threadid_key];
2860		NSNumber* pid_num = extra[srp_expected_pid_key];
2861		T_QUIET; T_ASSERT_TRUE(threadid_num != nil || pid_num != nil, "expected SRP threadid or pid");
2862		if (threadid_num != nil) {
2863			srp_expected_threadid = [threadid_num unsignedLongLongValue];
2864			T_QUIET; T_ASSERT_GT(srp_expected_threadid, 0ull, "srp_expected_threadid greater than zero");
2865		}
2866		if (pid_num != nil) {
2867			srp_expected_pid = [pid_num intValue];
2868			T_QUIET; T_ASSERT_GT(srp_expected_pid, 0, "srp_expected_pid greater than zero");
2869		}
2870		T_LOG("looking for SRP pid: %d threadid: %llu", srp_expected_pid, srp_expected_threadid);
2871	}
2872
2873	if (expect_sp_throttled) {
2874		NSNumber* ctx = extra[sp_throttled_expected_ctxt_key];
2875		T_QUIET; T_ASSERT_TRUE(ctx != nil, "expected pid");
2876		throttled_service_ctx = [ctx intValue];
2877		T_QUIET; T_ASSERT_GT(throttled_service_ctx, 0, "expected pid greater than zero");
2878
2879		NSNumber *throttled = extra[sp_throttled_expect_flag];
2880		T_QUIET; T_ASSERT_TRUE(throttled != nil, "expected flag value");
2881		is_throttled = ([throttled intValue] != 0);
2882
2883		T_LOG("Looking for service with ctxt: %d, thottled:%d", throttled_service_ctx, is_throttled);
2884	}
2885
2886	if (expect_translated_child) {
2887		NSNumber* pid_num = extra[translated_child_pid_key];
2888		T_QUIET; T_ASSERT_NOTNULL(pid_num, "translated child pid provided");
2889		translated_child_pid = [pid_num intValue];
2890		T_QUIET; T_ASSERT_GT(translated_child_pid, 0, "translated child pid greater than zero");
2891	}
2892	if (expect_exec_inprogress) {
2893		NSNumber* pid_num = extra[exec_inprogress_pid_key];
2894		T_QUIET; T_ASSERT_NOTNULL(pid_num, "exec inprogress pid provided");
2895		exec_inprogress_pid = [pid_num intValue];
2896		T_QUIET; T_ASSERT_GT(exec_inprogress_pid, 0, "exec inprogress pid greater than zero");
2897
2898		exec_inprogress_cb = extra[exec_inprogress_found_key];
2899		T_QUIET; T_ASSERT_NOTNULL(exec_inprogress_cb, "exec inprogress found callback provided");
2900	}
2901	if (expect_driverkit) {
2902		driverkit_cb = extra[driverkit_found_key];
2903		T_QUIET; T_ASSERT_NOTNULL(driverkit_cb, "driverkit found callback provided");
2904	}
2905
2906	if (expect_asyncstack) {
2907		NSNumber* threadid_id = extra[asyncstack_expected_threadid_key];
2908		T_QUIET; T_ASSERT_NOTNULL(threadid_id, "asyncstack threadid provided");
2909		asyncstack_threadid = [threadid_id unsignedLongLongValue];
2910		asyncstack_stack = extra[asyncstack_expected_stack_key];
2911		T_QUIET; T_ASSERT_NOTNULL(asyncstack_stack, "asyncstack expected stack provided");
2912	}
2913
2914	kcdata_iter_t iter = kcdata_iter(ssbuf, sslen);
2915	if (delta) {
2916		T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT,
2917				"buffer provided is a delta stackshot");
2918
2919			iter = kcdata_iter_next(iter);
2920	} else {
2921		if (kcdata_iter_type(iter) != KCDATA_BUFFER_BEGIN_COMPRESSED) {
2922			T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT,
2923					"buffer provided is a stackshot");
2924
2925			iter = kcdata_iter_next(iter);
2926		} else {
2927			/* we are dealing with a compressed buffer */
2928			iter = kcdata_iter_next(iter);
2929			uint64_t compression_type = 0, totalout = 0, totalin = 0;
2930
2931			uint64_t *data;
2932			char *desc;
2933			for (int i = 0; i < 3; i ++) {
2934				kcdata_iter_get_data_with_desc(iter, &desc, (void **)&data, NULL);
2935				if (strcmp(desc, "kcd_c_type") == 0) {
2936					compression_type = *data;
2937				} else if (strcmp(desc, "kcd_c_totalout") == 0){
2938					totalout = *data;
2939				} else if (strcmp(desc, "kcd_c_totalin") == 0){
2940					totalin = *data;
2941				}
2942
2943				iter = kcdata_iter_next(iter);
2944			}
2945
2946			T_ASSERT_EQ(compression_type, UINT64_C(1), "zlib compression is used");
2947			T_ASSERT_GT(totalout, UINT64_C(0), "successfully gathered how long the compressed buffer is");
2948			T_ASSERT_GT(totalin, UINT64_C(0), "successfully gathered how long the uncompressed buffer will be at least");
2949
2950			/* progress to the next kcdata item */
2951			T_ASSERT_EQ(kcdata_iter_type(iter), KCDATA_BUFFER_BEGIN_STACKSHOT, "compressed stackshot found");
2952
2953			char *bufferBase = kcdata_iter_payload(iter);
2954
2955			/*
2956			 * zlib is used, allocate a buffer based on the metadata, plus
2957			 * extra scratch space (+12.5%) in case totalin was inconsistent
2958			 */
2959			size_t inflatedBufferSize = totalin + (totalin >> 3);
2960			inflatedBufferBase = malloc(inflatedBufferSize);
2961			T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(inflatedBufferBase, "allocated temporary output buffer");
2962
2963			z_stream zs;
2964			memset(&zs, 0, sizeof(zs));
2965			T_QUIET; T_ASSERT_EQ(inflateInit(&zs), Z_OK, "inflateInit OK");
2966			zs.next_in = (unsigned char *)bufferBase;
2967			T_QUIET; T_ASSERT_LE(totalout, (uint64_t)UINT_MAX, "stackshot is not too large");
2968			zs.avail_in = (uInt)totalout;
2969			zs.next_out = (unsigned char *)inflatedBufferBase;
2970			T_QUIET; T_ASSERT_LE(inflatedBufferSize, (size_t)UINT_MAX, "output region is not too large");
2971			zs.avail_out = (uInt)inflatedBufferSize;
2972			T_ASSERT_EQ(inflate(&zs, Z_FINISH), Z_STREAM_END, "inflated buffer");
2973			inflateEnd(&zs);
2974
2975			T_ASSERT_EQ((uint64_t)zs.total_out, totalin, "expected number of bytes inflated");
2976
2977			/* copy the data after the compressed area */
2978			T_QUIET; T_ASSERT_GE((void *)bufferBase, ssbuf,
2979					"base of compressed stackshot is after the returned stackshot buffer");
2980			size_t header_size = (size_t)(bufferBase - (char *)ssbuf);
2981			size_t data_after_compressed_size = sslen - totalout - header_size;
2982			T_QUIET; T_ASSERT_LE(data_after_compressed_size,
2983					inflatedBufferSize - zs.total_out,
2984					"footer fits in the buffer");
2985			memcpy(inflatedBufferBase + zs.total_out,
2986					bufferBase + totalout,
2987					data_after_compressed_size);
2988
2989			iter = kcdata_iter(inflatedBufferBase, inflatedBufferSize);
2990		}
2991	}
2992
2993	KCDATA_ITER_FOREACH(iter) {
2994		NSError *error = nil;
2995
2996		switch (kcdata_iter_type(iter)) {
2997		case KCDATA_TYPE_ARRAY: {
2998			T_QUIET;
2999			T_ASSERT_TRUE(kcdata_iter_array_valid(iter),
3000					"checked that array is valid");
3001
3002			NSMutableDictionary *array = parseKCDataArray(iter, &error);
3003			T_QUIET; T_ASSERT_NOTNULL(array, "parsed array from stackshot");
3004			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing array");
3005
3006			if (kcdata_iter_array_elem_type(iter) == STACKSHOT_KCTYPE_SYS_SHAREDCACHE_LAYOUT) {
3007				struct dyld_uuid_info_64 *shared_cache_uuids = kcdata_iter_payload(iter);
3008				uint32_t uuid_count = kcdata_iter_array_elem_count(iter);
3009				T_ASSERT_NOTNULL(shared_cache_uuids, "parsed shared cache layout array");
3010				T_ASSERT_GT(uuid_count, 0, "returned valid number of UUIDs from shared cache");
3011				verify_stackshot_sharedcache_layout(shared_cache_uuids, uuid_count);
3012				found_shared_cache_layout = true;
3013			}
3014
3015			break;
3016		}
3017		case KCDATA_TYPE_CONTAINER_BEGIN: {
3018			T_QUIET;
3019			T_ASSERT_TRUE(kcdata_iter_container_valid(iter),
3020					"checked that container is valid");
3021
3022			uint64_t containerid = kcdata_iter_container_id(iter);
3023			uint32_t container_type = kcdata_iter_container_type(iter);
3024
3025			if (container_type == STACKSHOT_KCCONTAINER_SHAREDCACHE) {
3026				NSDictionary *container = parseKCDataContainer(&iter, &error);
3027				T_QUIET; T_ASSERT_NOTNULL(container, "parsed sharedcache container from stackshot");
3028				T_QUIET; T_ASSERT_NULL(error, "error unset after parsing sharedcache container");
3029				T_QUIET; T_EXPECT_EQ(sharedCaches[@(containerid)], nil, "sharedcache containerid %lld should be unique", containerid);
3030				sharedCaches[@(containerid)] = container;
3031				break;
3032			}
3033
3034			if (container_type == STACKSHOT_KCCONTAINER_EXCLAVES) {
3035				found_exclaves = true;
3036				break;
3037			}
3038
3039			/*
3040			 * treat containers other than tasks/transitioning_tasks
3041			 * as expanded in-line.
3042			 */
3043			if (container_type != STACKSHOT_KCCONTAINER_TASK &&
3044			    container_type != STACKSHOT_KCCONTAINER_TRANSITIONING_TASK) {
3045				T_LOG("container skipped: %d", container_type);
3046				break;
3047			}
3048			NSDictionary *container = parseKCDataContainer(&iter, &error);
3049			T_QUIET; T_ASSERT_NOTNULL(container, "parsed task/transitioning_task container from stackshot");
3050			T_QUIET; T_ASSERT_NULL(error, "error unset after parsing container");
3051
3052			found_tasks++;
3053
3054			NSDictionary* task_snapshot = container[@"task_snapshots"][@"task_snapshot"];
3055			NSDictionary* task_delta_snapshot = container[@"task_snapshots"][@"task_delta_snapshot"];
3056			NSDictionary* transitioning_task_snapshot = container[@"transitioning_task_snapshots"][@"transitioning_task_snapshot"];
3057
3058			NSNumber *task_pid = NULL;
3059			if (task_snapshot) {
3060				task_pid = task_snapshot[@"ts_unique_pid"];
3061			} else if(task_delta_snapshot) {
3062				task_pid = task_snapshot[@"tds_unique_pid"];
3063			} else if(transitioning_task_snapshot) {
3064				task_pid = transitioning_task_snapshot[@"tts_pid"];
3065			}
3066
3067			if (task_pid && [seen_tasks containsObject:task_pid]) {
3068				T_QUIET; T_ASSERT_FALSE([seen_tasks containsObject:task_pid], "No duplicate PIDs in stackshot");
3069				[seen_tasks addObject:task_pid];
3070			}
3071
3072			/*
3073			 * Having processed the container, we now only check it
3074			 * if it's the correct type.
3075			 */
3076			if ((!expect_transitioning_task && (container_type != STACKSHOT_KCCONTAINER_TASK)) ||
3077			    (expect_transitioning_task && (container_type != STACKSHOT_KCCONTAINER_TRANSITIONING_TASK))) {
3078				break;
3079			}
3080			if (!expect_transitioning_task) {
3081			    	T_QUIET; T_ASSERT_TRUE(!!task_snapshot != !!task_delta_snapshot, "Either task_snapshot xor task_delta_snapshot provided");
3082			}
3083
3084			if (expect_dispatch_queue_label && !found_dispatch_queue_label) {
3085				for (id thread_key in container[@"task_snapshots"][@"thread_snapshots"]) {
3086					NSMutableDictionary *thread = container[@"task_snapshots"][@"thread_snapshots"][thread_key];
3087					NSString *dql = thread[@"dispatch_queue_label"];
3088
3089					if ([dql isEqualToString:@TEST_STACKSHOT_QUEUE_LABEL]) {
3090						found_dispatch_queue_label = true;
3091						break;
3092					}
3093				}
3094			}
3095
3096			if (expect_transitioning_task && !found_transitioning_task) {
3097				if (transitioning_task_snapshot) {
3098					uint64_t the_pid = [transitioning_task_snapshot[@"tts_pid"] unsignedLongLongValue];
3099					if (the_pid == (uint64_t)transistioning_task_pid) {
3100					    found_transitioning_task = true;
3101
3102					    T_PASS("FOUND Transitioning task %llu has a transitioning task snapshot", (uint64_t) transistioning_task_pid);
3103					    break;
3104					}
3105				}
3106			}
3107
3108			if (expect_postexec_child && !found_postexec_child) {
3109				if (task_snapshot) {
3110					uint64_t unique_pid = [task_snapshot[@"ts_unique_pid"] unsignedLongLongValue];
3111					if (unique_pid == postexec_child_unique_pid) {
3112						found_postexec_child = true;
3113
3114						T_PASS("post-exec child %llu has a task snapshot", postexec_child_unique_pid);
3115
3116						break;
3117					}
3118				}
3119
3120				if (task_delta_snapshot) {
3121					uint64_t unique_pid = [task_delta_snapshot[@"tds_unique_pid"] unsignedLongLongValue];
3122					if (unique_pid == postexec_child_unique_pid) {
3123						found_postexec_child = true;
3124
3125						T_FAIL("post-exec child %llu shouldn't have a delta task snapshot", postexec_child_unique_pid);
3126
3127						break;
3128					}
3129				}
3130			}
3131
3132			int pid = [task_snapshot[@"ts_pid"] intValue];
3133
3134			if (pid && expect_shared_cache_uuid && !found_shared_cache_uuid) {
3135				id ptr = container[@"task_snapshots"][@"shared_cache_dyld_load_info"];
3136				if (ptr) {
3137					id uuid = ptr[@"imageUUID"];
3138
3139					uint8_t uuid_p[16];
3140					for (unsigned int i = 0; i < 16; i ++) {
3141						NSNumber *uuidByte = uuid[i];
3142						uuid_p[i] = (uint8_t)uuidByte.charValue;
3143					}
3144
3145					check_shared_cache_uuid(uuid_p);
3146
3147					uint64_t baseAddress = (uint64_t)((NSNumber *)ptr[@"imageSlidBaseAddress"]).longLongValue;
3148					uint64_t firstMapping = (uint64_t)((NSNumber *)ptr[@"sharedCacheSlidFirstMapping"]).longLongValue;
3149
3150					T_EXPECT_LE(baseAddress, firstMapping,
3151						"in per-task shared_cache_dyld_load_info, "
3152						"baseAddress <= firstMapping");
3153					T_EXPECT_GE(baseAddress + (7ull << 32) + (1ull << 29),
3154						firstMapping,
3155						"in per-task shared_cache_dyld_load_info, "
3156						"baseAddress + 28.5gig >= firstMapping");
3157
3158					size_t shared_cache_len;
3159					const void *addr = _dyld_get_shared_cache_range(&shared_cache_len);
3160					T_EXPECT_EQ((uint64_t)addr, firstMapping,
3161							"SlidFirstMapping should match shared_cache_range");
3162
3163					/*
3164					 * check_shared_cache_uuid() will assert on failure, so if
3165					 * we get here, then we have found the shared cache UUID
3166					 * and it's correct
3167					 */
3168					found_shared_cache_uuid = true;
3169				}
3170			}
3171
3172			if (expect_sharedcache_child) {
3173				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3174				uint64_t sharedregion_flags = (task_flags & (kTaskSharedRegionNone | kTaskSharedRegionSystem | kTaskSharedRegionOther));
3175				id sharedregion_info = container[@"task_snapshots"][@"shared_cache_dyld_load_info"];
3176				id sharedcache_id = container[@"task_snapshots"][@"sharedCacheID"];
3177				if (!found_sharedcache_badflags) {
3178					T_QUIET; T_EXPECT_NE(sharedregion_flags, 0ll, "one of the kTaskSharedRegion flags should be set on all tasks");
3179					bool multiple = (sharedregion_flags & (sharedregion_flags - 1)) != 0;
3180					T_QUIET; T_EXPECT_FALSE(multiple, "only one kTaskSharedRegion flag should be set on each task");
3181					found_sharedcache_badflags = (sharedregion_flags == 0 || multiple);
3182				}
3183				if (pid == 0) {
3184					T_ASSERT_EQ(sharedregion_flags, (uint64_t)kTaskSharedRegionNone, "Kernel proc (pid 0) should have no shared region");
3185				} else if (pid == sharedcache_child_pid) {
3186					found_sharedcache_child = true;
3187					sharedcache_child_flags = sharedregion_flags;
3188				} else if (pid == getpid()) {
3189					found_sharedcache_self = true;
3190					sharedcache_self_flags = sharedregion_flags;
3191				}
3192				if (sharedregion_flags == kTaskSharedRegionOther && !(task_flags & kTaskSharedRegionInfoUnavailable)) {
3193					T_QUIET; T_EXPECT_NOTNULL(sharedregion_info, "kTaskSharedRegionOther should have a shared_cache_dyld_load_info struct");
3194					T_QUIET; T_EXPECT_NOTNULL(sharedcache_id, "kTaskSharedRegionOther should have a sharedCacheID");
3195					if (sharedcache_id != nil) {
3196						T_QUIET; T_EXPECT_NOTNULL(sharedCaches[sharedcache_id], "sharedCacheID %d should exist", [sharedcache_id intValue]);
3197					}
3198				} else {
3199					T_QUIET; T_EXPECT_NULL(sharedregion_info, "non-kTaskSharedRegionOther should have no shared_cache_dyld_load_info struct");
3200					T_QUIET; T_EXPECT_NULL(sharedcache_id, "non-kTaskSharedRegionOther should have no sharedCacheID");
3201				}
3202			}
3203
3204			if (expect_zombie_child && (pid == zombie_child_pid)) {
3205				found_zombie_child = true;
3206
3207				expected_num_tasks += 1;
3208
3209				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3210				T_ASSERT_TRUE((task_flags & kTerminatedSnapshot) == kTerminatedSnapshot, "child zombie marked as terminated");
3211
3212				continue;
3213			}
3214
3215			if (expect_translated_child && (pid == translated_child_pid)) {
3216				found_translated_child = true;
3217
3218				uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3219				T_EXPECT_BITS_SET(task_flags, kTaskIsTranslated, "child marked as translated");
3220
3221				continue;
3222			}
3223			if (expect_exec_inprogress && (pid == exec_inprogress_pid || pid == -exec_inprogress_pid)) {
3224				exec_inprogress_found++;
3225				T_LOG("found exec task with pid %d, instance %d", pid, exec_inprogress_found);
3226				T_QUIET; T_ASSERT_LE(exec_inprogress_found, 2, "no more than two with the expected pid");
3227				if (exec_inprogress_found == 2) {
3228					T_LOG("found 2 tasks with pid %d", exec_inprogress_pid);
3229					exec_inprogress_cb(containerid, exec_inprogress_containerid);
3230				} else {
3231					exec_inprogress_containerid = containerid;
3232				}
3233			}
3234			if (expect_driverkit && driverkit_cb != NULL) {
3235				driverkit_cb(pid);
3236			}
3237			if (expect_cseg_waitinfo) {
3238				NSArray *winfos = container[@"task_snapshots"][@"thread_waitinfo"];
3239
3240				for (id i in winfos) {
3241					NSNumber *waitType = i[@"wait_type"];
3242					NSNumber *owner = i[@"owner"];
3243					if (waitType.intValue == kThreadWaitCompressor &&
3244							owner.unsignedLongValue == cseg_expected_threadid) {
3245						found_cseg_waitinfo = true;
3246						break;
3247					}
3248				}
3249			}
3250
3251			if (expect_srp_waitinfo) {
3252				NSArray *tinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3253				NSArray *winfos = container[@"task_snapshots"][@"thread_waitinfo"];
3254				for (id i in tinfos) {
3255					if (!found_srp_waitinfo) {
3256						bool found_thread = false;
3257						bool found_pid = false;
3258						if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_THREAD) &&
3259						    [i[@"turnstile_context"] unsignedLongLongValue] == srp_expected_threadid &&
3260						    srp_expected_threadid != 0) {
3261							found_thread = true;
3262						}
3263						if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_BLOCKED_ON_TASK) &&
3264						    [i[@"turnstile_context"] intValue] == srp_expected_pid &&
3265						    srp_expected_pid != -1) {
3266							found_pid = true;
3267						}
3268						if (found_pid || found_thread) {
3269							T_LOG("found SRP %s %lld waiter: %d", (found_thread ? "thread" : "pid"),
3270							    [i[@"turnstile_context"] unsignedLongLongValue], [i[@"waiter"] intValue]);
3271							/* we found something that is blocking the correct threadid */
3272							for (id j in winfos) {
3273								if ([j[@"waiter"] intValue] == [i[@"waiter"] intValue] &&
3274								    [j[@"wait_type"] intValue] == kThreadWaitPortReceive) {
3275									found_srp_waitinfo = true;
3276									T_EXPECT_EQ([j[@"wait_flags"] intValue], STACKSHOT_WAITINFO_FLAGS_SPECIALREPLY,
3277									    "SRP waitinfo should be marked as a special reply");
3278									break;
3279								}
3280							}
3281
3282							if (found_srp_waitinfo) {
3283								break;
3284							}
3285						}
3286					}
3287				}
3288			}
3289
3290			if (expect_sp_throttled) {
3291				NSArray *tinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3292				for (id i in tinfos) {
3293					if (([i[@"turnstile_flags"] intValue] & STACKSHOT_TURNSTILE_STATUS_PORTFLAGS)
3294						&& [i[@"turnstile_context"] intValue] == throttled_service_ctx) {
3295						int portlabel_id = [i[@"portlabel_id"] intValue];
3296						T_LOG("[pid:%d] Turnstile (flags = 0x%x, ctx = %d, portlabel_id = %d)", pid,
3297							[i[@"turnstile_flags"] intValue], [i[@"turnstile_context"] intValue], portlabel_id);
3298						for (id portid in container[@"task_snapshots"][@"portlabels"]) {
3299							if (portlabel_id != [portid intValue]) {
3300								continue;
3301							}
3302
3303							NSMutableDictionary *portlabel = container[@"task_snapshots"][@"portlabels"][portid];
3304							T_ASSERT_TRUE(portlabel != nil, "Found portlabel id: %d", [portid intValue]);
3305							NSString *portlabel_name = portlabel[@"portlabel_name"];
3306							T_EXPECT_TRUE(portlabel_name != nil, "Found portlabel %s", portlabel_name.UTF8String);
3307							T_EXPECT_EQ_STR(portlabel_name.UTF8String, THROTTLED_SERVICE_NAME, "throttled service port name matches");
3308							T_EXPECT_EQ(([portlabel[@"portlabel_flags"] intValue] & STACKSHOT_PORTLABEL_THROTTLED) != 0,
3309								is_throttled, "Port %s throttled", is_throttled ? "is" : "isn't");
3310							found_throttled_service = true;
3311							break;
3312						}
3313					}
3314
3315					if (found_throttled_service) {
3316						break;
3317					}
3318				}
3319			}
3320
3321			if (expect_suspendinfo) {
3322				// TODO: rdar://112563110
3323			}
3324
3325
3326			if (pid != getpid()) {
3327				break;
3328			}
3329
3330			T_EXPECT_EQ_STR(current_process_name(),
3331					[task_snapshot[@"ts_p_comm"] UTF8String],
3332					"current process name matches in stackshot");
3333
3334			uint64_t task_flags = [task_snapshot[@"ts_ss_flags"] unsignedLongLongValue];
3335			T_ASSERT_BITS_NOTSET(task_flags, kTerminatedSnapshot, "current process not marked as terminated");
3336			T_ASSERT_BITS_NOTSET(task_flags, kTaskIsTranslated, "current process not marked as translated");
3337
3338			T_QUIET;
3339			T_EXPECT_LE(pid, [task_snapshot[@"ts_unique_pid"] intValue],
3340					"unique pid is greater than pid");
3341
3342			NSDictionary* task_cpu_architecture = container[@"task_snapshots"][@"task_cpu_architecture"];
3343			T_QUIET; T_ASSERT_NOTNULL(task_cpu_architecture[@"cputype"], "have cputype");
3344			T_QUIET; T_ASSERT_NOTNULL(task_cpu_architecture[@"cpusubtype"], "have cputype");
3345			int cputype = [task_cpu_architecture[@"cputype"] intValue];
3346			int cpusubtype = [task_cpu_architecture[@"cpusubtype"] intValue];
3347
3348			struct proc_archinfo archinfo;
3349			int retval = proc_pidinfo(pid, PROC_PIDARCHINFO, 0, &archinfo, sizeof(archinfo));
3350			T_QUIET; T_WITH_ERRNO; T_ASSERT_GT(retval, 0, "proc_pidinfo(PROC_PIDARCHINFO) returned a value > 0");
3351			T_QUIET; T_ASSERT_EQ(retval, (int)sizeof(struct proc_archinfo), "proc_pidinfo call for PROC_PIDARCHINFO returned expected size");
3352			T_QUIET; T_EXPECT_EQ(cputype, archinfo.p_cputype, "cpu type is correct");
3353			T_QUIET; T_EXPECT_EQ(cpusubtype, archinfo.p_cpusubtype, "cpu subtype is correct");
3354
3355			NSDictionary * codesigning_info = container[@"task_snapshots"][@"stackshot_task_codesigning_info"];
3356			T_QUIET; T_ASSERT_NOTNULL(codesigning_info[@"csflags"], "have csflags");
3357			uint64_t flags = [codesigning_info[@"csflags"] unsignedLongLongValue];
3358			T_QUIET; T_EXPECT_GT(flags, 0, "nonzero csflags");
3359
3360			T_QUIET; T_ASSERT_NOTNULL(container[@"task_snapshots"][@"jetsam_coalition"], "have jetsam coalition");
3361			uint64_t jetsam_coalition = [container[@"task_snapshots"][@"jetsam_coalition"] unsignedLongLongValue];
3362			T_QUIET; T_EXPECT_GT(jetsam_coalition, 0, "nonzero jetsam coalition");
3363
3364			bool found_main_thread = false;
3365			uint64_t main_thread_id = -1ULL;
3366			bool found_null_kernel_frame = false;
3367			for (id thread_key in container[@"task_snapshots"][@"thread_snapshots"]) {
3368				NSMutableDictionary *thread = container[@"task_snapshots"][@"thread_snapshots"][thread_key];
3369				NSDictionary *thread_snap = thread[@"thread_snapshot"];
3370
3371				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_thread_id"] intValue], 0,
3372						"thread ID of thread in current task is valid");
3373				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_base_priority"] intValue], 0,
3374						"base priority of thread in current task is valid");
3375				T_QUIET; T_EXPECT_GT([thread_snap[@"ths_sched_priority"] intValue], 0,
3376						"scheduling priority of thread in current task is valid");
3377
3378				NSString *pth_name = thread[@"pth_name"];
3379				if (pth_name != nil && [pth_name isEqualToString:@TEST_THREAD_NAME]) {
3380					found_main_thread = true;
3381					main_thread_id = [thread_snap[@"ths_thread_id"] unsignedLongLongValue];
3382
3383					T_QUIET; T_EXPECT_GT([thread_snap[@"ths_total_syscalls"] intValue], 0,
3384							"total syscalls of current thread is valid");
3385
3386					NSDictionary *cpu_times = thread[@"cpu_times"];
3387					T_EXPECT_GE([cpu_times[@"runnable_time"] intValue],
3388							[cpu_times[@"system_time"] intValue] +
3389							[cpu_times[@"user_time"] intValue],
3390							"runnable time of current thread is valid");
3391				}
3392				if (!found_null_kernel_frame) {
3393					for (NSNumber *frame in thread[@"kernel_frames"]) {
3394						if (frame.unsignedLongValue == 0) {
3395							found_null_kernel_frame = true;
3396							break;
3397						}
3398					}
3399				}
3400				if (expect_asyncstack && !found_asyncstack &&
3401				    asyncstack_threadid == [thread_snap[@"ths_thread_id"] unsignedLongLongValue]) {
3402					found_asyncstack = true;
3403					NSArray* async_stack = thread[@"user_async_stack_frames"];
3404					NSNumber* start_idx = thread[@"user_async_start_index"];
3405					NSArray* user_stack = thread[@"user_stack_frames"];
3406					T_QUIET; T_ASSERT_NOTNULL(async_stack, "async thread %#llx has user_async_stack_frames", asyncstack_threadid);
3407					T_QUIET; T_ASSERT_NOTNULL(start_idx, "async thread %#llx has user_async_start_index", asyncstack_threadid);
3408					T_QUIET; T_ASSERT_NOTNULL(user_stack, "async thread %#llx has user_stack_frames", asyncstack_threadid);
3409					T_QUIET; T_ASSERT_EQ(async_stack.count, asyncstack_stack.count,
3410						"actual async_stack count == expected async_stack count");
3411					for (size_t i = 0; i < async_stack.count; i++) {
3412						T_EXPECT_EQ([async_stack[i][@"lr"] unsignedLongLongValue],
3413							[asyncstack_stack[i] unsignedLongLongValue], "frame %zu matches", i);
3414					}
3415				}
3416			}
3417			T_EXPECT_TRUE(found_main_thread, "found main thread for current task in stackshot");
3418			T_EXPECT_FALSE(found_null_kernel_frame, "should not see any NULL kernel frames");
3419
3420			if (expect_turnstile_lock && !found_turnstile_lock) {
3421				NSArray *tsinfos = container[@"task_snapshots"][@"thread_turnstileinfo"];
3422
3423				for (id i in tsinfos) {
3424					if ([i[@"turnstile_context"] unsignedLongLongValue] == main_thread_id) {
3425						found_turnstile_lock = true;
3426						break;
3427					}
3428				}
3429			}
3430			break;
3431		}
3432		case STACKSHOT_KCTYPE_SHAREDCACHE_LOADINFO: {
3433			// Legacy shared cache info
3434			struct dyld_shared_cache_loadinfo *payload = kcdata_iter_payload(iter);
3435			T_ASSERT_EQ((size_t)kcdata_iter_size(iter), sizeof(*payload), "valid dyld_shared_cache_loadinfo struct");
3436
3437			check_shared_cache_uuid(payload->sharedCacheUUID);
3438
3439			T_EXPECT_LE(payload->sharedCacheUnreliableSlidBaseAddress,
3440				payload->sharedCacheSlidFirstMapping,
3441				"SlidBaseAddress <= SlidFirstMapping");
3442			T_EXPECT_GE(payload->sharedCacheUnreliableSlidBaseAddress + (7ull << 32) + (1ull << 29),
3443				payload->sharedCacheSlidFirstMapping,
3444				"SlidFirstMapping should be within 28.5gigs of SlidBaseAddress");
3445
3446			size_t shared_cache_len;
3447			const void *addr = _dyld_get_shared_cache_range(&shared_cache_len);
3448			T_EXPECT_EQ((uint64_t)addr, payload->sharedCacheSlidFirstMapping,
3449			    "SlidFirstMapping should match shared_cache_range");
3450
3451			/*
3452			 * check_shared_cache_uuid() asserts on failure, so we must have
3453			 * found the shared cache UUID to be correct.
3454			 */
3455			found_shared_cache_uuid = true;
3456			break;
3457		}
3458		case KCDATA_TYPE_UINT64_DESC: {
3459			char     *desc;
3460			uint64_t *data;
3461			uint32_t  size;
3462			kcdata_iter_get_data_with_desc(iter, &desc, &data, &size);
3463
3464			if (strcmp(desc, "stackshot_tasks_count") == 0) {
3465				expected_num_tasks = *data;
3466			} else if (strcmp(desc, "stackshot_threads_count") == 0) {
3467				expected_num_threads = *data;
3468			}
3469
3470			break;
3471		}
3472		case STACKSHOT_KCTYPE_LATENCY_INFO_CPU: {
3473			struct stackshot_latency_cpu *cpu_latency = kcdata_iter_payload(iter);
3474			found_percpu_tasks += cpu_latency->tasks_processed;
3475			found_percpu_threads += cpu_latency->threads_processed;
3476			break;
3477		}
3478		}
3479	}
3480
3481	if (expect_sharedcache_child) {
3482		T_QUIET; T_ASSERT_TRUE(found_sharedcache_child, "found sharedcache child in kcdata");
3483		T_QUIET; T_ASSERT_TRUE(found_sharedcache_self, "found self in kcdata");
3484		if (found_sharedcache_child && found_sharedcache_self) {
3485			T_QUIET; T_ASSERT_NE(sharedcache_child_flags, (uint64_t)kTaskSharedRegionNone, "sharedcache child should have shared region");
3486			T_QUIET; T_ASSERT_NE(sharedcache_self_flags, (uint64_t)kTaskSharedRegionNone, "sharedcache: self should have shared region");
3487			if (sharedcache_self_flags == kTaskSharedRegionSystem && !sharedcache_child_sameaddr) {
3488				/* If we're in the system shared region, and the child has a different address, child must have an Other shared region */
3489				T_ASSERT_EQ(sharedcache_child_flags, (uint64_t)kTaskSharedRegionOther,
3490				    "sharedcache child should have Other shared region");
3491			}
3492		}
3493	}
3494
3495	if (expect_transitioning_task) {
3496		T_QUIET; T_ASSERT_TRUE(found_transitioning_task, "found transitioning_task child in kcdata");
3497	}
3498
3499	if (expect_exec_inprogress) {
3500		T_QUIET; T_ASSERT_GT(exec_inprogress_found, 0, "found at least 1 task for execing process");
3501	}
3502
3503	if (expect_zombie_child) {
3504		T_QUIET; T_ASSERT_TRUE(found_zombie_child, "found zombie child in kcdata");
3505	}
3506
3507	if (expect_postexec_child) {
3508		T_QUIET; T_ASSERT_TRUE(found_postexec_child, "found post-exec child in kcdata");
3509	}
3510
3511	if (expect_translated_child) {
3512		T_QUIET; T_ASSERT_TRUE(found_translated_child, "found translated child in kcdata");
3513	}
3514
3515	if (expect_shared_cache_layout) {
3516		T_QUIET; T_ASSERT_TRUE(found_shared_cache_layout, "shared cache layout found in kcdata");
3517	}
3518
3519	if (expect_shared_cache_uuid) {
3520		T_QUIET; T_ASSERT_TRUE(found_shared_cache_uuid, "shared cache UUID found in kcdata");
3521	}
3522
3523	if (expect_dispatch_queue_label) {
3524		T_QUIET; T_ASSERT_TRUE(found_dispatch_queue_label, "dispatch queue label found in kcdata");
3525	}
3526
3527	if (expect_turnstile_lock) {
3528		T_QUIET; T_ASSERT_TRUE(found_turnstile_lock, "found expected deadlock");
3529	}
3530
3531	if (expect_cseg_waitinfo) {
3532		T_QUIET; T_ASSERT_TRUE(found_cseg_waitinfo, "found c_seg waitinfo");
3533	}
3534
3535	if (expect_srp_waitinfo) {
3536		T_QUIET; T_ASSERT_TRUE(found_srp_waitinfo, "found special reply port waitinfo");
3537	}
3538
3539	if (expect_sp_throttled) {
3540		T_QUIET; T_ASSERT_TRUE(found_throttled_service, "found the throttled service");
3541	}
3542
3543	if (expect_asyncstack) {
3544		T_QUIET; T_ASSERT_TRUE(found_asyncstack, "found async stack threadid");
3545	}
3546
3547	if ([extra objectForKey:no_exclaves_key] != nil) {
3548		T_QUIET; T_ASSERT_FALSE(found_exclaves, "did not find any Exclaves data");
3549	}
3550
3551
3552	bool check_counts = !delta && !found_transitioning_task && !expect_single_task && !expect_driverkit;
3553
3554	if (check_counts && (expected_num_threads != 0) && (found_percpu_threads != 0)) {
3555		/* If the task counts below check out, we can be sure that the per-cpu reported thread counts are accurate. */
3556		T_QUIET; T_ASSERT_EQ_ULLONG(found_percpu_threads, expected_num_threads, "number of threads reported by CPUs matches expected count");
3557	}
3558
3559	if (check_counts && (expected_num_tasks != 0)) {
3560		T_QUIET; T_ASSERT_EQ_ULLONG(found_tasks, expected_num_tasks, "number of tasks in kcdata matches expected count");
3561		if (found_percpu_tasks != 0) {
3562			T_QUIET; T_ASSERT_EQ_ULLONG(found_percpu_tasks, expected_num_tasks, "number of tasks reported by CPUs matches expected count");
3563		}
3564	}
3565
3566	T_ASSERT_FALSE(KCDATA_ITER_FOREACH_FAILED(iter), "successfully iterated kcdata");
3567
3568	free(inflatedBufferBase);
3569}
3570
3571static const char *
3572current_process_name(void)
3573{
3574	static char name[64];
3575
3576	if (!name[0]) {
3577		int ret = proc_name(getpid(), name, sizeof(name));
3578		T_QUIET;
3579		T_ASSERT_POSIX_SUCCESS(ret, "proc_name failed for current process");
3580	}
3581
3582	return name;
3583}
3584
3585static void
3586initialize_thread(void)
3587{
3588	int ret = pthread_setname_np(TEST_THREAD_NAME);
3589	T_QUIET;
3590	T_ASSERT_POSIX_ZERO(ret, "set thread name to %s", TEST_THREAD_NAME);
3591}
3592
3593T_DECL(dirty_buffer, "test that stackshot works with a dirty input buffer from kernel", T_META_TAG_VM_PREFERRED)
3594{
3595	const char *test_sysctl = "stackshot_dirty_buffer";
3596	int64_t result;
3597
3598	T_LOG("running sysctl to trigger kernel-driven stackshot");
3599	result = run_sysctl_test(test_sysctl, 0);
3600	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3601}
3602
3603T_DECL(kernel_initiated, "smoke test that stackshot works with kernel-initiated stackshots", T_META_TAG_VM_PREFERRED)
3604{
3605	const char *test_sysctl = "stackshot_kernel_initiator";
3606	int64_t result;
3607	__block bool did_get_stackshot = false;
3608
3609	initialize_thread(); // must run before the stackshots to keep parse_stackshot happy
3610
3611	T_LOG("running sysctl to trigger kernel-driven stackshot type 1");
3612	result = run_sysctl_test(test_sysctl, 1);
3613	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3614
3615	T_LOG("running sysctl to trigger kernel-driven stackshot type 2");
3616	result = run_sysctl_test(test_sysctl, 2);
3617	T_ASSERT_EQ_LLONG(result, 1, "sysctl result indicated success");
3618
3619	struct scenario scenario = {
3620		.name = "from_kernel_initiated",
3621		.flags = STACKSHOT_RETRIEVE_EXISTING_BUFFER,
3622	};
3623
3624	T_LOG("attempting to fetch stored in-kernel stackshot");
3625	take_stackshot(&scenario, false, ^(void *ssbuf, size_t sslen) {
3626		T_ASSERT_NOTNULL(ssbuf, "non-null kernel stackshot");
3627		T_ASSERT_GT(sslen, 0, "non-zero stackshot size");
3628		parse_stackshot(0, ssbuf, sslen, nil);
3629		did_get_stackshot = true;
3630	});
3631
3632	T_ASSERT_TRUE(did_get_stackshot, "got stackshot from kernel type 2");
3633}
3634