Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
os_thread.h
Go to the documentation of this file.
1// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4
5#ifndef RUNTIME_VM_OS_THREAD_H_
6#define RUNTIME_VM_OS_THREAD_H_
7
8#include "platform/atomic.h"
9#include "platform/globals.h"
10#include "platform/safe_stack.h"
11#include "platform/utils.h"
12#include "vm/allocation.h"
13#include "vm/globals.h"
14
15// Declare the OS-specific types ahead of defining the generic classes.
16#if defined(DART_USE_ABSL)
17#include "vm/os_thread_absl.h"
18#elif defined(DART_HOST_OS_ANDROID)
20#elif defined(DART_HOST_OS_FUCHSIA)
22#elif defined(DART_HOST_OS_LINUX)
23#include "vm/os_thread_linux.h"
24#elif defined(DART_HOST_OS_MACOS)
25#include "vm/os_thread_macos.h"
26#elif defined(DART_HOST_OS_WINDOWS)
27#include "vm/os_thread_win.h"
28#else
29#error Unknown target os.
30#endif
31
32namespace dart {
33
34// Forward declarations.
35class Log;
36class Mutex;
37class ThreadState;
38class TimelineEventBlock;
39
40class Mutex {
41 public:
42 explicit Mutex(NOT_IN_PRODUCT(const char* name = "anonymous mutex"));
44
45 bool IsOwnedByCurrentThread() const;
46
47 private:
48 void Lock();
49 bool TryLock(); // Returns false if lock is busy and locking failed.
50 void Unlock();
51
52 MutexData data_;
53 NOT_IN_PRODUCT(const char* name_);
54#if defined(DEBUG)
55 ThreadId owner_;
56#endif // defined(DEBUG)
57
58 friend class MallocLocker;
59 friend class MutexLocker;
61 friend class OSThreadIterator;
64 friend class PageSpace;
65 friend void Dart_TestMutex();
67};
68
70 public:
71 bool is_os_thread() const { return is_os_thread_; }
72
73 private:
74 explicit BaseThread(bool is_os_thread) : is_os_thread_(is_os_thread) {}
75 virtual ~BaseThread() {}
76
77 bool is_os_thread_;
78
79 friend class ThreadState;
80 friend class OSThread;
81
83};
84
85// Low-level operations on OS platform threads.
86class OSThread : public BaseThread {
87 public:
88 static const uword kInvalidStackLimit = ~static_cast<uword>(0);
89
90 // The constructor of OSThread is never called directly, instead we call
91 // this factory style method 'CreateOSThread' to create OSThread structures.
92 // The method can return a nullptr if the Dart VM is in shutdown mode.
93 static OSThread* CreateOSThread();
94 ~OSThread();
95
96 ThreadId id() const {
98 return id_;
99 }
100
101#ifdef SUPPORT_TIMELINE
102 ThreadId trace_id() const {
104 return trace_id_;
105 }
106#endif
107
108 const char* name() const { return name_; }
109
110 void SetName(const char* name);
111
112 Mutex* timeline_block_lock() const { return &timeline_block_lock_; }
113
114 // Only safe to access when holding |timeline_block_lock_|.
115 TimelineEventBlock* TimelineBlockLocked() const {
116 ASSERT(timeline_block_lock()->IsOwnedByCurrentThread());
117 return timeline_block_;
118 }
119
120 // Only safe to access when holding |timeline_block_lock_|.
121 void SetTimelineBlockLocked(TimelineEventBlock* block) {
122 ASSERT(timeline_block_lock()->IsOwnedByCurrentThread());
123 timeline_block_ = block;
124 }
125
126 Log* log() const { return log_; }
127
128 uword stack_base() const { return stack_base_; }
129 uword stack_limit() const { return stack_limit_; }
130 uword overflow_stack_limit() const { return stack_limit_ + stack_headroom_; }
131
132 bool HasStackHeadroom() { return HasStackHeadroom(stack_headroom_); }
133 bool HasStackHeadroom(intptr_t headroom) {
134 return GetCurrentStackPointer() > (stack_limit_ + headroom);
135 }
136
137 // May fail for the main thread on Linux if resources are low.
138 static bool GetCurrentStackBounds(uword* lower, uword* upper);
139
140 // Returns the current C++ stack pointer. Equivalent taking the address of a
141 // stack allocated local, but plays well with AddressSanitizer and SafeStack.
142 // Accurate enough for stack overflow checks but not accurate enough for
143 // alignment checks.
145
146#if defined(USING_SAFE_STACK)
147 static uword GetCurrentSafestackPointer();
148 static void SetCurrentSafestackPointer(uword ssp);
149#endif
150
151#if !defined(PRODUCT)
152 // Used to temporarily disable or enable thread interrupts.
156#endif // !defined(PRODUCT)
157
158 // The currently executing thread, or nullptr if not yet initialized.
160 BaseThread* thread = GetCurrentTLS();
161 OSThread* os_thread = nullptr;
162 if (thread != nullptr) {
163 if (thread->is_os_thread()) {
164 os_thread = reinterpret_cast<OSThread*>(thread);
165 } else {
166 ThreadState* vm_thread = reinterpret_cast<ThreadState*>(thread);
167 os_thread = GetOSThreadFromThread(vm_thread);
168 }
169 }
170 return os_thread;
171 }
172
173 // The currently executing thread. If there is no currently executing thread,
174 // a new OSThread is created and returned.
175 static OSThread* Current() {
176 OSThread* os_thread = TryCurrent();
177 if (os_thread == nullptr) {
178 os_thread = CreateAndSetUnknownThread();
179 }
180 return os_thread;
181 }
182 static void SetCurrent(OSThread* current) { SetCurrentTLS(current); }
183
184 static ThreadState* CurrentVMThread() { return current_vm_thread_; }
185#if defined(DEBUG)
186 static void SetCurrentVMThread(ThreadState* thread) {
187 current_vm_thread_ = thread;
188 }
189#endif
190
191 // TODO(5411455): Use flag to override default value and Validate the
192 // stack size by querying OS.
194 intptr_t headroom =
195 OSThread::CalculateHeadroom(OSThread::GetMaxStackSize());
196 ASSERT(headroom < OSThread::GetMaxStackSize());
197 uword stack_size = OSThread::GetMaxStackSize() - headroom;
198 return stack_size;
199 }
201 return reinterpret_cast<BaseThread*>(OSThread::GetThreadLocal(thread_key_));
202 }
203 static void SetCurrentTLS(BaseThread* value);
204
205 typedef void (*ThreadStartFunction)(uword parameter);
206 typedef void (*ThreadDestructor)(void* parameter);
207
208 // Start a thread running the specified function. Returns 0 if the
209 // thread started successfully and a system specific error code if
210 // the thread failed to start.
211 static int Start(const char* name,
213 uword parameter);
214
216 ThreadDestructor destructor = nullptr);
219 return ThreadInlineImpl::GetThreadLocal(key);
220 }
223 static intptr_t GetMaxStackSize();
224 static void Join(ThreadJoinId id);
225 static intptr_t ThreadIdToIntPtr(ThreadId id);
226 static ThreadId ThreadIdFromIntPtr(intptr_t id);
227 static bool Compare(ThreadId a, ThreadId b);
228
229 // This function can be called only once per OSThread, and should only be
230 // called when the returned id will eventually be passed to OSThread::Join().
232
233 // Called at VM startup and shutdown.
234 static void Init();
235
236 static bool IsThreadInList(ThreadId id);
237
238 static void DisableOSThreadCreation();
239 static void EnableOSThreadCreation();
240
241 static constexpr intptr_t kStackSizeBufferMax = (16 * KB * kWordSize);
242 static constexpr float kStackSizeBufferFraction = 0.5;
243
246
247 private:
248 // The constructor is private as CreateOSThread should be used
249 // to create a new OSThread structure.
250 OSThread();
251
252 // These methods should not be used in a generic way and hence
253 // are private, they have been added to solve the problem of
254 // accessing the VM thread structure from an OSThread object
255 // in the windows thread interrupter which is used for profiling.
256 // We could eliminate this requirement if the windows thread interrupter
257 // is implemented differently.
258 ThreadState* thread() const { return thread_; }
259 void set_thread(ThreadState* value) { thread_ = value; }
260
261 static void Cleanup();
262#ifdef SUPPORT_TIMELINE
263 static ThreadId GetCurrentThreadTraceId();
264#endif // SUPPORT_TIMELINE
265
266 // Retrieves the name given to the current thread at the OS level and returns
267 // it as a heap-allocated string that must eventually be freed by the caller
268 // using free. Returns |nullptr| when the name cannot be retrieved.
269 static char* GetCurrentThreadName();
270 static OSThread* GetOSThreadFromThread(ThreadState* thread);
271 static void AddThreadToListLocked(OSThread* thread);
272 static void RemoveThreadFromList(OSThread* thread);
273 static OSThread* CreateAndSetUnknownThread();
274
275 static uword CalculateHeadroom(uword stack_size) {
276 uword headroom = kStackSizeBufferFraction * stack_size;
277 return (headroom > kStackSizeBufferMax) ? kStackSizeBufferMax : headroom;
278 }
279
280 static ThreadLocalKey thread_key_;
281
282 const ThreadId id_;
283#if defined(DEBUG)
284 // In DEBUG mode we use this field to ensure that GetCurrentThreadJoinId is
285 // only called once per OSThread.
287#endif
288#ifdef SUPPORT_TIMELINE
289 const ThreadId trace_id_; // Used to interface with tracing tools.
290#endif
291 char* name_; // A name for this thread.
292
293 mutable Mutex timeline_block_lock_;
294 // The block that the timeline recorder has permitted this thread to write
295 // events to.
296 TimelineEventBlock* timeline_block_ = nullptr;
297
298 // All |Thread|s are registered in the thread list.
299 OSThread* thread_list_next_ = nullptr;
300
301#if !defined(PRODUCT)
302 // Thread interrupts disabled by default.
303 RelaxedAtomic<uintptr_t> thread_interrupt_disabled_ = {1};
304 bool prepared_for_interrupts_ = false;
305 void* thread_interrupter_state_ = nullptr;
306#endif // !defined(PRODUCT)
307
308 Log* log_;
309 uword stack_base_ = 0;
310 uword stack_limit_ = 0;
311 uword stack_headroom_ = 0;
312 ThreadState* thread_ = nullptr;
313 // The ThreadPool::Worker which owns this OSThread. If this OSThread was not
314 // started by a ThreadPool it will be nullptr. This TLS value is not
315 // protected and should only be read/written by the OSThread itself.
316 void* owning_thread_pool_worker_ = nullptr;
317
318 // thread_list_lock_ cannot have a static lifetime because the order in which
319 // destructors run is undefined. At the moment this lock cannot be deleted
320 // either since otherwise, if a thread only begins to run after we have
321 // started to run TLS destructors for a call to exit(), there will be a race
322 // on its deletion in CreateOSThread().
323 static Mutex* thread_list_lock_;
324 static OSThread* thread_list_head_;
325 static bool creation_enabled_;
326
327 // Inline initialization is important for avoiding unnecessary TLS
328 // initialization checks at each use.
329 static inline thread_local ThreadState* current_vm_thread_ = nullptr;
330
331 friend class Thread; // to access set_thread(Thread*).
332 friend class OSThreadIterator;
336 friend class ThreadPool; // to access owning_thread_pool_worker_
337};
338
339// Note that this takes the thread list lock, prohibiting threads from coming
340// on- or off-line.
342 public:
345
346 // Returns false when there are no more threads left.
347 bool HasNext() const;
348
349 // Returns the current thread and moves forward.
350 OSThread* Next();
351
352 private:
353 OSThread* next_;
354};
355
356class Monitor {
357 public:
359
360 static constexpr int64_t kNoTimeout = 0;
361
364
365#if defined(DEBUG)
366 bool IsOwnedByCurrentThread() const {
367 return owner_ == OSThread::GetCurrentThreadId();
368 }
369#else
371 UNREACHABLE();
372 return false;
373 }
374#endif
375
376 private:
377 bool TryEnter(); // Returns false if lock is busy and locking failed.
378 void Enter();
379 void Exit();
380
381 // Wait for notification or timeout.
382 WaitResult Wait(int64_t millis);
383 WaitResult WaitMicros(int64_t micros);
384
385 // Notify waiting threads.
386 void Notify();
387 void NotifyAll();
388
389 MonitorData data_; // OS-specific data.
390#if defined(DEBUG)
391 ThreadId owner_;
392#endif // defined(DEBUG)
393
394 friend class MonitorLocker;
396 friend class SafepointRwLock;
397 friend void Dart_TestMonitor();
399};
400
401inline bool Mutex::IsOwnedByCurrentThread() const {
402#if defined(DEBUG)
403 return owner_ == OSThread::GetCurrentThreadId();
404#else
405 UNREACHABLE();
406 return false;
407#endif
408}
409
410// Mark when we are running in a signal handler (Linux, Android) or with a
411// suspended thread (Windows, Mac, Fuchia). During this time, we cannot take
412// locks, access Thread/Isolate::Current(), or use malloc.
414#if defined(DEBUG)
415 public:
417 ASSERT(!in_thread_interrupt_scope_); // We don't use nested signals.
418 in_thread_interrupt_scope_ = true;
419
420 // Poison attempts to use Thread::Current. This is much cheaper than adding
421 // an assert in Thread::Current itself.
422 saved_current_vm_thread_ = OSThread::CurrentVMThread();
423 OSThread::SetCurrentVMThread(reinterpret_cast<ThreadState*>(0xabababab));
424 }
425
427 OSThread::SetCurrentVMThread(saved_current_vm_thread_);
428 in_thread_interrupt_scope_ = false;
429 }
430
431 static bool in_thread_interrupt_scope() { return in_thread_interrupt_scope_; }
432
433 private:
434 ThreadState* saved_current_vm_thread_;
435 static inline thread_local bool in_thread_interrupt_scope_ = false;
436#endif // DEBUG
437};
438
439} // namespace dart
440
441#endif // RUNTIME_VM_OS_THREAD_H_
#define UNREACHABLE()
Definition assert.h:248
friend class ThreadState
Definition os_thread.h:79
bool is_os_thread() const
Definition os_thread.h:71
virtual ~BaseThread()
Definition os_thread.h:75
bool IsOwnedByCurrentThread() const
Definition os_thread.h:370
friend void Dart_TestMonitor()
static constexpr int64_t kNoTimeout
Definition os_thread.h:360
Mutex(NOT_IN_PRODUCT(const char *name="anonymous mutex"))
bool IsOwnedByCurrentThread() const
Definition os_thread.h:401
friend class TimelineEventRingRecorder
Definition os_thread.h:63
friend void Dart_TestMutex()
friend class TimelineEventRecorder
Definition os_thread.h:62
friend class MallocLocker
Definition os_thread.h:58
bool HasStackHeadroom(intptr_t headroom)
Definition os_thread.h:133
uword stack_base() const
Definition os_thread.h:128
static constexpr intptr_t kStackSizeBufferMax
Definition os_thread.h:241
static void DeleteThreadLocal(ThreadLocalKey key)
static int Start(const char *name, ThreadStartFunction function, uword parameter)
const char * name() const
Definition os_thread.h:108
ThreadId id() const
Definition os_thread.h:96
static bool GetCurrentStackBounds(uword *lower, uword *upper)
Log * log() const
Definition os_thread.h:126
bool ThreadInterruptsEnabled()
Definition os_thread.cc:167
void DisableThreadInterrupts()
Definition os_thread.cc:143
static OSThread * CreateOSThread()
Definition os_thread.cc:66
void SetTimelineBlockLocked(TimelineEventBlock *block)
Definition os_thread.h:121
static void SetCurrent(OSThread *current)
Definition os_thread.h:182
static uword GetThreadLocal(ThreadLocalKey key)
Definition os_thread.h:218
void(* ThreadDestructor)(void *parameter)
Definition os_thread.h:206
void SetName(const char *name)
Definition os_thread.cc:115
static uword GetCurrentStackPointer()
Definition os_thread.cc:132
static OSThread * TryCurrent()
Definition os_thread.h:159
static ThreadId ThreadIdFromIntPtr(intptr_t id)
static const uword kInvalidStackLimit
Definition os_thread.h:88
static void SetCurrentTLS(BaseThread *value)
Definition os_thread.cc:318
static ThreadId GetCurrentThreadId()
TimelineEventBlock * TimelineBlockLocked() const
Definition os_thread.h:115
static void Join(ThreadJoinId id)
static ThreadState * CurrentVMThread()
Definition os_thread.h:184
friend class ThreadInterrupterFuchsia
Definition os_thread.h:333
static bool Compare(ThreadId a, ThreadId b)
static uword GetSpecifiedStackSize()
Definition os_thread.h:193
static ThreadLocalKey CreateThreadLocal(ThreadDestructor destructor=nullptr)
bool HasStackHeadroom()
Definition os_thread.h:132
static void Init()
Definition os_thread.cc:177
static OSThread * Current()
Definition os_thread.h:175
static void EnableOSThreadCreation()
Definition os_thread.cc:252
static void DisableOSThreadCreation()
Definition os_thread.cc:247
friend class ThreadInterrupterWin
Definition os_thread.h:335
static BaseThread * GetCurrentTLS()
Definition os_thread.h:200
uword stack_limit() const
Definition os_thread.h:129
friend class ThreadInterrupterMacOS
Definition os_thread.h:334
static const ThreadId kInvalidThreadId
Definition os_thread.h:244
uword overflow_stack_limit() const
Definition os_thread.h:130
static ThreadJoinId GetCurrentThreadJoinId(OSThread *thread)
void EnableThreadInterrupts()
Definition os_thread.cc:148
Mutex * timeline_block_lock() const
Definition os_thread.h:112
static bool IsThreadInList(ThreadId id)
Definition os_thread.cc:230
void(* ThreadStartFunction)(uword parameter)
Definition os_thread.h:205
static void SetThreadLocal(ThreadLocalKey key, uword value)
static intptr_t ThreadIdToIntPtr(ThreadId id)
static constexpr float kStackSizeBufferFraction
Definition os_thread.h:242
static intptr_t GetMaxStackSize()
static const ThreadJoinId kInvalidThreadJoinId
Definition os_thread.h:245
#define ASSERT(E)
static bool b
struct MyStruct a[10]
uint8_t value
Dart_NativeFunction function
Definition fuchsia.cc:51
void Log(const char *format,...) SK_PRINTF_LIKE(1
const char *const name
pthread_t ThreadJoinId
constexpr intptr_t KB
Definition globals.h:528
uintptr_t uword
Definition globals.h:501
constexpr intptr_t kWordSize
Definition globals.h:509
pthread_key_t ThreadLocalKey
pthread_t ThreadId
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName)
Definition globals.h:593
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition globals.h:581
#define NOT_IN_PRODUCT(code)
Definition globals.h:84