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