Merge branch 'master' of /home/git/random-fuzzer into thread-switch
[c11tester.git] / threads.cc
1 /** @file threads.cc
2  *  @brief Thread functions.
3  */
4
5 #include <string.h>
6
7 #include <threads.h>
8 #include "mutex.h"
9 #include "common.h"
10 #include "threads-model.h"
11 #include "action.h"
12
13 /* global "model" object */
14 #include "model.h"
15 #include "execution.h"
16 #include "schedule.h"
17 #include "clockvector.h"
18
19 #ifdef TLS
20 #include <dlfcn.h>
21 uintptr_t get_tls_addr() {
22         uintptr_t addr;
23         asm ("mov %%fs:0, %0" : "=r" (addr));
24         return addr;
25 }
26
27 #include <asm/prctl.h>
28 #include <sys/prctl.h>
29 extern "C" {
30 int arch_prctl(int code, unsigned long addr);
31 }
32 static void set_tls_addr(uintptr_t addr) {
33         arch_prctl(ARCH_SET_FS, addr);
34         asm ("mov %0, %%fs:0" : : "r" (addr) : "memory");
35 }
36 #endif
37
38 /** Allocate a stack for a new thread. */
39 static void * stack_allocate(size_t size)
40 {
41         return Thread_malloc(size);
42 }
43
44 /** Free a stack for a terminated thread. */
45 static void stack_free(void *stack)
46 {
47         Thread_free(stack);
48 }
49
50 /**
51  * @brief Get the current Thread
52  *
53  * Must be called from a user context
54  *
55  * @return The currently executing thread
56  */
57 Thread * thread_current(void)
58 {
59         ASSERT(model);
60         return model->get_current_thread();
61 }
62
63 void modelexit() {
64         model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
65 }
66
67 void initMainThread() {
68         atexit(modelexit);
69         Thread * curr_thread = thread_current();
70         model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
71 }
72
73 /**
74  * Provides a startup wrapper for each thread, allowing some initial
75  * model-checking data to be recorded. This method also gets around makecontext
76  * not being 64-bit clean
77  */
78 void thread_startup()
79 {
80         Thread * curr_thread = thread_current();
81 #ifndef TLS
82         /* Add dummy "start" action, just to create a first clock vector */
83         model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
84 #endif
85
86         /* Call the actual thread function */
87         if (curr_thread->start_routine != NULL) {
88                 curr_thread->start_routine(curr_thread->arg);
89         } else if (curr_thread->pstart_routine != NULL) {
90                 // set pthread return value
91                 void *retval = curr_thread->pstart_routine(curr_thread->arg);
92                 curr_thread->set_pthread_return(retval);
93         }
94 #ifndef TLS
95         /* Finish thread properly */
96         model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, curr_thread));
97 #endif
98 }
99
100 static int (*pthread_mutex_init_p)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) = NULL;
101
102 int real_pthread_mutex_init(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) {
103         return pthread_mutex_init_p(__mutex, __mutexattr);
104 }
105
106 static int (*pthread_mutex_lock_p) (pthread_mutex_t *__mutex) = NULL;
107
108 int real_pthread_mutex_lock (pthread_mutex_t *__mutex) {
109         return pthread_mutex_lock_p(__mutex);
110 }
111
112 static int (*pthread_mutex_unlock_p) (pthread_mutex_t *__mutex) = NULL;
113
114 int real_pthread_mutex_unlock (pthread_mutex_t *__mutex) {
115         return pthread_mutex_unlock_p(__mutex);
116 }
117
118 static int (*pthread_create_p) (pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void * __restrict) = NULL;
119
120 int real_pthread_create (pthread_t *__restrict __newthread, const pthread_attr_t *__restrict __attr, void *(*__start_routine)(void *), void *__restrict __arg) {
121         return pthread_create_p(__newthread, __attr, __start_routine, __arg);
122 }
123
124 static int (*pthread_join_p) (pthread_t __th, void ** __thread_return) = NULL;
125
126 int real_pthread_join (pthread_t __th, void ** __thread_return) {
127         return pthread_join_p(__th, __thread_return);
128 }
129
130 static void (*pthread_exit_p)(void *) __attribute__((noreturn))= NULL;
131
132 void real_pthread_exit (void * value_ptr) {
133         pthread_exit_p(value_ptr);
134 }
135
136 void real_init_all() {
137         char * error;
138         if (!pthread_mutex_init_p) {
139                 pthread_mutex_init_p = (int (*)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr))dlsym(RTLD_NEXT, "pthread_mutex_init");
140                 if ((error = dlerror()) != NULL) {
141                         fputs(error, stderr);
142                         exit(EXIT_FAILURE);
143                 }
144         }
145         if (!pthread_mutex_lock_p) {
146                 pthread_mutex_lock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_lock");
147                 if ((error = dlerror()) != NULL) {
148                         fputs(error, stderr);
149                         exit(EXIT_FAILURE);
150                 }
151         }
152         if (!pthread_mutex_unlock_p) {
153                 pthread_mutex_unlock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_unlock");
154                 if ((error = dlerror()) != NULL) {
155                         fputs(error, stderr);
156                         exit(EXIT_FAILURE);
157                 }
158         }
159         if (!pthread_create_p) {
160                 pthread_create_p = (int (*)(pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void *__restrict))dlsym(RTLD_NEXT, "pthread_create");
161                 if ((error = dlerror()) != NULL) {
162                         fputs(error, stderr);
163                         exit(EXIT_FAILURE);
164                 }
165         }
166         if (!pthread_join_p) {
167                 pthread_join_p = (int (*)(pthread_t __th, void ** __thread_return))dlsym(RTLD_NEXT, "pthread_join");
168                 if ((error = dlerror()) != NULL) {
169                         fputs(error, stderr);
170                         exit(EXIT_FAILURE);
171                 }
172         }
173
174         if (!pthread_exit_p) {
175                 *((void (**)(void *)) &pthread_exit_p) = (void (*)(void *))dlsym(RTLD_NEXT, "pthread_exit");
176                 if ((error = dlerror()) != NULL) {
177                         fputs(error, stderr);
178                         exit(EXIT_FAILURE);
179                 }
180         }
181 }
182
183 #ifdef TLS
184 void finalize_helper_thread() {
185         Thread * curr_thread = thread_current();
186         real_pthread_mutex_lock(&curr_thread->mutex);
187         curr_thread->tls = (char *) get_tls_addr();
188         real_pthread_mutex_unlock(&curr_thread->mutex);
189         //Wait in the kernel until it is time for us to finish
190         real_pthread_mutex_lock(&curr_thread->mutex2);
191         real_pthread_mutex_unlock(&curr_thread->mutex2);
192         //return to helper thread function
193         setcontext(&curr_thread->context);
194 }
195
196 void * helper_thread(void * ptr) {
197         Thread * curr_thread = thread_current();
198
199         //build a context for this real thread so we can take it's context
200         int ret = getcontext(&curr_thread->helpercontext);
201         ASSERT(!ret);
202
203         //Setup destructor
204         if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)4)) {
205                 printf("Destructor setup failed\n");
206                 exit(-1);
207         }
208
209
210         /* Initialize new managed context */
211         curr_thread->helper_stack = stack_allocate(STACK_SIZE);
212         curr_thread->helpercontext.uc_stack.ss_sp = curr_thread->helper_stack;
213         curr_thread->helpercontext.uc_stack.ss_size = STACK_SIZE;
214         curr_thread->helpercontext.uc_stack.ss_flags = 0;
215         curr_thread->helpercontext.uc_link = model->get_system_context();
216         makecontext(&curr_thread->helpercontext, finalize_helper_thread, 0);
217
218         model_swapcontext(&curr_thread->context, &curr_thread->helpercontext);
219
220
221         //start the real thread
222         thread_startup();
223
224         return NULL;
225 }
226
227 #ifdef TLS
228 void tlsdestructor(void *v) {
229         uintptr_t count = (uintptr_t) v;
230         if (count > 1) {
231                 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)(count - 1))) {
232                         printf("Destructor setup failed\n");
233                         exit(-1);
234                 }
235                 return;
236         }
237         /* Finish thread properly */
238         model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
239 }
240 #endif
241
242 void setup_context() {
243         Thread * curr_thread = thread_current();
244
245         /* Add dummy "start" action, just to create a first clock vector */
246         model->switch_thread(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
247
248         real_init_all();
249
250         /* Initialize our lock */
251         real_pthread_mutex_init(&curr_thread->mutex, NULL);
252         real_pthread_mutex_init(&curr_thread->mutex2, NULL);
253         real_pthread_mutex_lock(&curr_thread->mutex2);
254
255         /* Create the real thread */
256         real_pthread_create(&curr_thread->thread, NULL, helper_thread, NULL);
257         bool notdone = true;
258         while(notdone) {
259                 real_pthread_mutex_lock(&curr_thread->mutex);
260                 if (curr_thread->tls != NULL)
261                         notdone = false;
262                 real_pthread_mutex_unlock(&curr_thread->mutex);
263         }
264
265         set_tls_addr((uintptr_t)curr_thread->tls);
266         setcontext(&curr_thread->context);
267 }
268 #endif
269
270 /**
271  * Create a thread context for a new thread so we can use
272  * setcontext/getcontext/swapcontext to swap it out.
273  * @return 0 on success; otherwise, non-zero error condition
274  */
275 int Thread::create_context()
276 {
277         int ret;
278
279         ret = getcontext(&context);
280         if (ret)
281                 return ret;
282
283         /* Initialize new managed context */
284         stack = stack_allocate(STACK_SIZE);
285         context.uc_stack.ss_sp = stack;
286         context.uc_stack.ss_size = STACK_SIZE;
287         context.uc_stack.ss_flags = 0;
288         context.uc_link = model->get_system_context();
289 #ifdef TLS
290         makecontext(&context, setup_context, 0);
291 #else
292         makecontext(&context, thread_startup, 0);
293 #endif
294
295         return 0;
296 }
297
298 /**
299  * Swaps the current context to another thread of execution. This form switches
300  * from a user Thread to a system context.
301  * @param t Thread representing the currently-running thread. The current
302  * context is saved here.
303  * @param ctxt Context to which we will swap. Must hold a valid system context.
304  * @return Does not return, unless we return to Thread t's context. See
305  * swapcontext(3) (returns 0 for success, -1 for failure).
306  */
307 int Thread::swap(Thread *t, ucontext_t *ctxt)
308 {
309         t->set_state(THREAD_READY);
310 #ifdef TLS
311         set_tls_addr((uintptr_t)model->getInitThread()->tls);
312 #endif
313         return model_swapcontext(&t->context, ctxt);
314 }
315
316 /**
317  * Swaps the current context to another thread of execution. This form switches
318  * from a system context to a user Thread.
319  * @param ctxt System context variable to which to save the current context.
320  * @param t Thread to which we will swap. Must hold a valid user context.
321  * @return Does not return, unless we return to the system context (ctxt). See
322  * swapcontext(3) (returns 0 for success, -1 for failure).
323  */
324 int Thread::swap(ucontext_t *ctxt, Thread *t)
325 {
326         t->set_state(THREAD_RUNNING);
327 #ifdef TLS
328         if (t->tls != NULL)
329                 set_tls_addr((uintptr_t)t->tls);
330 #endif
331         return model_swapcontext(ctxt, &t->context);
332 }
333
334 int Thread::swap(Thread *t, Thread *t2)
335 {
336         t->set_state(THREAD_READY);
337         t2->set_state(THREAD_RUNNING);
338 #ifdef TLS
339         if (t2->tls != NULL)
340                 set_tls_addr((uintptr_t)t2->tls);
341 #endif
342         return model_swapcontext(&t->context, &t2->context);
343 }
344
345 /** Terminate a thread and free its stack. */
346 void Thread::complete()
347 {
348         ASSERT(!is_complete());
349         DEBUG("completed thread %d\n", id_to_int(get_id()));
350         state = THREAD_COMPLETED;
351         if (stack)
352                 stack_free(stack);
353 #ifdef TLS
354         if (this != model->getInitThread()) {
355                 ASSERT(thread_current()==NULL);
356                 real_pthread_mutex_unlock(&mutex2);
357                 real_pthread_join(thread, NULL);
358                 stack_free(helper_stack);
359         }
360 #endif
361 }
362
363 /**
364  * @brief Construct a new model-checker Thread
365  *
366  * A model-checker Thread is used for accounting purposes only. It will never
367  * have its own stack, and it should never be inserted into the Scheduler.
368  *
369  * @param tid The thread ID to assign
370  */
371 Thread::Thread(thread_id_t tid) :
372         parent(NULL),
373         acq_fence_cv(new ClockVector()),
374         creation(NULL),
375         pending(NULL),
376         start_routine(NULL),
377         arg(NULL),
378         stack(NULL),
379 #ifdef TLS
380         tls(NULL),
381 #endif
382         user_thread(NULL),
383         id(tid),
384         state(THREAD_READY),    /* Thread is always ready? */
385         last_action_val(0),
386         model_thread(true)
387 {
388         memset(&context, 0, sizeof(context));
389 }
390
391 /**
392  * Construct a new thread.
393  * @param t The thread identifier of the newly created thread.
394  * @param func The function that the thread will call.
395  * @param a The parameter to pass to this function.
396  */
397 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
398         parent(parent),
399         acq_fence_cv(new ClockVector()),
400         creation(NULL),
401         pending(NULL),
402         start_routine(func),
403         pstart_routine(NULL),
404         arg(a),
405 #ifdef TLS
406         tls(NULL),
407 #endif
408         user_thread(t),
409         id(tid),
410         state(THREAD_CREATED),
411         last_action_val(VALUE_NONE),
412         model_thread(false)
413 {
414         int ret;
415
416         /* Initialize state */
417         ret = create_context();
418         if (ret)
419                 model_print("Error in create_context\n");
420
421         user_thread->priv = this;       // WL
422 }
423
424 /**
425  * Construct a new thread for pthread.
426  * @param t The thread identifier of the newly created thread.
427  * @param func The function that the thread will call.
428  * @param a The parameter to pass to this function.
429  */
430 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
431         parent(parent),
432         acq_fence_cv(new ClockVector()),
433         creation(NULL),
434         pending(NULL),
435         start_routine(NULL),
436         pstart_routine(func),
437         arg(a),
438 #ifdef TLS
439         tls(NULL),
440 #endif
441         user_thread(t),
442         id(tid),
443         state(THREAD_CREATED),
444         last_action_val(VALUE_NONE),
445         model_thread(false)
446 {
447         int ret;
448
449         /* Initialize state */
450         ret = create_context();
451         if (ret)
452                 model_print("Error in create_context\n");
453 }
454
455
456 /** Destructor */
457 Thread::~Thread()
458 {
459         if (!is_complete())
460                 complete();
461
462         delete acq_fence_cv;
463 }
464
465 /** @return The thread_id_t corresponding to this Thread object. */
466 thread_id_t Thread::get_id() const
467 {
468         return id;
469 }
470
471 /**
472  * Set a thread's THREAD_* state (@see thread_state)
473  * @param s The state to enter
474  */
475 void Thread::set_state(thread_state s)
476 {
477         ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
478         state = s;
479 }
480
481 /**
482  * Get the Thread that this Thread is immediately waiting on
483  * @return The thread we are waiting on, if any; otherwise NULL
484  */
485 Thread * Thread::waiting_on() const
486 {
487         if (!pending)
488                 return NULL;
489
490         if (pending->get_type() == THREAD_JOIN)
491                 return pending->get_thread_operand();
492         else if (pending->get_type() == PTHREAD_JOIN)
493                 return pending->get_thread_operand();
494         else if (pending->is_lock())
495                 return (Thread *)pending->get_mutex()->get_state()->locked;
496         return NULL;
497 }
498
499 /**
500  * Check if this Thread is waiting (blocking) on a given Thread, directly or
501  * indirectly (via a chain of waiting threads)
502  *
503  * @param t The Thread on which we may be waiting
504  * @return True if we are waiting on Thread t; false otherwise
505  */
506 bool Thread::is_waiting_on(const Thread *t) const
507 {
508         Thread *wait;
509
510         // One thread relocks a recursive mutex
511         if (waiting_on() == t && pending->is_lock()) {
512                 int mutex_type = pending->get_mutex()->get_state()->type;
513                 if (mutex_type == PTHREAD_MUTEX_RECURSIVE)
514                         return false;
515         }
516
517         for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())
518                 if (wait == t)
519                         return true;
520         return false;
521 }