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