1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
29 #include "pthread_internal.h"
31 #include <errno.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/mman.h>
36 #include "private/bionic_futex.h"
37 #include "private/bionic_tls.h"
38 #include "private/libc_logging.h"
39 #include "private/ScopedPthreadMutexLocker.h"
41 pthread_internal_t* g_thread_list = NULL;
42 pthread_mutex_t g_thread_list_lock = PTHREAD_MUTEX_INITIALIZER;
44 void _pthread_internal_remove_locked(pthread_internal_t* thread, bool free_thread) {
45 if (thread->next != NULL) {
46 thread->next->prev = thread->prev;
47 }
48 if (thread->prev != NULL) {
49 thread->prev->next = thread->next;
50 } else {
51 g_thread_list = thread->next;
52 }
54 // For threads using user allocated stack (including the main thread), the pthread_internal_t
55 // can't be freed since it is on the stack.
56 if (free_thread && !(thread->attr.flags & PTHREAD_ATTR_FLAG_USER_ALLOCATED_STACK)) {
57 // Use one munmap to free the whole thread stack, including pthread_internal_t.
58 munmap(thread->attr.stack_base, thread->attr.stack_size);
59 }
60 }
62 void _pthread_internal_add(pthread_internal_t* thread) {
63 ScopedPthreadMutexLocker locker(&g_thread_list_lock);
65 // We insert at the head.
66 thread->next = g_thread_list;
67 thread->prev = NULL;
68 if (thread->next != NULL) {
69 thread->next->prev = thread;
70 }
71 g_thread_list = thread;
72 }
74 pthread_internal_t* __get_thread(void) {
75 return reinterpret_cast<pthread_internal_t*>(__get_tls()[TLS_SLOT_THREAD_ID]);
76 }