1 #include <dispatch/dispatch.h>
2 #include <mach-o/dyld.h>
3 #include <signal.h>
4 #include <sys/kern_sysctl.h>
5 #include <sys/sysctl.h>
6 #include <sys/kern_memorystatus.h>
7
8 #include <darwintest.h>
9 #include <darwintest_utils.h>
10
11 #include "test_utils.h"
12
13 bool
is_development_kernel(void)14 is_development_kernel(void)
15 {
16 static dispatch_once_t is_development_once;
17 static bool is_development;
18
19 dispatch_once(&is_development_once, ^{
20 int dev;
21 size_t dev_size = sizeof(dev);
22
23 T_QUIET;
24 T_ASSERT_POSIX_SUCCESS(sysctlbyname("kern.development", &dev,
25 &dev_size, NULL, 0), NULL);
26 is_development = (dev != 0);
27 });
28
29 return is_development;
30 }
31
32
33 bool
process_is_translated()34 process_is_translated()
35 {
36 static dispatch_once_t is_translated_once;
37 static bool is_translated;
38
39 dispatch_once(&is_translated_once, ^{
40 int out_value = 0;
41 size_t inout_size = sizeof(out_value);
42 if (sysctlbyname("sysctl.proc_translated", &out_value, &inout_size, NULL, 0) != 0) {
43 /*
44 * ENOENT means the sysctl is not present and therefore
45 * this process is not translated. Any other error is bad.
46 */
47 T_QUIET; T_ASSERT_POSIX_ERROR(errno, ENOENT, "sysctlbyname(sysctl.proc_translated)");
48 is_translated = false;
49 } else {
50 T_QUIET; T_ASSERT_GE(inout_size, sizeof(out_value), "sysctlbyname(sysctl.proc_translated)");
51 is_translated = (bool)out_value;
52 }
53 });
54 return is_translated;
55 }
56
57
58 pid_t
launch_background_helper(const char * variant,bool start_suspended,bool memorystatus_managed)59 launch_background_helper(
60 const char* variant,
61 bool start_suspended,
62 bool memorystatus_managed)
63 {
64 pid_t pid;
65 char **launch_tool_args;
66 char testpath[PATH_MAX];
67 char *variant_cpy = strdup(variant);
68 uint32_t testpath_buf_size;
69 int ret;
70
71 testpath_buf_size = sizeof(testpath);
72 ret = _NSGetExecutablePath(testpath, &testpath_buf_size);
73 launch_tool_args = (char *[]){
74 testpath,
75 "-n",
76 variant_cpy,
77 NULL
78 };
79 ret = dt_launch_tool(&pid, launch_tool_args, start_suspended, NULL, NULL);
80 if (ret != 0) {
81 T_LOG("dt_launch tool returned %d with error code %d", ret, errno);
82 }
83 T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "dt_launch_tool");
84 if (memorystatus_managed) {
85 set_process_memorystatus_managed(pid);
86 }
87 free(variant_cpy);
88 return pid;
89 }
90
91 void
set_process_memorystatus_managed(pid_t pid)92 set_process_memorystatus_managed(pid_t pid)
93 {
94 kern_return_t ret = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_MANAGED, pid, 1, NULL, 0);
95 T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "memorystatus_control");
96 }
97