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