xref: /xnu-11215/tests/perf_exit_proc.c (revision aca3beaa)
1 #include <pthread.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <unistd.h>
5 
6 #include <mach/mach.h>
7 #include <mach/mach_vm.h>
8 
9 static void*
loop(void * arg)10 loop(__attribute__ ((unused)) void *arg)
11 {
12 	while (1) {
13 	}
14 }
15 
16 
17 static int
run_additional_threads(int nthreads)18 run_additional_threads(int nthreads)
19 {
20 	for (int i = 0; i < nthreads; i++) {
21 		pthread_t pthread;
22 		int err;
23 
24 		err = pthread_create(&pthread, NULL, loop, NULL);
25 		if (err) {
26 			return err;
27 		}
28 	}
29 
30 	return 0;
31 }
32 
33 static int
allocate_and_wire_memory(mach_vm_size_t size)34 allocate_and_wire_memory(mach_vm_size_t size)
35 {
36 	int err;
37 	task_t task = mach_task_self();
38 	mach_vm_address_t addr;
39 
40 	if (size <= 0) {
41 		return 0;
42 	}
43 
44 	err = mach_vm_allocate(task, &addr, size, VM_FLAGS_ANYWHERE);
45 	if (err != KERN_SUCCESS) {
46 		printf("mach_vm_allocate returned non-zero: %s\n", mach_error_string(err));
47 		return err;
48 	}
49 	err = mach_vm_protect(task, addr, size, 0, VM_PROT_READ | VM_PROT_WRITE);
50 	if (err != KERN_SUCCESS) {
51 		printf("mach_vm_protect returned non-zero: %s\n", mach_error_string(err));
52 		return err;
53 	}
54 	host_t host_priv_port;
55 	err = host_get_host_priv_port(mach_host_self(), &host_priv_port);
56 	if (err != KERN_SUCCESS) {
57 		printf("host_get_host_priv_port returned non-zero: %s\n", mach_error_string(err));
58 		return err;
59 	}
60 	err = mach_vm_wire(host_priv_port, task, addr, size, VM_PROT_READ | VM_PROT_WRITE);
61 	if (err != KERN_SUCCESS) {
62 		printf("mach_vm_wire returned non-zero: %s\n", mach_error_string(err));
63 		return err;
64 	}
65 
66 	return 0;
67 }
68 
69 int
main(int argc,char * argv[])70 main(int argc, char *argv[])
71 {
72 	int nthreads = 0;
73 	int err;
74 	mach_vm_size_t wired_mem = 0;
75 
76 	if (argc > 1) {
77 		nthreads = (int)strtoul(argv[1], NULL, 10);
78 	}
79 	if (argc > 2) {
80 		wired_mem = (mach_vm_size_t)strtoul(argv[2], NULL, 10);
81 	}
82 
83 	err = allocate_and_wire_memory(wired_mem);
84 	if (err) {
85 		return err;
86 	}
87 
88 	err = run_additional_threads(nthreads);
89 	if (err) {
90 		return err;
91 	}
92 
93 	return 0;
94 }
95