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