Il 29/12/23 15:14, Samuel Thibault ha scritto:
Luca Dariz, le jeu. 28 déc. 2023 20:42:55 +0100, a ecrit:
diff --git a/tests/testlib.c b/tests/testlib.c
index 6abe8c4d..e6be46ee 100644
--- a/tests/testlib.c
+++ b/tests/testlib.c
@@ -95,3 +95,56 @@ void _start()
printf("%s: test %s exit code %x\n", TEST_SUCCESS_MARKER, argv[0], ret);
halt();
}
+
+// started from
https://github.com/dwarfmaster/mach-ipc/blob/master/minimal_threads/main.c
So this *has* to reproduce the MIT license header of that repository.
Better put it in a separate file.
ok
+static uint32_t stack_top[PAGE_SIZE] __attribute__ ((aligned (PAGE_SIZE)));
+thread_t test_thread_start(task_t task, void(*routine)(void*), void* arg) {
+ const vm_size_t stack_size = PAGE_SIZE * 16;
+ kern_return_t ret;
+ vm_address_t stack;
+
+ ret = vm_allocate(task, &stack, stack_size, TRUE);
+ ASSERT_RET(ret, "can't allocate the stack for a new thread");
+
+ ret = vm_protect(task, stack, PAGE_SIZE, FALSE, VM_PROT_NONE);
+ ASSERT_RET(ret, "can't protect the stack from overflows");
+
+ long *top = (long*)((vm_offset_t)stack_top + PAGE_SIZE) - 2;
+ *top = 0; /* The return address */
+#ifndef __x86_64__
+ *(top + 1) = (long)arg; /* The argument is passed on the stack on x86_32 */
+#endif
+ ret = vm_write(task, stack + stack_size - PAGE_SIZE, (vm_offset_t)stack_top,
PAGE_SIZE);
+ ASSERT_RET(ret, "can't initialize the stack for the new thread");
+
+ thread_t thread;
+ ret = thread_create(task, &thread);
+ ASSERT_RET(ret, "thread_create()");
+
+ struct i386_thread_state state;
+ unsigned int count;
+ count = i386_THREAD_STATE_COUNT;
+ ret = thread_get_state(thread, i386_REGS_SEGS_STATE,
+ (thread_state_t) &state, &count);
+ ASSERT_RET(ret, "thread_get_state()");
+
+#ifdef __x86_64__
+ state.rip = (long) routine;
+ state.ursp = (long) (stack + stack_size - 16);
Rather use sizeof(long)*2.
+ state.rbp = 0;
+ state.rdi = (long)arg;
+#else
+ state.eip = (long) routine;
+ state.uesp = (long) (stack + stack_size - 8);
And here as well.
ok
+ state.ebp = 0;
+#endif
+ ret = thread_set_state(thread, i386_REGS_SEGS_STATE,
+ (thread_state_t) &state, i386_THREAD_STATE_COUNT);
+ ASSERT_RET(ret, "thread_set_state");
+
+ ret = thread_resume(thread);
+ ASSERT_RET(ret, "thread_resume");
+
+ return thread;
+}
--
2.39.2