xref: /llvm-project/lldb/test/API/linux/thread/create_during_instruction_step/main.cpp (revision 99451b4453688a94c6014cac233d371ab4cc342d)
1 //===-- main.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // This file deliberately uses low level linux-specific API for thread creation because:
10 // - instruction-stepping over thread creation using higher-level functions was very slow
11 // - it was also unreliable due to single-stepping bugs unrelated to this test
12 // - some threading libraries do not create or destroy threads when we would expect them to
13 
14 #include <sched.h>
15 
16 #include <atomic>
17 #include <cstdio>
18 
19 enum { STACK_SIZE = 0x2000 };
20 
21 static uint8_t child_stack[STACK_SIZE];
22 
23 pid_t child_tid;
24 
25 std::atomic<bool> flag(false);
26 
27 int thread_main(void *)
28 {
29     while (! flag) // Make sure the thread does not exit prematurely
30         ;
31 
32     return 0;
33 }
34 
35 int main ()
36 {
37     int ret = clone(thread_main,
38             child_stack + STACK_SIZE/2, // Don't care whether the stack grows up or down,
39                                         // just point to the middle
40             CLONE_CHILD_CLEARTID | CLONE_FILES | CLONE_FS | CLONE_PARENT_SETTID |
41             CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_THREAD | CLONE_VM,
42             nullptr, // thread_main argument
43             &child_tid);
44 
45     if (ret == -1)
46     {
47         perror("clone");
48         return 1;
49     }
50 
51     flag = true;
52 
53     return 0;
54 }
55