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