2 * @brief Thread functions.
10 #include "threads-model.h"
13 /* global "model" object */
15 #include "execution.h"
20 uintptr_t get_tls_addr() {
22 asm ("mov %%fs:0, %0" : "=r" (addr));
26 #include <asm/prctl.h>
27 #include <sys/prctl.h>
29 int arch_prctl(int code, unsigned long addr);
31 static void set_tls_addr(uintptr_t addr) {
32 arch_prctl(ARCH_SET_FS, addr);
33 asm ("mov %0, %%fs:0" : : "r" (addr) : "memory");
37 /** Allocate a stack for a new thread. */
38 static void * stack_allocate(size_t size)
40 return Thread_malloc(size);
43 /** Free a stack for a terminated thread. */
44 static void stack_free(void *stack)
50 * @brief Get the current Thread
52 * Must be called from a user context
54 * @return The currently executing thread
56 Thread * thread_current(void)
59 return model->get_current_thread();
63 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
66 void initMainThread() {
68 Thread * curr_thread = thread_current();
69 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
73 * Provides a startup wrapper for each thread, allowing some initial
74 * model-checking data to be recorded. This method also gets around makecontext
75 * not being 64-bit clean
79 Thread * curr_thread = thread_current();
81 /* Add dummy "start" action, just to create a first clock vector */
82 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
85 /* Call the actual thread function */
86 if (curr_thread->start_routine != NULL) {
87 curr_thread->start_routine(curr_thread->arg);
88 } else if (curr_thread->pstart_routine != NULL) {
89 // set pthread return value
90 void *retval = curr_thread->pstart_routine(curr_thread->arg);
91 curr_thread->set_pthread_return(retval);
94 /* Finish thread properly */
95 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, curr_thread));
99 static int (*pthread_mutex_init_p)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) = NULL;
101 int real_pthread_mutex_init(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) {
102 return pthread_mutex_init_p(__mutex, __mutexattr);
105 static int (*pthread_mutex_lock_p) (pthread_mutex_t *__mutex) = NULL;
107 int real_pthread_mutex_lock (pthread_mutex_t *__mutex) {
108 return pthread_mutex_lock_p(__mutex);
111 static int (*pthread_mutex_unlock_p) (pthread_mutex_t *__mutex) = NULL;
113 int real_pthread_mutex_unlock (pthread_mutex_t *__mutex) {
114 return pthread_mutex_unlock_p(__mutex);
117 static int (*pthread_create_p) (pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void * __restrict) = NULL;
119 int real_pthread_create (pthread_t *__restrict __newthread, const pthread_attr_t *__restrict __attr, void *(*__start_routine)(void *), void *__restrict __arg) {
120 return pthread_create_p(__newthread, __attr, __start_routine, __arg);
123 static int (*pthread_join_p) (pthread_t __th, void ** __thread_return) = NULL;
125 int real_pthread_join (pthread_t __th, void ** __thread_return) {
126 return pthread_join_p(__th, __thread_return);
129 static void (*pthread_exit_p)(void *) __attribute__((noreturn))= NULL;
131 void real_pthread_exit (void * value_ptr) {
132 pthread_exit_p(value_ptr);
135 void real_init_all() {
137 if (!pthread_mutex_init_p) {
138 pthread_mutex_init_p = (int (*)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr))dlsym(RTLD_NEXT, "pthread_mutex_init");
139 if ((error = dlerror()) != NULL) {
140 fputs(error, stderr);
144 if (!pthread_mutex_lock_p) {
145 pthread_mutex_lock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_lock");
146 if ((error = dlerror()) != NULL) {
147 fputs(error, stderr);
151 if (!pthread_mutex_unlock_p) {
152 pthread_mutex_unlock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_unlock");
153 if ((error = dlerror()) != NULL) {
154 fputs(error, stderr);
158 if (!pthread_create_p) {
159 pthread_create_p = (int (*)(pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void *__restrict))dlsym(RTLD_NEXT, "pthread_create");
160 if ((error = dlerror()) != NULL) {
161 fputs(error, stderr);
165 if (!pthread_join_p) {
166 pthread_join_p = (int (*)(pthread_t __th, void ** __thread_return))dlsym(RTLD_NEXT, "pthread_join");
167 if ((error = dlerror()) != NULL) {
168 fputs(error, stderr);
173 if (!pthread_exit_p) {
174 *((void (**)(void *)) &pthread_exit_p) = (void (*)(void *))dlsym(RTLD_NEXT, "pthread_exit");
175 if ((error = dlerror()) != NULL) {
176 fputs(error, stderr);
183 void finalize_helper_thread() {
184 Thread * curr_thread = thread_current();
185 real_pthread_mutex_lock(&curr_thread->mutex);
186 curr_thread->tls = (char *) get_tls_addr();
187 real_pthread_mutex_unlock(&curr_thread->mutex);
188 //Wait in the kernel until it is time for us to finish
189 real_pthread_mutex_lock(&curr_thread->mutex2);
190 real_pthread_mutex_unlock(&curr_thread->mutex2);
191 //return to helper thread function
192 setcontext(&curr_thread->context);
195 void * helper_thread(void * ptr) {
196 Thread * curr_thread = thread_current();
198 //build a context for this real thread so we can take it's context
199 int ret = getcontext(&curr_thread->helpercontext);
203 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)4)) {
204 printf("Destructor setup failed\n");
209 /* Initialize new managed context */
210 curr_thread->helper_stack = stack_allocate(STACK_SIZE);
211 curr_thread->helpercontext.uc_stack.ss_sp = curr_thread->helper_stack;
212 curr_thread->helpercontext.uc_stack.ss_size = STACK_SIZE;
213 curr_thread->helpercontext.uc_stack.ss_flags = 0;
214 curr_thread->helpercontext.uc_link = model->get_system_context();
215 makecontext(&curr_thread->helpercontext, finalize_helper_thread, 0);
217 model_swapcontext(&curr_thread->context, &curr_thread->helpercontext);
220 //start the real thread
227 void tlsdestructor(void *v) {
228 uintptr_t count = (uintptr_t) v;
230 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)(count - 1))) {
231 printf("Destructor setup failed\n");
236 /* Finish thread properly */
237 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
241 void setup_context() {
242 Thread * curr_thread = thread_current();
244 /* Add dummy "start" action, just to create a first clock vector */
245 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
249 /* Initialize our lock */
250 real_pthread_mutex_init(&curr_thread->mutex, NULL);
251 real_pthread_mutex_init(&curr_thread->mutex2, NULL);
252 real_pthread_mutex_lock(&curr_thread->mutex2);
254 /* Create the real thread */
255 real_pthread_create(&curr_thread->thread, NULL, helper_thread, NULL);
258 real_pthread_mutex_lock(&curr_thread->mutex);
259 if (curr_thread->tls != NULL)
261 real_pthread_mutex_unlock(&curr_thread->mutex);
264 set_tls_addr((uintptr_t)curr_thread->tls);
265 setcontext(&curr_thread->context);
270 * Create a thread context for a new thread so we can use
271 * setcontext/getcontext/swapcontext to swap it out.
272 * @return 0 on success; otherwise, non-zero error condition
274 int Thread::create_context()
278 ret = getcontext(&context);
282 /* Initialize new managed context */
283 stack = stack_allocate(STACK_SIZE);
284 context.uc_stack.ss_sp = stack;
285 context.uc_stack.ss_size = STACK_SIZE;
286 context.uc_stack.ss_flags = 0;
287 context.uc_link = model->get_system_context();
289 makecontext(&context, setup_context, 0);
291 makecontext(&context, thread_startup, 0);
298 * Swaps the current context to another thread of execution. This form switches
299 * from a user Thread to a system context.
300 * @param t Thread representing the currently-running thread. The current
301 * context is saved here.
302 * @param ctxt Context to which we will swap. Must hold a valid system context.
303 * @return Does not return, unless we return to Thread t's context. See
304 * swapcontext(3) (returns 0 for success, -1 for failure).
306 int Thread::swap(Thread *t, ucontext_t *ctxt)
308 t->set_state(THREAD_READY);
310 set_tls_addr((uintptr_t)model->getInitThread()->tls);
312 return model_swapcontext(&t->context, ctxt);
316 * Swaps the current context to another thread of execution. This form switches
317 * from a system context to a user Thread.
318 * @param ctxt System context variable to which to save the current context.
319 * @param t Thread to which we will swap. Must hold a valid user context.
320 * @return Does not return, unless we return to the system context (ctxt). See
321 * swapcontext(3) (returns 0 for success, -1 for failure).
323 int Thread::swap(ucontext_t *ctxt, Thread *t)
325 t->set_state(THREAD_RUNNING);
328 set_tls_addr((uintptr_t)t->tls);
330 return model_swapcontext(ctxt, &t->context);
334 /** Terminate a thread and free its stack. */
335 void Thread::complete()
337 ASSERT(!is_complete());
338 DEBUG("completed thread %d\n", id_to_int(get_id()));
339 state = THREAD_COMPLETED;
343 if (this != model->getInitThread()) {
344 ASSERT(thread_current()==NULL);
345 real_pthread_mutex_unlock(&mutex2);
346 real_pthread_join(thread, NULL);
347 stack_free(helper_stack);
353 * @brief Construct a new model-checker Thread
355 * A model-checker Thread is used for accounting purposes only. It will never
356 * have its own stack, and it should never be inserted into the Scheduler.
358 * @param tid The thread ID to assign
360 Thread::Thread(thread_id_t tid) :
372 state(THREAD_READY), /* Thread is always ready? */
376 memset(&context, 0, sizeof(context));
380 * Construct a new thread.
381 * @param t The thread identifier of the newly created thread.
382 * @param func The function that the thread will call.
383 * @param a The parameter to pass to this function.
385 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
390 pstart_routine(NULL),
397 state(THREAD_CREATED),
398 last_action_val(VALUE_NONE),
403 /* Initialize state */
404 ret = create_context();
406 model_print("Error in create_context\n");
408 user_thread->priv = this; // WL
412 * Construct a new thread for pthread.
413 * @param t The thread identifier of the newly created thread.
414 * @param func The function that the thread will call.
415 * @param a The parameter to pass to this function.
417 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
422 pstart_routine(func),
429 state(THREAD_CREATED),
430 last_action_val(VALUE_NONE),
435 /* Initialize state */
436 ret = create_context();
438 model_print("Error in create_context\n");
449 /** @return The thread_id_t corresponding to this Thread object. */
450 thread_id_t Thread::get_id() const
456 * Set a thread's THREAD_* state (@see thread_state)
457 * @param s The state to enter
459 void Thread::set_state(thread_state s)
461 ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
466 * Get the Thread that this Thread is immediately waiting on
467 * @return The thread we are waiting on, if any; otherwise NULL
469 Thread * Thread::waiting_on() const
474 if (pending->get_type() == THREAD_JOIN)
475 return pending->get_thread_operand();
476 else if (pending->get_type() == PTHREAD_JOIN)
477 return pending->get_thread_operand();
478 else if (pending->is_lock())
479 return (Thread *)pending->get_mutex()->get_state()->locked;
484 * Check if this Thread is waiting (blocking) on a given Thread, directly or
485 * indirectly (via a chain of waiting threads)
487 * @param t The Thread on which we may be waiting
488 * @return True if we are waiting on Thread t; false otherwise
490 bool Thread::is_waiting_on(const Thread *t) const
493 for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())