Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
os_thread_win.cc
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#include "platform/globals.h" // NOLINT
6#if defined(DART_HOST_OS_WINDOWS) && !defined(DART_USE_ABSL)
7
8#include "vm/growable_array.h"
9#include "vm/lockers.h"
10#include "vm/os_thread.h"
11
12#include <process.h> // NOLINT
13
15#include "platform/assert.h"
16#include "platform/safe_stack.h"
17
18#include "vm/flags.h"
19
20namespace dart {
21
22DEFINE_FLAG(int,
23 worker_thread_priority,
24 kMinInt,
25 "The thread priority the VM should use for new worker threads.");
26
27// This flag is flipped by platform_win.cc when the process is exiting.
28// TODO(zra): Remove once VM shuts down cleanly.
29bool private_flag_windows_run_tls_destructors = true;
30
31class ThreadStartData {
32 public:
33 ThreadStartData(const char* name,
34 OSThread::ThreadStartFunction function,
35 uword parameter)
36 : name_(name), function_(function), parameter_(parameter) {}
37
38 const char* name() const { return name_; }
39 OSThread::ThreadStartFunction function() const { return function_; }
40 uword parameter() const { return parameter_; }
41
42 private:
43 const char* name_;
44 OSThread::ThreadStartFunction function_;
45 uword parameter_;
46
47 DISALLOW_COPY_AND_ASSIGN(ThreadStartData);
48};
49
50// Dispatch to the thread start function provided by the caller. This trampoline
51// is used to ensure that the thread is properly destroyed if the thread just
52// exits.
53static unsigned int __stdcall ThreadEntry(void* data_ptr) {
54 if (FLAG_worker_thread_priority != kMinInt) {
55 if (SetThreadPriority(GetCurrentThread(), FLAG_worker_thread_priority) ==
56 0) {
57 FATAL("Setting thread priority to %d failed: GetLastError() = %d\n",
58 FLAG_worker_thread_priority, GetLastError());
59 }
60 }
61
62 ThreadStartData* data = reinterpret_cast<ThreadStartData*>(data_ptr);
63
64 const char* name = data->name();
66 uword parameter = data->parameter();
67 delete data;
68
69 // Create new OSThread object and set as TLS for new thread.
70 OSThread* thread = OSThread::CreateOSThread();
71 if (thread != nullptr) {
73 thread->SetName(name);
74
75 // Call the supplied thread start function handing it its parameters.
76 function(parameter);
77 }
78
79 return 0;
80}
81
82int OSThread::Start(const char* name,
83 ThreadStartFunction function,
84 uword parameter) {
85 ThreadStartData* start_data = new ThreadStartData(name, function, parameter);
86 uint32_t tid;
87 uintptr_t thread = _beginthreadex(nullptr, OSThread::GetMaxStackSize(),
88 ThreadEntry, start_data, 0, &tid);
89 if (thread == -1L || thread == 0) {
90#ifdef DEBUG
91 fprintf(stderr, "_beginthreadex error: %d (%s)\n", errno, strerror(errno));
92#endif
93 return errno;
94 }
95
96 // Close the handle, so we don't leak the thread object.
97 CloseHandle(reinterpret_cast<HANDLE>(thread));
98
99 return 0;
100}
101
104
106 ThreadLocalKey key = TlsAlloc();
107 if (key == kUnsetThreadLocalKey) {
108 FATAL("TlsAlloc failed %d", GetLastError());
109 }
110 ThreadLocalData::AddThreadLocal(key, destructor);
111 return key;
112}
113
116 BOOL result = TlsFree(key);
117 if (!result) {
118 FATAL("TlsFree failed %d", GetLastError());
119 }
120 ThreadLocalData::RemoveThreadLocal(key);
121}
122
123intptr_t OSThread::GetMaxStackSize() {
124 const int kStackSize = (128 * kWordSize * KB);
125 return kStackSize;
126}
127
129 return ::GetCurrentThreadId();
130}
131
132#ifdef SUPPORT_TIMELINE
133ThreadId OSThread::GetCurrentThreadTraceId() {
134 return ::GetCurrentThreadId();
135}
136#endif // SUPPORT_TIMELINE
137
138char* OSThread::GetCurrentThreadName() {
139 // TODO(derekx): We aren't even setting the thread name on Windows, so we need
140 // to figure out how to set/get the thread name on Windows.
141 return nullptr;
142}
143
145 ASSERT(thread != nullptr);
146 // Make sure we're filling in the join id for the current thread.
148 ASSERT(thread->id() == id);
149 // Make sure the join_id_ hasn't been set, yet.
150 DEBUG_ASSERT(thread->join_id_ == kInvalidThreadJoinId);
151 HANDLE handle = OpenThread(SYNCHRONIZE, false, id);
152 ASSERT(handle != nullptr);
153#if defined(DEBUG)
154 thread->join_id_ = handle;
155#endif
156 return handle;
157}
158
160 HANDLE handle = static_cast<HANDLE>(id);
161 ASSERT(handle != nullptr);
162 DWORD res = WaitForSingleObject(handle, INFINITE);
163 CloseHandle(handle);
164 ASSERT(res == WAIT_OBJECT_0);
165}
166
168 COMPILE_ASSERT(sizeof(id) <= sizeof(intptr_t));
169 return static_cast<intptr_t>(id);
170}
171
173 return static_cast<ThreadId>(id);
174}
175
177 return a == b;
178}
179
180bool OSThread::GetCurrentStackBounds(uword* lower, uword* upper) {
181 // On Windows stack limits for the current thread are available in
182 // the thread information block (TIB).
183 NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
184 *upper = reinterpret_cast<uword>(tib->StackBase);
185 // Notice that we cannot use the TIB's StackLimit for the stack end, as it
186 // tracks the end of the committed range. We're after the end of the reserved
187 // stack area (most of which will be uncommitted, most times).
188 MEMORY_BASIC_INFORMATION stack_info;
189 memset(&stack_info, 0, sizeof(MEMORY_BASIC_INFORMATION));
190 size_t result_size =
191 VirtualQuery(&stack_info, &stack_info, sizeof(MEMORY_BASIC_INFORMATION));
192 ASSERT(result_size >= sizeof(MEMORY_BASIC_INFORMATION));
193 *lower = reinterpret_cast<uword>(stack_info.AllocationBase);
194 ASSERT(*upper > *lower);
195 // When the third last page of the reserved stack is accessed as a
196 // guard page, the second last page will be committed (along with removing
197 // the guard bit on the third last) _and_ a stack overflow exception
198 // is raised.
199 //
200 // http://blogs.msdn.com/b/satyem/archive/2012/08/13/thread-s-stack-memory-management.aspx
201 // explains the details.
202 ASSERT((*upper - *lower) >= (4u * 0x1000));
203 *lower += 4 * 0x1000;
204 return true;
205}
206
207#if defined(USING_SAFE_STACK)
210uword OSThread::GetCurrentSafestackPointer() {
211#error "SAFE_STACK is unsupported on this platform"
212 return 0;
213}
214
217void OSThread::SetCurrentSafestackPointer(uword ssp) {
218#error "SAFE_STACK is unsupported on this platform"
219}
220#endif
221
224 BOOL result = TlsSetValue(key, reinterpret_cast<void*>(value));
225 if (!result) {
226 FATAL("TlsSetValue failed %d", GetLastError());
227 }
228}
229
230Mutex::Mutex(NOT_IN_PRODUCT(const char* name))
231#if !defined(PRODUCT)
232 : name_(name)
233#endif
234{
235 InitializeSRWLock(&data_.lock_);
236#if defined(DEBUG)
237 // When running with assertions enabled we do track the owner.
239#endif // defined(DEBUG)
240}
241
243#if defined(DEBUG)
244 // When running with assertions enabled we do track the owner.
246#endif // defined(DEBUG)
247}
248
249void Mutex::Lock() {
250 DEBUG_ASSERT(!ThreadInterruptScope::in_thread_interrupt_scope());
251
252 AcquireSRWLockExclusive(&data_.lock_);
253#if defined(DEBUG)
254 // When running with assertions enabled we do track the owner.
256#endif // defined(DEBUG)
257}
258
259bool Mutex::TryLock() {
260 DEBUG_ASSERT(!ThreadInterruptScope::in_thread_interrupt_scope());
261
262 if (TryAcquireSRWLockExclusive(&data_.lock_) != 0) {
263#if defined(DEBUG)
264 // When running with assertions enabled we do track the owner.
266#endif // defined(DEBUG)
267 return true;
268 }
269 return false;
270}
271
272void Mutex::Unlock() {
273#if defined(DEBUG)
274 // When running with assertions enabled we do track the owner.
277#endif // defined(DEBUG)
278 ReleaseSRWLockExclusive(&data_.lock_);
279}
280
282 InitializeSRWLock(&data_.lock_);
283 InitializeConditionVariable(&data_.cond_);
284#if defined(DEBUG)
285 // When running with assertions enabled we track the owner.
287#endif // defined(DEBUG)
288}
289
291#if defined(DEBUG)
292 // When running with assertions enabled we track the owner.
294#endif // defined(DEBUG)
295}
296
297bool Monitor::TryEnter() {
298 DEBUG_ASSERT(!ThreadInterruptScope::in_thread_interrupt_scope());
299
300 // Attempt to pass the semaphore but return immediately.
301 if (TryAcquireSRWLockExclusive(&data_.lock_) != 0) {
302#if defined(DEBUG)
303 // When running with assertions enabled we do track the owner.
306#endif // defined(DEBUG)
307 return true;
308 }
309 return false;
310}
311
312void Monitor::Enter() {
313 DEBUG_ASSERT(!ThreadInterruptScope::in_thread_interrupt_scope());
314
315 AcquireSRWLockExclusive(&data_.lock_);
316
317#if defined(DEBUG)
318 // When running with assertions enabled we track the owner.
321#endif // defined(DEBUG)
322}
323
324void Monitor::Exit() {
325#if defined(DEBUG)
326 // When running with assertions enabled we track the owner.
329#endif // defined(DEBUG)
330
331 ReleaseSRWLockExclusive(&data_.lock_);
332}
333
334Monitor::WaitResult Monitor::Wait(int64_t millis) {
335#if defined(DEBUG)
336 // When running with assertions enabled we track the owner.
338 ThreadId saved_owner = owner_;
340#endif // defined(DEBUG)
341
343 if (millis == kNoTimeout) {
344 SleepConditionVariableSRW(&data_.cond_, &data_.lock_, INFINITE, 0);
345 } else {
346 // Wait for the given period of time for a Notify or a NotifyAll
347 // event.
348 if (!SleepConditionVariableSRW(&data_.cond_, &data_.lock_, millis, 0)) {
349 ASSERT(GetLastError() == ERROR_TIMEOUT);
350 retval = kTimedOut;
351 }
352 }
353
354#if defined(DEBUG)
355 // When running with assertions enabled we track the owner.
358 ASSERT(owner_ == saved_owner);
359#endif // defined(DEBUG)
360 return retval;
361}
362
363Monitor::WaitResult Monitor::WaitMicros(int64_t micros) {
364 // TODO(johnmccutchan): Investigate sub-millisecond sleep times on Windows.
365 int64_t millis = micros / kMicrosecondsPerMillisecond;
366 if ((millis * kMicrosecondsPerMillisecond) < micros) {
367 // We've been asked to sleep for a fraction of a millisecond,
368 // this isn't supported on Windows. Bumps milliseconds up by one
369 // so that we never return too early. We likely return late though.
370 millis += 1;
371 }
372 return Wait(millis);
373}
374
375void Monitor::Notify() {
376 // When running with assertions enabled we track the owner.
378 WakeConditionVariable(&data_.cond_);
379}
380
381void Monitor::NotifyAll() {
382 // When running with assertions enabled we track the owner.
384 WakeAllConditionVariable(&data_.cond_);
385}
386
387void ThreadLocalData::AddThreadLocal(ThreadLocalKey key,
388 ThreadDestructor destructor) {
389 ASSERT(thread_locals_ != nullptr);
390 if (destructor == nullptr) {
391 // We only care about thread locals with destructors.
392 return;
393 }
394 MutexLocker ml(mutex_);
395#if defined(DEBUG)
396 // Verify that we aren't added twice.
397 for (intptr_t i = 0; i < thread_locals_->length(); i++) {
398 const ThreadLocalEntry& entry = thread_locals_->At(i);
399 ASSERT(entry.key() != key);
400 }
401#endif
402 // Add to list.
403 thread_locals_->Add(ThreadLocalEntry(key, destructor));
404}
405
406void ThreadLocalData::RemoveThreadLocal(ThreadLocalKey key) {
407 ASSERT(thread_locals_ != nullptr);
408 MutexLocker ml(mutex_);
409 intptr_t i = 0;
410 for (; i < thread_locals_->length(); i++) {
411 const ThreadLocalEntry& entry = thread_locals_->At(i);
412 if (entry.key() == key) {
413 break;
414 }
415 }
416 if (i == thread_locals_->length()) {
417 // Not found.
418 return;
419 }
420 thread_locals_->RemoveAt(i);
421}
422
423// This function is executed on the thread that is exiting. It is invoked
424// by |OnDartThreadExit| (see below for notes on TLS destructors on Windows).
426 // If an OS thread is created but ThreadLocalData::Init has not yet been
427 // called, this method still runs. If this happens, there's nothing to clean
428 // up here. See issue 33826.
429 if (thread_locals_ == nullptr) {
430 return;
431 }
432 ASSERT(mutex_ != nullptr);
433 MutexLocker ml(mutex_);
434 for (intptr_t i = 0; i < thread_locals_->length(); i++) {
435 const ThreadLocalEntry& entry = thread_locals_->At(i);
436 // We access the exiting thread's TLS variable here.
437 void* p = reinterpret_cast<void*>(OSThread::GetThreadLocal(entry.key()));
438 // We invoke the constructor here.
439 entry.destructor()(p);
440 }
441}
442
443Mutex* ThreadLocalData::mutex_ = nullptr;
444MallocGrowableArray<ThreadLocalEntry>* ThreadLocalData::thread_locals_ =
445 nullptr;
446
447void ThreadLocalData::Init() {
448 mutex_ = new Mutex();
449 thread_locals_ = new MallocGrowableArray<ThreadLocalEntry>();
450}
451
452void ThreadLocalData::Cleanup() {
453 if (mutex_ != nullptr) {
454 delete mutex_;
455 mutex_ = nullptr;
456 }
457 if (thread_locals_ != nullptr) {
458 delete thread_locals_;
459 thread_locals_ = nullptr;
460 }
461}
462
463} // namespace dart
464
465// The following was adapted from Chromium:
466// src/base/threading/thread_local_storage_win.cc
467
468// Thread Termination Callbacks.
469// Windows doesn't support a per-thread destructor with its
470// TLS primitives. So, we build it manually by inserting a
471// function to be called on each thread's exit.
472// This magic is from http://www.codeproject.com/threads/tls.asp
473// and it works for VC++ 7.0 and later.
474
475// Force a reference to _tls_used to make the linker create the TLS directory
476// if it's not already there. (e.g. if __declspec(thread) is not used).
477// Force a reference to p_thread_callback_dart to prevent whole program
478// optimization from discarding the variable.
479#ifdef _WIN64
480
481#pragma comment(linker, "/INCLUDE:_tls_used")
482#pragma comment(linker, "/INCLUDE:p_thread_callback_dart")
483
484#else // _WIN64
485
486#pragma comment(linker, "/INCLUDE:__tls_used")
487#pragma comment(linker, "/INCLUDE:_p_thread_callback_dart")
488
489#endif // _WIN64
490
491// Static callback function to call with each thread termination.
492void NTAPI OnDartThreadExit(PVOID module, DWORD reason, PVOID reserved) {
493 if (!dart::private_flag_windows_run_tls_destructors) {
494 return;
495 }
496 // On XP SP0 & SP1, the DLL_PROCESS_ATTACH is never seen. It is sent on SP2+
497 // and on W2K and W2K3. So don't assume it is sent.
498 if (DLL_THREAD_DETACH == reason || DLL_PROCESS_DETACH == reason) {
500 }
501}
502
503// .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
504// called automatically by the OS loader code (not the CRT) when the module is
505// loaded and on thread creation. They are NOT called if the module has been
506// loaded by a LoadLibrary() call. It must have implicitly been loaded at
507// process startup.
508// By implicitly loaded, I mean that it is directly referenced by the main EXE
509// or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
510// implicitly loaded.
511//
512// See VC\crt\src\tlssup.c for reference.
513
514// extern "C" suppresses C++ name mangling so we know the symbol name for the
515// linker /INCLUDE:symbol pragma above.
516extern "C" {
517// The linker must not discard p_thread_callback_dart. (We force a reference
518// to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If
519// this variable is discarded, the OnDartThreadExit function will never be
520// called.
521#ifdef _WIN64
522
523// .CRT section is merged with .rdata on x64 so it must be constant data.
524#pragma const_seg(".CRT$XLB")
525// When defining a const variable, it must have external linkage to be sure the
526// linker doesn't discard it.
527extern const PIMAGE_TLS_CALLBACK p_thread_callback_dart;
528const PIMAGE_TLS_CALLBACK p_thread_callback_dart = OnDartThreadExit;
529
530// Reset the default section.
531#pragma const_seg()
532
533#else // _WIN64
534
535#pragma data_seg(".CRT$XLB")
536PIMAGE_TLS_CALLBACK p_thread_callback_dart = OnDartThreadExit;
537
538// Reset the default section.
539#pragma data_seg()
540
541#endif // _WIN64
542} // extern "C"
543
544#endif // defined(DART_HOST_OS_WINDOWS) && !defined(DART_USE_ABSL)
#define NO_SANITIZE_ADDRESS
#define DEBUG_ASSERT(cond)
Definition assert.h:321
#define COMPILE_ASSERT(expr)
Definition assert.h:339
bool IsOwnedByCurrentThread() const
Definition os_thread.h:370
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
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)
static OSThread * CreateOSThread()
Definition os_thread.cc:66
static void SetCurrent(OSThread *current)
Definition os_thread.h:182
static uword GetThreadLocal(ThreadLocalKey key)
Definition os_thread.h:218
static ThreadId ThreadIdFromIntPtr(intptr_t id)
static ThreadId GetCurrentThreadId()
static void Join(ThreadJoinId id)
static bool Compare(ThreadId a, ThreadId b)
static ThreadLocalKey CreateThreadLocal(ThreadDestructor destructor=nullptr)
static const ThreadId kInvalidThreadId
Definition os_thread.h:244
static ThreadJoinId GetCurrentThreadJoinId(OSThread *thread)
void(* ThreadStartFunction)(uword parameter)
Definition os_thread.h:205
static void SetThreadLocal(ThreadLocalKey key, uword value)
static intptr_t ThreadIdToIntPtr(ThreadId id)
static intptr_t GetMaxStackSize()
static const ThreadJoinId kInvalidThreadJoinId
Definition os_thread.h:245
static void RunDestructors()
#define ASSERT(E)
static bool b
struct MyStruct a[10]
#define FATAL(error)
GAsyncResult * result
#define DEFINE_FLAG(type, name, default_value, comment)
Definition flags.h:16
Dart_NativeFunction function
Definition fuchsia.cc:51
const char * name
Definition fuchsia.cc:50
constexpr int kMinInt
Definition globals.h:489
constexpr intptr_t kMicrosecondsPerMillisecond
Definition globals.h:561
const char *const name
pthread_t ThreadJoinId
constexpr intptr_t KB
Definition globals.h:528
uintptr_t uword
Definition globals.h:501
void(* ThreadDestructor)(void *parameter)
constexpr intptr_t kWordSize
Definition globals.h:509
pthread_key_t ThreadLocalKey
static int8_t data[kExtLength]
static const ThreadLocalKey kUnsetThreadLocalKey
pthread_t ThreadId
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition globals.h:581
#define NO_SANITIZE_SAFE_STACK
Definition safe_stack.h:17
#define NOT_IN_PRODUCT(code)
Definition globals.h:84
int BOOL
#define SYNCHRONIZE
void * PVOID
WINBASEAPI BOOLEAN WINAPI TryAcquireSRWLockExclusive(_Inout_ PSRWLOCK SRWLock)
WINBASEAPI _Releases_exclusive_lock_ SRWLock VOID WINAPI ReleaseSRWLockExclusive(_Inout_ PSRWLOCK SRWLock)
WINBASEAPI _Check_return_ _Post_equals_last_error_ DWORD WINAPI GetLastError(VOID)
void * HANDLE
unsigned long DWORD