1 #include <atomic>
2 #include <chrono>
3 #include <cstdlib>
4 #include <cstring>
5 #include <errno.h>
6 #include <inttypes.h>
7 #include <memory>
8 #include <mutex>
9 #if !defined(_WIN32)
10 #include <pthread.h>
11 #include <signal.h>
12 #include <unistd.h>
13 #endif
14 #include "thread.h"
15 #include <setjmp.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <string>
20 #include <thread>
21 #include <time.h>
22 #include <vector>
23 #if defined(__APPLE__)
24 #include <TargetConditionals.h>
25 #endif
26
27 static const char *const PRINT_PID_COMMAND = "print-pid";
28
29 static bool g_print_thread_ids = false;
30 static std::mutex g_print_mutex;
31 static bool g_threads_do_segfault = false;
32
33 static std::mutex g_jump_buffer_mutex;
34 static jmp_buf g_jump_buffer;
35 static bool g_is_segfaulting = false;
36
37 static char g_message[256];
38
39 static volatile char g_c1 = '0';
40 static volatile char g_c2 = '1';
41
print_pid()42 static void print_pid() {
43 #if defined(_WIN32)
44 fprintf(stderr, "PID: %d\n", ::GetCurrentProcessId());
45 #else
46 fprintf(stderr, "PID: %d\n", getpid());
47 #endif
48 }
49
signal_handler(int signo)50 static void signal_handler(int signo) {
51 #if defined(_WIN32)
52 // No signal support on Windows.
53 #else
54 const char *signal_name = nullptr;
55 switch (signo) {
56 case SIGUSR1:
57 signal_name = "SIGUSR1";
58 break;
59 case SIGSEGV:
60 signal_name = "SIGSEGV";
61 break;
62 default:
63 signal_name = nullptr;
64 }
65
66 // Print notice that we received the signal on a given thread.
67 char buf[100];
68 if (signal_name)
69 snprintf(buf, sizeof(buf), "received %s on thread id: %" PRIx64 "\n", signal_name, get_thread_id());
70 else
71 snprintf(buf, sizeof(buf), "received signo %d (%s) on thread id: %" PRIx64 "\n", signo, strsignal(signo), get_thread_id());
72 write(STDOUT_FILENO, buf, strlen(buf));
73
74 // Reset the signal handler if we're one of the expected signal handlers.
75 switch (signo) {
76 case SIGSEGV:
77 if (g_is_segfaulting) {
78 // Fix up the pointer we're writing to. This needs to happen if nothing
79 // intercepts the SIGSEGV (i.e. if somebody runs this from the command
80 // line).
81 longjmp(g_jump_buffer, 1);
82 }
83 break;
84 case SIGUSR1:
85 if (g_is_segfaulting) {
86 // Fix up the pointer we're writing to. This is used to test gdb remote
87 // signal delivery. A SIGSEGV will be raised when the thread is created,
88 // switched out for a SIGUSR1, and then this code still needs to fix the
89 // seg fault. (i.e. if somebody runs this from the command line).
90 longjmp(g_jump_buffer, 1);
91 }
92 break;
93 }
94
95 // Reset the signal handler.
96 sig_t sig_result = signal(signo, signal_handler);
97 if (sig_result == SIG_ERR) {
98 fprintf(stderr, "failed to set signal handler: errno=%d\n", errno);
99 exit(1);
100 }
101 #endif
102 }
103
swap_chars()104 static void swap_chars() {
105 #if defined(__x86_64__) || defined(__i386__)
106 asm volatile("movb %1, (%2)\n\t"
107 "movb %0, (%3)\n\t"
108 "movb %0, (%2)\n\t"
109 "movb %1, (%3)\n\t"
110 :
111 : "i"('0'), "i"('1'), "r"(&g_c1), "r"(&g_c2)
112 : "memory");
113 #elif defined(__aarch64__)
114 asm volatile("strb %w1, [%2]\n\t"
115 "strb %w0, [%3]\n\t"
116 "strb %w0, [%2]\n\t"
117 "strb %w1, [%3]\n\t"
118 :
119 : "r"('0'), "r"('1'), "r"(&g_c1), "r"(&g_c2)
120 : "memory");
121 #elif defined(__arm__)
122 asm volatile("strb %1, [%2]\n\t"
123 "strb %0, [%3]\n\t"
124 "strb %0, [%2]\n\t"
125 "strb %1, [%3]\n\t"
126 :
127 : "r"('0'), "r"('1'), "r"(&g_c1), "r"(&g_c2)
128 : "memory");
129 #else
130 #warning This may generate unpredictible assembly and cause the single-stepping test to fail.
131 #warning Please add appropriate assembly for your target.
132 g_c1 = '1';
133 g_c2 = '0';
134
135 g_c1 = '0';
136 g_c2 = '1';
137 #endif
138 }
139
hello()140 static void hello() {
141 std::lock_guard<std::mutex> lock(g_print_mutex);
142 printf("hello, world\n");
143 }
144
thread_func(void * arg)145 static void *thread_func(void *arg) {
146 static std::atomic<int> s_thread_index(1);
147 const int this_thread_index = s_thread_index++;
148 if (g_print_thread_ids) {
149 std::lock_guard<std::mutex> lock(g_print_mutex);
150 printf("thread %d id: %" PRIx64 "\n", this_thread_index, get_thread_id());
151 }
152
153 if (g_threads_do_segfault) {
154 // Sleep for a number of seconds based on the thread index.
155 // TODO add ability to send commands to test exe so we can
156 // handle timing more precisely. This is clunky. All we're
157 // trying to do is add predictability as to the timing of
158 // signal generation by created threads.
159 int sleep_seconds = 2 * (this_thread_index - 1);
160 std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds));
161
162 // Test creating a SEGV.
163 {
164 std::lock_guard<std::mutex> lock(g_jump_buffer_mutex);
165 g_is_segfaulting = true;
166 int *bad_p = nullptr;
167 if (setjmp(g_jump_buffer) == 0) {
168 // Force a seg fault signal on this thread.
169 *bad_p = 0;
170 } else {
171 // Tell the system we're no longer seg faulting.
172 // Used by the SIGUSR1 signal handler that we inject
173 // in place of the SIGSEGV so it only tries to
174 // recover from the SIGSEGV if this seg fault code
175 // was in play.
176 g_is_segfaulting = false;
177 }
178 }
179
180 {
181 std::lock_guard<std::mutex> lock(g_print_mutex);
182 printf("thread %" PRIx64 ": past SIGSEGV\n", get_thread_id());
183 }
184 }
185
186 int sleep_seconds_remaining = 60;
187 std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds_remaining));
188
189 return nullptr;
190 }
191
consume_front(std::string & str,const std::string & front)192 static bool consume_front(std::string &str, const std::string &front) {
193 if (str.find(front) != 0)
194 return false;
195
196 str = str.substr(front.size());
197 return true;
198 }
199
main(int argc,char ** argv)200 int main(int argc, char **argv) {
201 lldb_enable_attach();
202
203 std::vector<std::thread> threads;
204 std::unique_ptr<uint8_t[]> heap_array_up;
205 int return_value = 0;
206
207 #if !defined(_WIN32)
208 // Set the signal handler.
209 sig_t sig_result = signal(SIGALRM, signal_handler);
210 if (sig_result == SIG_ERR) {
211 fprintf(stderr, "failed to set SIGALRM signal handler: errno=%d\n", errno);
212 exit(1);
213 }
214
215 sig_result = signal(SIGUSR1, signal_handler);
216 if (sig_result == SIG_ERR) {
217 fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno);
218 exit(1);
219 }
220
221 sig_result = signal(SIGSEGV, signal_handler);
222 if (sig_result == SIG_ERR) {
223 fprintf(stderr, "failed to set SIGSEGV handler: errno=%d\n", errno);
224 exit(1);
225 }
226
227 sig_result = signal(SIGCHLD, SIG_IGN);
228 if (sig_result == SIG_ERR) {
229 fprintf(stderr, "failed to set SIGCHLD handler: errno=%d\n", errno);
230 exit(1);
231 }
232 #endif
233
234 // Process command line args.
235 for (int i = 1; i < argc; ++i) {
236 std::string arg = argv[i];
237 if (consume_front(arg, "stderr:")) {
238 // Treat remainder as text to go to stderr.
239 fprintf(stderr, "%s\n", arg.c_str());
240 } else if (consume_front(arg, "retval:")) {
241 // Treat as the return value for the program.
242 return_value = std::atoi(arg.c_str());
243 } else if (consume_front(arg, "sleep:")) {
244 // Treat as the amount of time to have this process sleep (in seconds).
245 int sleep_seconds_remaining = std::atoi(arg.c_str());
246
247 // Loop around, sleeping until all sleep time is used up. Note that
248 // signals will cause sleep to end early with the number of seconds
249 // remaining.
250 std::this_thread::sleep_for(
251 std::chrono::seconds(sleep_seconds_remaining));
252
253 } else if (consume_front(arg, "set-message:")) {
254 // Copy the contents after "set-message:" to the g_message buffer.
255 // Used for reading inferior memory and verifying contents match
256 // expectations.
257 strncpy(g_message, arg.c_str(), sizeof(g_message));
258
259 // Ensure we're null terminated.
260 g_message[sizeof(g_message) - 1] = '\0';
261
262 } else if (consume_front(arg, "print-message:")) {
263 std::lock_guard<std::mutex> lock(g_print_mutex);
264 printf("message: %s\n", g_message);
265 } else if (consume_front(arg, "get-data-address-hex:")) {
266 volatile void *data_p = nullptr;
267
268 if (arg == "g_message")
269 data_p = &g_message[0];
270 else if (arg == "g_c1")
271 data_p = &g_c1;
272 else if (arg == "g_c2")
273 data_p = &g_c2;
274
275 std::lock_guard<std::mutex> lock(g_print_mutex);
276 printf("data address: %p\n", data_p);
277 } else if (consume_front(arg, "get-heap-address-hex:")) {
278 // Create a byte array if not already present.
279 if (!heap_array_up)
280 heap_array_up.reset(new uint8_t[32]);
281
282 std::lock_guard<std::mutex> lock(g_print_mutex);
283 printf("heap address: %p\n", heap_array_up.get());
284
285 } else if (consume_front(arg, "get-stack-address-hex:")) {
286 std::lock_guard<std::mutex> lock(g_print_mutex);
287 printf("stack address: %p\n", &return_value);
288 } else if (consume_front(arg, "get-code-address-hex:")) {
289 void (*func_p)() = nullptr;
290
291 if (arg == "hello")
292 func_p = hello;
293 else if (arg == "swap_chars")
294 func_p = swap_chars;
295
296 std::lock_guard<std::mutex> lock(g_print_mutex);
297 printf("code address: %p\n", func_p);
298 } else if (consume_front(arg, "call-function:")) {
299 void (*func_p)() = nullptr;
300
301 if (arg == "hello")
302 func_p = hello;
303 else if (arg == "swap_chars")
304 func_p = swap_chars;
305 func_p();
306 #if !defined(_WIN32) && !defined(TARGET_OS_WATCH) && !defined(TARGET_OS_TV)
307 } else if (arg == "fork") {
308 if (fork() == 0)
309 _exit(0);
310 } else if (arg == "vfork") {
311 if (vfork() == 0)
312 _exit(0);
313 #endif
314 } else if (consume_front(arg, "thread:new")) {
315 threads.push_back(std::thread(thread_func, nullptr));
316 } else if (consume_front(arg, "thread:print-ids")) {
317 // Turn on thread id announcing.
318 g_print_thread_ids = true;
319
320 // And announce us.
321 {
322 std::lock_guard<std::mutex> lock(g_print_mutex);
323 printf("thread 0 id: %" PRIx64 "\n", get_thread_id());
324 }
325 } else if (consume_front(arg, "thread:segfault")) {
326 g_threads_do_segfault = true;
327 } else if (consume_front(arg, "print-pid")) {
328 print_pid();
329 } else {
330 // Treat the argument as text for stdout.
331 printf("%s\n", argv[i]);
332 }
333 }
334
335 // If we launched any threads, join them
336 for (std::vector<std::thread>::iterator it = threads.begin();
337 it != threads.end(); ++it)
338 it->join();
339
340 return return_value;
341 }
342