bug fix
[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_thread(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_thread(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_thread(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_thread(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 = NULL;
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_thread(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 = NULL;
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         t2->set_state(THREAD_RUNNING);
337         if (t == t2)
338                 return 0;
339
340 #ifdef TLS
341         if (t2->tls != NULL)
342                 set_tls_addr((uintptr_t)t2->tls);
343 #endif
344         return model_swapcontext(&t->context, &t2->context);
345 }
346
347 /** Terminate a thread. */
348 void Thread::complete()
349 {
350         ASSERT(!is_complete());
351         DEBUG("completed thread %d\n", id_to_int(get_id()));
352         state = THREAD_COMPLETED;
353 }
354
355 void Thread::freeResources() {
356         if (stack)
357                 stack_free(stack);
358 #ifdef TLS
359         if (this != model->getInitThread()) {
360                 ASSERT(thread_current()==NULL);
361                 real_pthread_mutex_unlock(&mutex2);
362                 real_pthread_join(thread, NULL);
363                 stack_free(helper_stack);
364         }
365 #endif
366 }
367
368 /**
369  * @brief Construct a new model-checker Thread
370  *
371  * A model-checker Thread is used for accounting purposes only. It will never
372  * have its own stack, and it should never be inserted into the Scheduler.
373  *
374  * @param tid The thread ID to assign
375  */
376 Thread::Thread(thread_id_t tid) :
377         parent(NULL),
378         acq_fence_cv(new ClockVector()),
379         creation(NULL),
380         pending(NULL),
381         start_routine(NULL),
382         arg(NULL),
383         stack(NULL),
384 #ifdef TLS
385         tls(NULL),
386 #endif
387         user_thread(NULL),
388         id(tid),
389         state(THREAD_READY),    /* Thread is always ready? */
390         last_action_val(0),
391         model_thread(true)
392 {
393         memset(&context, 0, sizeof(context));
394 }
395
396 /**
397  * Construct a new thread.
398  * @param t The thread identifier of the newly created thread.
399  * @param func The function that the thread will call.
400  * @param a The parameter to pass to this function.
401  */
402 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
403         parent(parent),
404         acq_fence_cv(new ClockVector()),
405         creation(NULL),
406         pending(NULL),
407         start_routine(func),
408         pstart_routine(NULL),
409         arg(a),
410 #ifdef TLS
411         tls(NULL),
412 #endif
413         user_thread(t),
414         id(tid),
415         state(THREAD_CREATED),
416         last_action_val(VALUE_NONE),
417         model_thread(false)
418 {
419         int ret;
420
421         /* Initialize state */
422         ret = create_context();
423         if (ret)
424                 model_print("Error in create_context\n");
425
426         user_thread->priv = this;       // WL
427 }
428
429 /**
430  * Construct a new thread for pthread.
431  * @param t The thread identifier of the newly created thread.
432  * @param func The function that the thread will call.
433  * @param a The parameter to pass to this function.
434  */
435 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
436         parent(parent),
437         acq_fence_cv(new ClockVector()),
438         creation(NULL),
439         pending(NULL),
440         start_routine(NULL),
441         pstart_routine(func),
442         arg(a),
443 #ifdef TLS
444         tls(NULL),
445 #endif
446         user_thread(t),
447         id(tid),
448         state(THREAD_CREATED),
449         last_action_val(VALUE_NONE),
450         model_thread(false)
451 {
452         int ret;
453
454         /* Initialize state */
455         ret = create_context();
456         if (ret)
457                 model_print("Error in create_context\n");
458 }
459
460
461 /** Destructor */
462 Thread::~Thread()
463 {
464         if (!is_complete())
465                 complete();
466
467         delete acq_fence_cv;
468 }
469
470 /** @return The thread_id_t corresponding to this Thread object. */
471 thread_id_t Thread::get_id() const
472 {
473         return id;
474 }
475
476 /**
477  * Set a thread's THREAD_* state (@see thread_state)
478  * @param s The state to enter
479  */
480 void Thread::set_state(thread_state s)
481 {
482         ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
483         state = s;
484 }
485
486 /**
487  * Get the Thread that this Thread is immediately waiting on
488  * @return The thread we are waiting on, if any; otherwise NULL
489  */
490 Thread * Thread::waiting_on() const
491 {
492         if (!pending)
493                 return NULL;
494
495         if (pending->get_type() == THREAD_JOIN)
496                 return pending->get_thread_operand();
497         else if (pending->get_type() == PTHREAD_JOIN)
498                 return pending->get_thread_operand();
499         else if (pending->is_lock())
500                 return (Thread *)pending->get_mutex()->get_state()->locked;
501         return NULL;
502 }
503
504 /**
505  * Check if this Thread is waiting (blocking) on a given Thread, directly or
506  * indirectly (via a chain of waiting threads)
507  *
508  * @param t The Thread on which we may be waiting
509  * @return True if we are waiting on Thread t; false otherwise
510  */
511 bool Thread::is_waiting_on(const Thread *t) const
512 {
513         Thread *wait;
514
515         // One thread relocks a recursive mutex
516         if (waiting_on() == t && pending->is_lock()) {
517                 int mutex_type = pending->get_mutex()->get_state()->type;
518                 if (mutex_type == PTHREAD_MUTEX_RECURSIVE)
519                         return false;
520         }
521
522         for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())
523                 if (wait == t)
524                         return true;
525         return false;
526 }