add support for freeing threads
[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                 real_pthread_mutex_unlock(&mutex2);
361                 real_pthread_join(thread, NULL);
362                 stack_free(helper_stack);
363         }
364 #endif
365         state = THREAD_FREED;
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         wakeup_state(false),
382         start_routine(NULL),
383         arg(NULL),
384         stack(NULL),
385 #ifdef TLS
386         tls(NULL),
387 #endif
388         user_thread(NULL),
389         id(tid),
390         state(THREAD_READY),    /* Thread is always ready? */
391         last_action_val(0),
392         model_thread(true)
393 {
394         memset(&context, 0, sizeof(context));
395 }
396
397 /**
398  * Construct a new thread.
399  * @param t The thread identifier of the newly created thread.
400  * @param func The function that the thread will call.
401  * @param a The parameter to pass to this function.
402  */
403 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
404         parent(parent),
405         acq_fence_cv(new ClockVector()),
406         creation(NULL),
407         pending(NULL),
408         wakeup_state(false),
409         start_routine(func),
410         pstart_routine(NULL),
411         arg(a),
412 #ifdef TLS
413         tls(NULL),
414 #endif
415         user_thread(t),
416         id(tid),
417         state(THREAD_CREATED),
418         last_action_val(VALUE_NONE),
419         model_thread(false)
420 {
421         int ret;
422
423         /* Initialize state */
424         ret = create_context();
425         if (ret)
426                 model_print("Error in create_context\n");
427
428         user_thread->priv = this;       // WL
429 }
430
431 /**
432  * Construct a new thread for pthread.
433  * @param t The thread identifier of the newly created thread.
434  * @param func The function that the thread will call.
435  * @param a The parameter to pass to this function.
436  */
437 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
438         parent(parent),
439         acq_fence_cv(new ClockVector()),
440         creation(NULL),
441         pending(NULL),
442         wakeup_state(false),
443         start_routine(NULL),
444         pstart_routine(func),
445         arg(a),
446 #ifdef TLS
447         tls(NULL),
448 #endif
449         user_thread(t),
450         id(tid),
451         state(THREAD_CREATED),
452         last_action_val(VALUE_NONE),
453         model_thread(false)
454 {
455         int ret;
456
457         /* Initialize state */
458         ret = create_context();
459         if (ret)
460                 model_print("Error in create_context\n");
461 }
462
463
464 /** Destructor */
465 Thread::~Thread()
466 {
467         if (!is_complete())
468                 complete();
469
470         delete acq_fence_cv;
471 }
472
473 /** @return The thread_id_t corresponding to this Thread object. */
474 thread_id_t Thread::get_id() const
475 {
476         return id;
477 }
478
479 /**
480  * Set a thread's THREAD_* state (@see thread_state)
481  * @param s The state to enter
482  */
483 void Thread::set_state(thread_state s)
484 {
485         ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
486         state = s;
487 }
488
489 /**
490  * Get the Thread that this Thread is immediately waiting on
491  * @return The thread we are waiting on, if any; otherwise NULL
492  */
493 Thread * Thread::waiting_on() const
494 {
495         if (!pending)
496                 return NULL;
497
498         if (pending->get_type() == THREAD_JOIN)
499                 return pending->get_thread_operand();
500         else if (pending->get_type() == PTHREAD_JOIN)
501                 return pending->get_thread_operand();
502         else if (pending->is_lock())
503                 return (Thread *)pending->get_mutex()->get_state()->locked;
504         return NULL;
505 }
506
507 /**
508  * Check if this Thread is waiting (blocking) on a given Thread, directly or
509  * indirectly (via a chain of waiting threads)
510  *
511  * @param t The Thread on which we may be waiting
512  * @return True if we are waiting on Thread t; false otherwise
513  */
514 bool Thread::is_waiting_on(const Thread *t) const
515 {
516         Thread *wait;
517
518         // One thread relocks a recursive mutex
519         if (waiting_on() == t && pending->is_lock()) {
520                 int mutex_type = pending->get_mutex()->get_state()->type;
521                 if (mutex_type == PTHREAD_MUTEX_RECURSIVE)
522                         return false;
523         }
524
525         for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())
526                 if (wait == t)
527                         return true;
528         return false;
529 }