• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/threading/platform_thread_win.h"
6 
7 #include <stddef.h>
8 
9 #include <string>
10 
11 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/crash_logging.h"
14 #include "base/debug/profiler.h"
15 #include "base/feature_list.h"
16 #include "base/logging.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/process/memory.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/threading/scoped_blocking_call.h"
23 #include "base/threading/scoped_thread_priority.h"
24 #include "base/threading/thread_id_name_manager.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/threading/threading_features.h"
27 #include "base/time/time_override.h"
28 #include "base/win/scoped_handle.h"
29 #include "base/win/windows_version.h"
30 #include "build/build_config.h"
31 
32 #include <windows.h>
33 
34 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
35 #include "base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan.h"
36 #include "base/allocator/partition_allocator/src/partition_alloc/starscan/stack/stack.h"
37 #endif
38 
39 namespace base {
40 
41 BASE_FEATURE(kUseThreadPriorityLowest,
42              "UseThreadPriorityLowest",
43              base::FEATURE_DISABLED_BY_DEFAULT);
44 BASE_FEATURE(kAboveNormalCompositingBrowserWin,
45              "AboveNormalCompositingBrowserWin",
46              base::FEATURE_ENABLED_BY_DEFAULT);
47 
48 BASE_FEATURE(kBackgroundThreadNormalMemoryPriorityWin,
49              "BackgroundThreadNormalMemoryPriorityWin",
50              base::FEATURE_DISABLED_BY_DEFAULT);
51 
52 namespace {
53 
54 // Flag used to set thread priority to |THREAD_PRIORITY_LOWEST| for
55 // |kUseThreadPriorityLowest| Feature.
56 std::atomic<bool> g_use_thread_priority_lowest{false};
57 // Flag used to map Compositing ThreadType |THREAD_PRIORITY_ABOVE_NORMAL| on the
58 // UI thread for |kAboveNormalCompositingBrowserWin| Feature.
59 std::atomic<bool> g_above_normal_compositing_browser{true};
60 // Flag used to set thread memory priority to |MEMORY_PRIORITY_NORMAL| on
61 // background threads for |kThreadNormalMemoryPriorityWin| Feature.
62 std::atomic<bool> g_background_thread_normal_memory_priority_win{false};
63 
64 // These values are sometimes returned by ::GetThreadPriority().
65 constexpr int kWinDisplayPriority1 = 5;
66 constexpr int kWinDisplayPriority2 = 6;
67 
68 // The information on how to set the thread name comes from
69 // a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
70 const DWORD kVCThreadNameException = 0x406D1388;
71 
72 typedef struct tagTHREADNAME_INFO {
73   DWORD dwType;  // Must be 0x1000.
74   LPCSTR szName;  // Pointer to name (in user addr space).
75   DWORD dwThreadID;  // Thread ID (-1=caller thread).
76   DWORD dwFlags;  // Reserved for future use, must be zero.
77 } THREADNAME_INFO;
78 
79 // The SetThreadDescription API was brought in version 1607 of Windows 10.
80 typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread,
81                                               PCWSTR lpThreadDescription);
82 
83 // This function has try handling, so it is separated out of its caller.
SetNameInternal(PlatformThreadId thread_id,const char * name)84 void SetNameInternal(PlatformThreadId thread_id, const char* name) {
85   THREADNAME_INFO info;
86   info.dwType = 0x1000;
87   info.szName = name;
88   info.dwThreadID = thread_id;
89   info.dwFlags = 0;
90 
91   __try {
92     RaiseException(kVCThreadNameException, 0, sizeof(info) / sizeof(ULONG_PTR),
93                    reinterpret_cast<ULONG_PTR*>(&info));
94   } __except (EXCEPTION_EXECUTE_HANDLER) {
95   }
96 }
97 
98 struct ThreadParams {
99   raw_ptr<PlatformThread::Delegate> delegate;
100   bool joinable;
101   ThreadType thread_type;
102   MessagePumpType message_pump_type;
103 };
104 
ThreadFunc(void * params)105 DWORD __stdcall ThreadFunc(void* params) {
106   ThreadParams* thread_params = static_cast<ThreadParams*>(params);
107   PlatformThread::Delegate* delegate = thread_params->delegate;
108   if (!thread_params->joinable)
109     base::DisallowSingleton();
110 
111   if (thread_params->thread_type != ThreadType::kDefault)
112     internal::SetCurrentThreadType(thread_params->thread_type,
113                                    thread_params->message_pump_type);
114 
115   // Retrieve a copy of the thread handle to use as the key in the
116   // thread name mapping.
117   PlatformThreadHandle::Handle platform_handle;
118   BOOL did_dup = DuplicateHandle(GetCurrentProcess(),
119                                 GetCurrentThread(),
120                                 GetCurrentProcess(),
121                                 &platform_handle,
122                                 0,
123                                 FALSE,
124                                 DUPLICATE_SAME_ACCESS);
125 
126 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
127   partition_alloc::internal::PCScan::NotifyThreadCreated(
128       partition_alloc::internal::GetStackPointer());
129 #endif
130 
131   win::ScopedHandle scoped_platform_handle;
132 
133   if (did_dup) {
134     scoped_platform_handle.Set(platform_handle);
135     ThreadIdNameManager::GetInstance()->RegisterThread(
136         scoped_platform_handle.get(), PlatformThread::CurrentId());
137   }
138 
139   delete thread_params;
140   delegate->ThreadMain();
141 
142   if (did_dup) {
143     ThreadIdNameManager::GetInstance()->RemoveName(scoped_platform_handle.get(),
144                                                    PlatformThread::CurrentId());
145   }
146 
147 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN)
148   partition_alloc::internal::PCScan::NotifyThreadDestroyed();
149 #endif
150 
151   // Ensure thread priority is at least NORMAL before initiating thread
152   // destruction. Thread destruction on Windows holds the LdrLock while
153   // performing TLS destruction which causes hangs if performed at background
154   // priority (priority inversion) (see: http://crbug.com/1096203).
155   if (::GetThreadPriority(::GetCurrentThread()) < THREAD_PRIORITY_NORMAL)
156     PlatformThread::SetCurrentThreadType(ThreadType::kDefault);
157 
158   return 0;
159 }
160 
161 // CreateThreadInternal() matches PlatformThread::CreateWithType(), except
162 // that |out_thread_handle| may be nullptr, in which case a non-joinable thread
163 // is created.
CreateThreadInternal(size_t stack_size,PlatformThread::Delegate * delegate,PlatformThreadHandle * out_thread_handle,ThreadType thread_type,MessagePumpType message_pump_type)164 bool CreateThreadInternal(size_t stack_size,
165                           PlatformThread::Delegate* delegate,
166                           PlatformThreadHandle* out_thread_handle,
167                           ThreadType thread_type,
168                           MessagePumpType message_pump_type) {
169   unsigned int flags = 0;
170   if (stack_size > 0) {
171     flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
172 #if defined(ARCH_CPU_32_BITS)
173   } else {
174     // The process stack size is increased to give spaces to |RendererMain| in
175     // |chrome/BUILD.gn|, but keep the default stack size of other threads to
176     // 1MB for the address space pressure.
177     flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
178     static BOOL is_wow64 = -1;
179     if (is_wow64 == -1 && !IsWow64Process(GetCurrentProcess(), &is_wow64))
180       is_wow64 = FALSE;
181     // When is_wow64 is set that means we are running on 64-bit Windows and we
182     // get 4 GiB of address space. In that situation we can afford to use 1 MiB
183     // of address space for stacks. When running on 32-bit Windows we only get
184     // 2 GiB of address space so we need to conserve. Typically stack usage on
185     // these threads is only about 100 KiB.
186     if (is_wow64)
187       stack_size = 1024 * 1024;
188     else
189       stack_size = 512 * 1024;
190 #endif
191   }
192 
193   ThreadParams* params = new ThreadParams;
194   params->delegate = delegate;
195   params->joinable = out_thread_handle != nullptr;
196   params->thread_type = thread_type;
197   params->message_pump_type = message_pump_type;
198 
199   // Using CreateThread here vs _beginthreadex makes thread creation a bit
200   // faster and doesn't require the loader lock to be available.  Our code will
201   // have to work running on CreateThread() threads anyway, since we run code on
202   // the Windows thread pool, etc.  For some background on the difference:
203   // http://www.microsoft.com/msj/1099/win32/win321099.aspx
204   void* thread_handle =
205       ::CreateThread(nullptr, stack_size, ThreadFunc, params, flags, nullptr);
206 
207   if (!thread_handle) {
208     DWORD last_error = ::GetLastError();
209 
210     switch (last_error) {
211       case ERROR_NOT_ENOUGH_MEMORY:
212       case ERROR_OUTOFMEMORY:
213       case ERROR_COMMITMENT_LIMIT:
214         TerminateBecauseOutOfMemory(stack_size);
215         break;
216 
217       default:
218         static auto* last_error_crash_key = debug::AllocateCrashKeyString(
219             "create_thread_last_error", debug::CrashKeySize::Size32);
220         debug::SetCrashKeyString(last_error_crash_key,
221                                  base::NumberToString(last_error));
222         break;
223     }
224 
225     delete params;
226     return false;
227   }
228 
229   if (out_thread_handle)
230     *out_thread_handle = PlatformThreadHandle(thread_handle);
231   else
232     CloseHandle(thread_handle);
233   return true;
234 }
235 
236 }  // namespace
237 
238 namespace internal {
239 
AssertMemoryPriority(HANDLE thread,int memory_priority)240 void AssertMemoryPriority(HANDLE thread, int memory_priority) {
241 #if DCHECK_IS_ON()
242   static const auto get_thread_information_fn =
243       reinterpret_cast<decltype(&::GetThreadInformation)>(::GetProcAddress(
244           ::GetModuleHandle(L"Kernel32.dll"), "GetThreadInformation"));
245 
246   DCHECK(get_thread_information_fn);
247 
248   MEMORY_PRIORITY_INFORMATION memory_priority_information = {};
249   DCHECK(get_thread_information_fn(thread, ::ThreadMemoryPriority,
250                                    &memory_priority_information,
251                                    sizeof(memory_priority_information)));
252 
253   DCHECK_EQ(memory_priority,
254             static_cast<int>(memory_priority_information.MemoryPriority));
255 #endif
256 }
257 
258 }  // namespace internal
259 
260 // static
CurrentId()261 PlatformThreadId PlatformThread::CurrentId() {
262   return ::GetCurrentThreadId();
263 }
264 
265 // static
CurrentRef()266 PlatformThreadRef PlatformThread::CurrentRef() {
267   return PlatformThreadRef(::GetCurrentThreadId());
268 }
269 
270 // static
CurrentHandle()271 PlatformThreadHandle PlatformThread::CurrentHandle() {
272   return PlatformThreadHandle(::GetCurrentThread());
273 }
274 
275 // static
YieldCurrentThread()276 void PlatformThread::YieldCurrentThread() {
277   ::Sleep(0);
278 }
279 
280 // static
Sleep(TimeDelta duration)281 void PlatformThread::Sleep(TimeDelta duration) {
282   // When measured with a high resolution clock, Sleep() sometimes returns much
283   // too early. We may need to call it repeatedly to get the desired duration.
284   // PlatformThread::Sleep doesn't support mock-time, so this always uses
285   // real-time.
286   const TimeTicks end = subtle::TimeTicksNowIgnoringOverride() + duration;
287   for (TimeTicks now = subtle::TimeTicksNowIgnoringOverride(); now < end;
288        now = subtle::TimeTicksNowIgnoringOverride()) {
289     ::Sleep(static_cast<DWORD>((end - now).InMillisecondsRoundedUp()));
290   }
291 }
292 
293 // static
SetName(const std::string & name)294 void PlatformThread::SetName(const std::string& name) {
295   SetNameCommon(name);
296 
297   // The SetThreadDescription API works even if no debugger is attached.
298   static auto set_thread_description_func =
299       reinterpret_cast<SetThreadDescription>(::GetProcAddress(
300           ::GetModuleHandle(L"Kernel32.dll"), "SetThreadDescription"));
301   if (set_thread_description_func) {
302     set_thread_description_func(::GetCurrentThread(),
303                                 base::UTF8ToWide(name).c_str());
304   }
305 
306   // The debugger needs to be around to catch the name in the exception.  If
307   // there isn't a debugger, we are just needlessly throwing an exception.
308   if (!::IsDebuggerPresent())
309     return;
310 
311   SetNameInternal(CurrentId(), name.c_str());
312 }
313 
314 // static
GetName()315 const char* PlatformThread::GetName() {
316   return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
317 }
318 
319 // static
CreateWithType(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadType thread_type,MessagePumpType pump_type_hint)320 bool PlatformThread::CreateWithType(size_t stack_size,
321                                     Delegate* delegate,
322                                     PlatformThreadHandle* thread_handle,
323                                     ThreadType thread_type,
324                                     MessagePumpType pump_type_hint) {
325   DCHECK(thread_handle);
326   return CreateThreadInternal(stack_size, delegate, thread_handle, thread_type,
327                               pump_type_hint);
328 }
329 
330 // static
CreateNonJoinable(size_t stack_size,Delegate * delegate)331 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
332   return CreateNonJoinableWithType(stack_size, delegate, ThreadType::kDefault);
333 }
334 
335 // static
CreateNonJoinableWithType(size_t stack_size,Delegate * delegate,ThreadType thread_type,MessagePumpType pump_type_hint)336 bool PlatformThread::CreateNonJoinableWithType(size_t stack_size,
337                                                Delegate* delegate,
338                                                ThreadType thread_type,
339                                                MessagePumpType pump_type_hint) {
340   return CreateThreadInternal(stack_size, delegate, nullptr /* non-joinable */,
341                               thread_type, pump_type_hint);
342 }
343 
344 // static
Join(PlatformThreadHandle thread_handle)345 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
346   DCHECK(thread_handle.platform_handle());
347 
348   DWORD thread_id = 0;
349   thread_id = ::GetThreadId(thread_handle.platform_handle());
350   DWORD last_error = 0;
351   if (!thread_id)
352     last_error = ::GetLastError();
353 
354   // Record information about the exiting thread in case joining hangs.
355   base::debug::Alias(&thread_id);
356   base::debug::Alias(&last_error);
357 
358   base::internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call(
359       FROM_HERE, base::BlockingType::MAY_BLOCK);
360 
361   // Wait for the thread to exit.  It should already have terminated but make
362   // sure this assumption is valid.
363   CHECK_EQ(WAIT_OBJECT_0,
364            WaitForSingleObject(thread_handle.platform_handle(), INFINITE));
365   CloseHandle(thread_handle.platform_handle());
366 }
367 
368 // static
Detach(PlatformThreadHandle thread_handle)369 void PlatformThread::Detach(PlatformThreadHandle thread_handle) {
370   CloseHandle(thread_handle.platform_handle());
371 }
372 
373 // static
CanChangeThreadType(ThreadType from,ThreadType to)374 bool PlatformThread::CanChangeThreadType(ThreadType from, ThreadType to) {
375   return true;
376 }
377 
378 namespace {
379 
SetCurrentThreadPriority(ThreadType thread_type,MessagePumpType pump_type_hint)380 void SetCurrentThreadPriority(ThreadType thread_type,
381                               MessagePumpType pump_type_hint) {
382   if (thread_type == ThreadType::kCompositing &&
383       pump_type_hint == MessagePumpType::UI &&
384       !g_above_normal_compositing_browser) {
385     // Ignore kCompositing thread type for UI thread as Windows has a
386     // priority boost mechanism. See
387     // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
388     return;
389   }
390 
391   PlatformThreadHandle::Handle thread_handle =
392       PlatformThread::CurrentHandle().platform_handle();
393 
394   if (!g_use_thread_priority_lowest && thread_type != ThreadType::kBackground) {
395     // Exit background mode if the new priority is not BACKGROUND. This is a
396     // no-op if not in background mode.
397     ::SetThreadPriority(thread_handle, THREAD_MODE_BACKGROUND_END);
398     // We used to DCHECK that memory priority is MEMORY_PRIORITY_NORMAL here,
399     // but found that it is not always the case (e.g. in the installer).
400     // crbug.com/1340578#c2
401   }
402 
403   int desired_priority = THREAD_PRIORITY_ERROR_RETURN;
404   switch (thread_type) {
405     case ThreadType::kBackground:
406       // Using THREAD_MODE_BACKGROUND_BEGIN instead of THREAD_PRIORITY_LOWEST
407       // improves input latency and navigation time. See
408       // https://docs.google.com/document/d/16XrOwuwTwKWdgPbcKKajTmNqtB4Am8TgS9GjbzBYLc0
409       //
410       // MSDN recommends THREAD_MODE_BACKGROUND_BEGIN for threads that perform
411       // background work, as it reduces disk and memory priority in addition to
412       // CPU priority.
413       desired_priority =
414           g_use_thread_priority_lowest.load(std::memory_order_relaxed)
415               ? THREAD_PRIORITY_LOWEST
416               : THREAD_MODE_BACKGROUND_BEGIN;
417       break;
418     case ThreadType::kUtility:
419       desired_priority = THREAD_PRIORITY_BELOW_NORMAL;
420       break;
421     case ThreadType::kResourceEfficient:
422     case ThreadType::kDefault:
423       desired_priority = THREAD_PRIORITY_NORMAL;
424       break;
425     case ThreadType::kCompositing:
426     case ThreadType::kDisplayCritical:
427       desired_priority = THREAD_PRIORITY_ABOVE_NORMAL;
428       break;
429     case ThreadType::kRealtimeAudio:
430       desired_priority = THREAD_PRIORITY_TIME_CRITICAL;
431       break;
432   }
433   DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN);
434 
435   [[maybe_unused]] const BOOL cpu_priority_success =
436       ::SetThreadPriority(thread_handle, desired_priority);
437   DPLOG_IF(ERROR, !cpu_priority_success)
438       << "Failed to set thread priority to " << desired_priority;
439 
440   if (g_background_thread_normal_memory_priority_win &&
441       desired_priority == THREAD_MODE_BACKGROUND_BEGIN) {
442     // Override the memory priority.
443     MEMORY_PRIORITY_INFORMATION memory_priority{.MemoryPriority =
444                                                     MEMORY_PRIORITY_NORMAL};
445     [[maybe_unused]] const BOOL memory_priority_success =
446         SetThreadInformation(thread_handle, ::ThreadMemoryPriority,
447                              &memory_priority, sizeof(memory_priority));
448     DPLOG_IF(ERROR, !memory_priority_success)
449         << "Set thread memory priority failed.";
450   }
451 
452   if (!g_use_thread_priority_lowest && thread_type == ThreadType::kBackground) {
453     // In a background process, THREAD_MODE_BACKGROUND_BEGIN lowers the memory
454     // and I/O priorities but not the CPU priority (kernel bug?). Use
455     // THREAD_PRIORITY_LOWEST to also lower the CPU priority.
456     // https://crbug.com/901483
457     if (PlatformThread::GetCurrentThreadPriorityForTest() !=
458         ThreadPriorityForTest::kBackground) {
459       ::SetThreadPriority(thread_handle, THREAD_PRIORITY_LOWEST);
460       // We used to DCHECK that memory priority is MEMORY_PRIORITY_VERY_LOW
461       // here, but found that it is not always the case (e.g. in the installer).
462       // crbug.com/1340578#c2
463     }
464   }
465 }
466 
SetCurrentThreadQualityOfService(ThreadType thread_type)467 void SetCurrentThreadQualityOfService(ThreadType thread_type) {
468   // QoS and power throttling were introduced in Win10 1709.
469   bool desire_ecoqos = false;
470   switch (thread_type) {
471     case ThreadType::kBackground:
472     case ThreadType::kUtility:
473     case ThreadType::kResourceEfficient:
474       desire_ecoqos = true;
475       break;
476     case ThreadType::kDefault:
477     case ThreadType::kCompositing:
478     case ThreadType::kDisplayCritical:
479     case ThreadType::kRealtimeAudio:
480       desire_ecoqos = false;
481       break;
482   }
483 
484   THREAD_POWER_THROTTLING_STATE thread_power_throttling_state{
485       .Version = THREAD_POWER_THROTTLING_CURRENT_VERSION,
486       .ControlMask =
487           desire_ecoqos ? THREAD_POWER_THROTTLING_EXECUTION_SPEED : 0ul,
488       .StateMask =
489           desire_ecoqos ? THREAD_POWER_THROTTLING_EXECUTION_SPEED : 0ul,
490   };
491   [[maybe_unused]] const BOOL success = ::SetThreadInformation(
492       ::GetCurrentThread(), ::ThreadPowerThrottling,
493       &thread_power_throttling_state, sizeof(thread_power_throttling_state));
494   // Failure is expected on versions of Windows prior to RS3.
495   DPLOG_IF(ERROR, !success && win::GetVersion() >= win::Version::WIN10_RS3)
496       << "Failed to set EcoQoS to " << std::boolalpha << desire_ecoqos;
497 }
498 
499 }  // namespace
500 
501 namespace internal {
502 
SetCurrentThreadTypeImpl(ThreadType thread_type,MessagePumpType pump_type_hint)503 void SetCurrentThreadTypeImpl(ThreadType thread_type,
504                               MessagePumpType pump_type_hint) {
505   SetCurrentThreadPriority(thread_type, pump_type_hint);
506   SetCurrentThreadQualityOfService(thread_type);
507 }
508 
509 }  // namespace internal
510 
511 // static
GetCurrentThreadPriorityForTest()512 ThreadPriorityForTest PlatformThread::GetCurrentThreadPriorityForTest() {
513   static_assert(
514       THREAD_PRIORITY_IDLE < 0,
515       "THREAD_PRIORITY_IDLE is >= 0 and will incorrectly cause errors.");
516   static_assert(
517       THREAD_PRIORITY_LOWEST < 0,
518       "THREAD_PRIORITY_LOWEST is >= 0 and will incorrectly cause errors.");
519   static_assert(THREAD_PRIORITY_BELOW_NORMAL < 0,
520                 "THREAD_PRIORITY_BELOW_NORMAL is >= 0 and will incorrectly "
521                 "cause errors.");
522   static_assert(
523       THREAD_PRIORITY_NORMAL == 0,
524       "The logic below assumes that THREAD_PRIORITY_NORMAL is zero. If it is "
525       "not, ThreadPriorityForTest::kBackground may be incorrectly detected.");
526   static_assert(THREAD_PRIORITY_ABOVE_NORMAL >= 0,
527                 "THREAD_PRIORITY_ABOVE_NORMAL is < 0 and will incorrectly be "
528                 "translated to ThreadPriorityForTest::kBackground.");
529   static_assert(THREAD_PRIORITY_HIGHEST >= 0,
530                 "THREAD_PRIORITY_HIGHEST is < 0 and will incorrectly be "
531                 "translated to ThreadPriorityForTest::kBackground.");
532   static_assert(THREAD_PRIORITY_TIME_CRITICAL >= 0,
533                 "THREAD_PRIORITY_TIME_CRITICAL is < 0 and will incorrectly be "
534                 "translated to ThreadPriorityForTest::kBackground.");
535   static_assert(THREAD_PRIORITY_ERROR_RETURN >= 0,
536                 "THREAD_PRIORITY_ERROR_RETURN is < 0 and will incorrectly be "
537                 "translated to ThreadPriorityForTest::kBackground.");
538 
539   const int priority =
540       ::GetThreadPriority(PlatformThread::CurrentHandle().platform_handle());
541 
542   // Negative values represent a background priority. We have observed -3, -4,
543   // -6 when THREAD_MODE_BACKGROUND_* is used. THREAD_PRIORITY_IDLE,
544   // THREAD_PRIORITY_LOWEST and THREAD_PRIORITY_BELOW_NORMAL are other possible
545   // negative values.
546   if (priority < THREAD_PRIORITY_BELOW_NORMAL)
547     return ThreadPriorityForTest::kBackground;
548 
549   switch (priority) {
550     case THREAD_PRIORITY_BELOW_NORMAL:
551       return ThreadPriorityForTest::kUtility;
552     case THREAD_PRIORITY_NORMAL:
553       return ThreadPriorityForTest::kNormal;
554     case kWinDisplayPriority1:
555       [[fallthrough]];
556     case kWinDisplayPriority2:
557       return ThreadPriorityForTest::kDisplay;
558     case THREAD_PRIORITY_ABOVE_NORMAL:
559     case THREAD_PRIORITY_HIGHEST:
560       return ThreadPriorityForTest::kDisplay;
561     case THREAD_PRIORITY_TIME_CRITICAL:
562       return ThreadPriorityForTest::kRealtimeAudio;
563     case THREAD_PRIORITY_ERROR_RETURN:
564       DPCHECK(false) << "::GetThreadPriority error";
565   }
566 
567   NOTREACHED() << "::GetThreadPriority returned " << priority << ".";
568   return ThreadPriorityForTest::kNormal;
569 }
570 
InitializePlatformThreadFeatures()571 void InitializePlatformThreadFeatures() {
572   g_use_thread_priority_lowest.store(
573       FeatureList::IsEnabled(kUseThreadPriorityLowest),
574       std::memory_order_relaxed);
575   g_above_normal_compositing_browser.store(
576       FeatureList::IsEnabled(kAboveNormalCompositingBrowserWin),
577       std::memory_order_relaxed);
578   g_background_thread_normal_memory_priority_win.store(
579       FeatureList::IsEnabled(kBackgroundThreadNormalMemoryPriorityWin),
580       std::memory_order_relaxed);
581 }
582 
583 // static
GetDefaultThreadStackSize()584 size_t PlatformThread::GetDefaultThreadStackSize() {
585   return 0;
586 }
587 
588 }  // namespace base
589