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