thread_restrictions.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_THREADING_THREAD_RESTRICTIONS_H_
  5. #define BASE_THREADING_THREAD_RESTRICTIONS_H_
  6. #include "base/base_export.h"
  7. #include "base/check_op.h"
  8. #include "base/gtest_prod_util.h"
  9. #include "base/location.h"
  10. #include "base/macros.h"
  11. #include "base/threading/hang_watcher.h"
  12. // -----------------------------------------------------------------------------
  13. // Usage documentation
  14. // -----------------------------------------------------------------------------
  15. //
  16. // Overview:
  17. // This file exposes functions to ban and allow certain slow operations
  18. // on a per-thread basis. To annotate *usage* of such slow operations, refer to
  19. // scoped_blocking_call.h instead.
  20. //
  21. // Specific allowances that can be controlled in this file are:
  22. // - Blocking call: Refers to any call that causes the calling thread to wait
  23. // off-CPU. It includes but is not limited to calls that wait on synchronous
  24. // file I/O operations: read or write a file from disk, interact with a pipe
  25. // or a socket, rename or delete a file, enumerate files in a directory, etc.
  26. // Acquiring a low contention lock is not considered a blocking call.
  27. //
  28. // - Waiting on a //base sync primitive: Refers to calling one of these methods:
  29. // - base::WaitableEvent::*Wait*
  30. // - base::ConditionVariable::*Wait*
  31. // - base::Process::WaitForExit*
  32. //
  33. // - Long CPU work: Refers to any code that takes more than 100 ms to
  34. // run when there is no CPU contention and no hard page faults and therefore,
  35. // is not suitable to run on a thread required to keep the browser responsive
  36. // (where jank could be visible to the user).
  37. //
  38. // The following disallowance functions are offered:
  39. // - DisallowBlocking(): Disallows blocking calls on the current thread.
  40. // - DisallowBaseSyncPrimitives(): Disallows waiting on a //base sync primitive
  41. // on the current thread.
  42. // - DisallowUnresponsiveTasks() Disallows blocking calls, waiting on a //base
  43. // sync primitive, and long cpu work on the current thread.
  44. //
  45. // In addition, scoped-allowance mechanisms are offered to make an exception
  46. // within a scope for a behavior that is normally disallowed.
  47. // - ScopedAllowBlocking(ForTesting): Allows blocking calls.
  48. // - ScopedAllowBaseSyncPrimitives(ForTesting)(OutsideBlockingScope): Allow
  49. // waiting on a //base sync primitive. The OutsideBlockingScope suffix allows
  50. // uses in a scope where blocking is also disallowed.
  51. //
  52. // Avoid using allowances outside of unit tests. In unit tests, use allowances
  53. // with the suffix "ForTesting".
  54. //
  55. // Prefer making blocking calls from tasks posted to base::ThreadPoolInstance
  56. // with base::MayBlock().
  57. //
  58. // Instead of waiting on a WaitableEvent or a ConditionVariable, prefer putting
  59. // the work that should happen after the wait in a continuation callback and
  60. // post it from where the WaitableEvent or ConditionVariable would have been
  61. // signaled. If something needs to be scheduled after many tasks have executed,
  62. // use base::BarrierClosure.
  63. //
  64. // On Windows, join processes asynchronously using base::win::ObjectWatcher.
  65. //
  66. // Where unavoidable, put ScopedAllow* instances in the narrowest scope possible
  67. // in the caller making the blocking call but no further down. For example: if a
  68. // Cleanup() method needs to do a blocking call, document Cleanup() as blocking
  69. // and add a ScopedAllowBlocking instance in callers that can't avoid making
  70. // this call from a context where blocking is banned, as such:
  71. //
  72. // void Client::MyMethod() {
  73. // (...)
  74. // {
  75. // // Blocking is okay here because XYZ.
  76. // ScopedAllowBlocking allow_blocking;
  77. // my_foo_->Cleanup();
  78. // }
  79. // (...)
  80. // }
  81. //
  82. // // This method can block.
  83. // void Foo::Cleanup() {
  84. // // Do NOT add the ScopedAllowBlocking in Cleanup() directly as that hides
  85. // // its blocking nature from unknowing callers and defeats the purpose of
  86. // // these checks.
  87. // FlushStateToDisk();
  88. // }
  89. //
  90. // Note: In rare situations where the blocking call is an implementation detail
  91. // (i.e. the impl makes a call that invokes AssertBlockingAllowed() but it
  92. // somehow knows that in practice this will not block), it might be okay to hide
  93. // the ScopedAllowBlocking instance in the impl with a comment explaining why
  94. // that's okay.
  95. class BrowserProcessImpl;
  96. class ChromeNSSCryptoModuleDelegate;
  97. class HistogramSynchronizer;
  98. class KeyStorageLinux;
  99. class NativeBackendKWallet;
  100. class NativeDesktopMediaList;
  101. namespace android_webview {
  102. class AwFormDatabaseService;
  103. class CookieManager;
  104. class ScopedAllowInitGLBindings;
  105. class VizCompositorThreadRunnerWebView;
  106. }
  107. namespace audio {
  108. class OutputDevice;
  109. }
  110. namespace blink {
  111. class DiskDataAllocator;
  112. class RTCVideoDecoderAdapter;
  113. class RTCVideoEncoder;
  114. class SourceStream;
  115. class VideoFrameResourceProvider;
  116. class WorkerThread;
  117. namespace scheduler {
  118. class WorkerThread;
  119. }
  120. }
  121. namespace cc {
  122. class CompletionEvent;
  123. class TileTaskManagerImpl;
  124. }
  125. namespace chromeos {
  126. class BlockingMethodCaller;
  127. class MojoUtils;
  128. namespace system {
  129. class StatisticsProviderImpl;
  130. }
  131. }
  132. namespace chrome_browser_net {
  133. class Predictor;
  134. }
  135. namespace chrome_cleaner {
  136. class SystemReportComponent;
  137. }
  138. namespace content {
  139. class BrowserGpuChannelHostFactory;
  140. class BrowserMainLoop;
  141. class BrowserProcessSubThread;
  142. class BrowserShutdownProfileDumper;
  143. class BrowserTestBase;
  144. class CategorizedWorkerPool;
  145. class DesktopCaptureDevice;
  146. class InProcessUtilityThread;
  147. class NestedMessagePumpAndroid;
  148. class NetworkServiceInstancePrivate;
  149. class PepperPrintSettingsManagerImpl;
  150. class RenderProcessHostImpl;
  151. class RenderWidgetHostViewMac;
  152. class RTCVideoDecoder;
  153. class SandboxHostLinux;
  154. class ScopedAllowWaitForDebugURL;
  155. class ServiceWorkerContextClient;
  156. class SoftwareOutputDeviceMus;
  157. class SynchronousCompositor;
  158. class SynchronousCompositorHost;
  159. class SynchronousCompositorSyncCallBridge;
  160. class TextInputClientMac;
  161. class WaitForProcessesToDumpProfilingInfo;
  162. class WebContentsViewMac;
  163. } // namespace content
  164. namespace cronet {
  165. class CronetPrefsManager;
  166. class CronetURLRequestContext;
  167. } // namespace cronet
  168. namespace dbus {
  169. class Bus;
  170. }
  171. namespace disk_cache {
  172. class BackendImpl;
  173. class InFlightIO;
  174. }
  175. namespace functions {
  176. class ExecScriptScopedAllowBaseSyncPrimitives;
  177. }
  178. namespace history_report {
  179. class HistoryReportJniBridge;
  180. }
  181. namespace gpu {
  182. class GpuChannelHost;
  183. }
  184. namespace leveldb_env {
  185. class DBTracker;
  186. }
  187. namespace location {
  188. namespace nearby {
  189. namespace chrome {
  190. class ScheduledExecutor;
  191. class SubmittableExecutor;
  192. } // namespace chrome
  193. } // namespace nearby
  194. } // namespace location
  195. namespace media {
  196. class AudioInputDevice;
  197. class AudioOutputDevice;
  198. class BlockingUrlProtocol;
  199. class PaintCanvasVideoRenderer;
  200. }
  201. namespace memory_instrumentation {
  202. class OSMetrics;
  203. }
  204. namespace metrics {
  205. class AndroidMetricsServiceClient;
  206. }
  207. namespace midi {
  208. class TaskService; // https://crbug.com/796830
  209. }
  210. namespace module_installer {
  211. class ScopedAllowModulePakLoad;
  212. }
  213. namespace mojo {
  214. class CoreLibraryInitializer;
  215. class SyncCallRestrictions;
  216. namespace core {
  217. class ScopedIPCSupport;
  218. }
  219. }
  220. namespace printing {
  221. class LocalPrinterHandlerDefault;
  222. class PrintJobWorker;
  223. class PrinterQuery;
  224. }
  225. namespace rlz_lib {
  226. class FinancialPing;
  227. }
  228. namespace syncer {
  229. class GetLocalChangesRequest;
  230. class HttpBridge;
  231. class ModelSafeWorker;
  232. }
  233. namespace ui {
  234. class CommandBufferClientImpl;
  235. class CommandBufferLocal;
  236. class DrmThreadProxy;
  237. class GpuState;
  238. }
  239. namespace weblayer {
  240. class BrowserContextImpl;
  241. class ContentBrowserClientImpl;
  242. class ProfileImpl;
  243. class WebLayerPathProvider;
  244. }
  245. namespace net {
  246. class MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
  247. class MultiThreadedProxyResolverScopedAllowJoinOnIO;
  248. class NetworkChangeNotifierMac;
  249. class NetworkConfigWatcherMacThread;
  250. namespace internal {
  251. class AddressTrackerLinux;
  252. }
  253. }
  254. namespace proxy_resolver {
  255. class ScopedAllowThreadJoinForProxyResolverV8Tracing;
  256. }
  257. namespace remoting {
  258. class AutoThread;
  259. namespace protocol {
  260. class ScopedAllowThreadJoinForWebRtcTransport;
  261. }
  262. }
  263. namespace resource_coordinator {
  264. class TabManagerDelegate;
  265. }
  266. namespace service_manager {
  267. class ServiceProcessLauncher;
  268. }
  269. namespace shell_integration_linux {
  270. class LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
  271. }
  272. namespace ui {
  273. class WindowResizeHelperMac;
  274. }
  275. namespace viz {
  276. class HostGpuMemoryBufferManager;
  277. }
  278. namespace vr {
  279. class VrShell;
  280. }
  281. namespace web {
  282. class WebMainLoop;
  283. class WebSubThread;
  284. }
  285. namespace webrtc {
  286. class DesktopConfigurationMonitor;
  287. }
  288. namespace base {
  289. namespace sequence_manager {
  290. namespace internal {
  291. class TaskQueueImpl;
  292. }
  293. } // namespace sequence_manager
  294. namespace android {
  295. class JavaHandlerThread;
  296. }
  297. namespace internal {
  298. class JobTaskSource;
  299. class TaskTracker;
  300. }
  301. class AdjustOOMScoreHelper;
  302. class FileDescriptorWatcher;
  303. class FilePath;
  304. class GetAppOutputScopedAllowBaseSyncPrimitives;
  305. class ScopedAllowThreadRecallForStackSamplingProfiler;
  306. class SimpleThread;
  307. class StackSamplingProfiler;
  308. class Thread;
  309. class WaitableEvent;
  310. bool PathProviderWin(int, FilePath*);
  311. #if DCHECK_IS_ON()
  312. #define INLINE_IF_DCHECK_IS_OFF BASE_EXPORT
  313. #define EMPTY_BODY_IF_DCHECK_IS_OFF
  314. #else
  315. #define INLINE_IF_DCHECK_IS_OFF inline
  316. // The static_assert() eats follow-on semicolons. `= default` would work
  317. // too, but it makes clang realize that all the Scoped classes are no-ops in
  318. // non-dcheck builds and it starts emitting many -Wunused-variable warnings.
  319. #define EMPTY_BODY_IF_DCHECK_IS_OFF \
  320. {} \
  321. static_assert(true, "")
  322. #endif
  323. namespace internal {
  324. // Asserts that blocking calls are allowed in the current scope. This is an
  325. // internal call, external code should use ScopedBlockingCall instead, which
  326. // serves as a precise annotation of the scope that may/will block.
  327. INLINE_IF_DCHECK_IS_OFF void AssertBlockingAllowed()
  328. EMPTY_BODY_IF_DCHECK_IS_OFF;
  329. } // namespace internal
  330. // Disallows blocking on the current thread.
  331. INLINE_IF_DCHECK_IS_OFF void DisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  332. // Disallows blocking calls within its scope.
  333. class BASE_EXPORT ScopedDisallowBlocking {
  334. public:
  335. ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  336. ~ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  337. private:
  338. #if DCHECK_IS_ON()
  339. const bool was_disallowed_;
  340. #endif
  341. DISALLOW_COPY_AND_ASSIGN(ScopedDisallowBlocking);
  342. };
  343. class BASE_EXPORT ScopedAllowBlocking {
  344. private:
  345. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest, ScopedAllowBlocking);
  346. friend class ScopedAllowBlockingForTesting;
  347. // This can only be instantiated by friends. Use ScopedAllowBlockingForTesting
  348. // in unit tests to avoid the friend requirement.
  349. friend class AdjustOOMScoreHelper;
  350. friend class StackSamplingProfiler;
  351. friend class android_webview::ScopedAllowInitGLBindings;
  352. friend class blink::DiskDataAllocator;
  353. friend class chromeos::MojoUtils; // http://crbug.com/1055467
  354. friend class content::BrowserProcessSubThread;
  355. friend class content::NetworkServiceInstancePrivate;
  356. friend class content::PepperPrintSettingsManagerImpl;
  357. friend class content::RenderProcessHostImpl;
  358. friend class content::RenderWidgetHostViewMac; // http://crbug.com/121917
  359. friend class content::WebContentsViewMac;
  360. friend class cronet::CronetPrefsManager;
  361. friend class cronet::CronetURLRequestContext;
  362. friend class memory_instrumentation::OSMetrics;
  363. friend class metrics::AndroidMetricsServiceClient;
  364. friend class module_installer::ScopedAllowModulePakLoad;
  365. friend class mojo::CoreLibraryInitializer;
  366. friend class printing::LocalPrinterHandlerDefault;
  367. friend class printing::PrintJobWorker;
  368. friend class resource_coordinator::TabManagerDelegate; // crbug.com/778703
  369. friend class web::WebSubThread;
  370. friend class weblayer::BrowserContextImpl;
  371. friend class weblayer::ContentBrowserClientImpl;
  372. friend class weblayer::ProfileImpl;
  373. friend class weblayer::WebLayerPathProvider;
  374. friend bool PathProviderWin(int, FilePath*);
  375. ScopedAllowBlocking(const Location& from_here = Location::Current());
  376. ~ScopedAllowBlocking();
  377. #if DCHECK_IS_ON()
  378. const bool was_disallowed_;
  379. #endif
  380. DISALLOW_COPY_AND_ASSIGN(ScopedAllowBlocking);
  381. };
  382. class ScopedAllowBlockingForTesting {
  383. public:
  384. ScopedAllowBlockingForTesting() {}
  385. ~ScopedAllowBlockingForTesting() {}
  386. private:
  387. #if DCHECK_IS_ON()
  388. ScopedAllowBlocking scoped_allow_blocking_;
  389. #endif
  390. DISALLOW_COPY_AND_ASSIGN(ScopedAllowBlockingForTesting);
  391. };
  392. INLINE_IF_DCHECK_IS_OFF void DisallowBaseSyncPrimitives()
  393. EMPTY_BODY_IF_DCHECK_IS_OFF;
  394. class BASE_EXPORT ScopedAllowBaseSyncPrimitives {
  395. private:
  396. // This can only be instantiated by friends. Use
  397. // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
  398. // requirement.
  399. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  400. ScopedAllowBaseSyncPrimitives);
  401. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  402. ScopedAllowBaseSyncPrimitivesResetsState);
  403. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  404. ScopedAllowBaseSyncPrimitivesWithBlockingDisallowed);
  405. // Allowed usage:
  406. friend class SimpleThread;
  407. friend class ::ChromeNSSCryptoModuleDelegate;
  408. friend class base::GetAppOutputScopedAllowBaseSyncPrimitives;
  409. friend class blink::SourceStream;
  410. friend class blink::WorkerThread;
  411. friend class blink::scheduler::WorkerThread;
  412. friend class chrome_cleaner::SystemReportComponent;
  413. friend class content::BrowserMainLoop;
  414. friend class content::BrowserProcessSubThread;
  415. friend class content::ServiceWorkerContextClient;
  416. friend class functions::ExecScriptScopedAllowBaseSyncPrimitives;
  417. friend class history_report::HistoryReportJniBridge;
  418. friend class internal::TaskTracker;
  419. friend class leveldb_env::DBTracker;
  420. friend class location::nearby::chrome::ScheduledExecutor;
  421. friend class location::nearby::chrome::SubmittableExecutor;
  422. friend class media::BlockingUrlProtocol;
  423. friend class mojo::core::ScopedIPCSupport;
  424. friend class net::MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
  425. friend class rlz_lib::FinancialPing;
  426. friend class shell_integration_linux::
  427. LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
  428. friend class syncer::HttpBridge;
  429. friend class syncer::GetLocalChangesRequest;
  430. friend class syncer::ModelSafeWorker;
  431. friend class webrtc::DesktopConfigurationMonitor;
  432. // Usage that should be fixed:
  433. friend class ::NativeBackendKWallet; // http://crbug.com/125331
  434. friend class ::chromeos::system::
  435. StatisticsProviderImpl; // http://crbug.com/125385
  436. friend class blink::VideoFrameResourceProvider; // http://crbug.com/878070
  437. ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  438. ~ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  439. #if DCHECK_IS_ON()
  440. const bool was_disallowed_;
  441. #endif
  442. DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitives);
  443. };
  444. class BASE_EXPORT ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {
  445. private:
  446. // This can only be instantiated by friends. Use
  447. // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
  448. // requirement.
  449. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  450. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope);
  451. FRIEND_TEST_ALL_PREFIXES(
  452. ThreadRestrictionsTest,
  453. ScopedAllowBaseSyncPrimitivesOutsideBlockingScopeResetsState);
  454. // Allowed usage:
  455. friend class ::BrowserProcessImpl; // http://crbug.com/125207
  456. friend class ::KeyStorageLinux;
  457. friend class ::NativeDesktopMediaList;
  458. friend class android::JavaHandlerThread;
  459. friend class android_webview::
  460. AwFormDatabaseService; // http://crbug.com/904431
  461. friend class android_webview::CookieManager;
  462. friend class android_webview::VizCompositorThreadRunnerWebView;
  463. friend class audio::OutputDevice;
  464. friend class base::sequence_manager::internal::TaskQueueImpl;
  465. friend class base::FileDescriptorWatcher;
  466. friend class base::internal::JobTaskSource;
  467. friend class base::ScopedAllowThreadRecallForStackSamplingProfiler;
  468. friend class base::StackSamplingProfiler;
  469. friend class blink::RTCVideoDecoderAdapter;
  470. friend class blink::RTCVideoEncoder;
  471. friend class cc::TileTaskManagerImpl;
  472. friend class content::CategorizedWorkerPool;
  473. friend class content::DesktopCaptureDevice;
  474. friend class content::InProcessUtilityThread;
  475. friend class content::RTCVideoDecoder;
  476. friend class content::SandboxHostLinux;
  477. friend class content::ScopedAllowWaitForDebugURL;
  478. friend class content::SynchronousCompositor;
  479. friend class content::SynchronousCompositorHost;
  480. friend class content::SynchronousCompositorSyncCallBridge;
  481. friend class content::WaitForProcessesToDumpProfilingInfo;
  482. friend class media::AudioInputDevice;
  483. friend class media::AudioOutputDevice;
  484. friend class media::PaintCanvasVideoRenderer;
  485. friend class mojo::SyncCallRestrictions;
  486. friend class net::NetworkConfigWatcherMacThread;
  487. friend class ui::DrmThreadProxy;
  488. friend class viz::HostGpuMemoryBufferManager;
  489. friend class vr::VrShell;
  490. // Usage that should be fixed:
  491. friend class ::chromeos::BlockingMethodCaller; // http://crbug.com/125360
  492. friend class base::Thread; // http://crbug.com/918039
  493. friend class cc::CompletionEvent; // http://crbug.com/902653
  494. friend class content::
  495. BrowserGpuChannelHostFactory; // http://crbug.com/125248
  496. friend class dbus::Bus; // http://crbug.com/125222
  497. friend class disk_cache::BackendImpl; // http://crbug.com/74623
  498. friend class disk_cache::InFlightIO; // http://crbug.com/74623
  499. friend class gpu::GpuChannelHost; // http://crbug.com/125264
  500. friend class remoting::protocol::
  501. ScopedAllowThreadJoinForWebRtcTransport; // http://crbug.com/660081
  502. friend class midi::TaskService; // https://crbug.com/796830
  503. friend class net::internal::AddressTrackerLinux; // http://crbug.com/125097
  504. friend class net::
  505. MultiThreadedProxyResolverScopedAllowJoinOnIO; // http://crbug.com/69710
  506. friend class net::NetworkChangeNotifierMac; // http://crbug.com/125097
  507. friend class printing::PrinterQuery; // http://crbug.com/66082
  508. friend class proxy_resolver::
  509. ScopedAllowThreadJoinForProxyResolverV8Tracing; // http://crbug.com/69710
  510. friend class remoting::AutoThread; // https://crbug.com/944316
  511. // Not used in production yet, https://crbug.com/844078.
  512. friend class service_manager::ServiceProcessLauncher;
  513. friend class ui::WindowResizeHelperMac; // http://crbug.com/902829
  514. friend class content::TextInputClientMac; // http://crbug.com/121917
  515. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope(
  516. const Location& from_here = Location::Current());
  517. ~ScopedAllowBaseSyncPrimitivesOutsideBlockingScope();
  518. #if DCHECK_IS_ON()
  519. const bool was_disallowed_;
  520. #endif
  521. // Since this object is used to indicate that sync primitives will be used to
  522. // wait for an event ignore the current operation for hang watching purposes
  523. // since the wait time duration is unknown.
  524. base::HangWatchScopeDisabled hang_watch_scope_disabled_;
  525. DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitivesOutsideBlockingScope);
  526. };
  527. // Allow base-sync-primitives in tests, doesn't require explicit friend'ing like
  528. // ScopedAllowBaseSyncPrimitives-types aimed at production do.
  529. // Note: For WaitableEvents in the test logic, base::TestWaitableEvent is
  530. // exposed as a convenience to avoid the need for
  531. // ScopedAllowBaseSyncPrimitivesForTesting.
  532. class BASE_EXPORT ScopedAllowBaseSyncPrimitivesForTesting {
  533. public:
  534. ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  535. ~ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  536. private:
  537. #if DCHECK_IS_ON()
  538. const bool was_disallowed_;
  539. #endif
  540. DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitivesForTesting);
  541. };
  542. // Counterpart to base::DisallowUnresponsiveTasks() for tests to allow them to
  543. // block their thread after it was banned.
  544. class BASE_EXPORT ScopedAllowUnresponsiveTasksForTesting {
  545. public:
  546. ScopedAllowUnresponsiveTasksForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  547. ~ScopedAllowUnresponsiveTasksForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  548. private:
  549. #if DCHECK_IS_ON()
  550. const bool was_disallowed_base_sync_;
  551. const bool was_disallowed_blocking_;
  552. const bool was_disallowed_cpu_;
  553. #endif
  554. DISALLOW_COPY_AND_ASSIGN(ScopedAllowUnresponsiveTasksForTesting);
  555. };
  556. namespace internal {
  557. // Asserts that waiting on a //base sync primitive is allowed in the current
  558. // scope.
  559. INLINE_IF_DCHECK_IS_OFF void AssertBaseSyncPrimitivesAllowed()
  560. EMPTY_BODY_IF_DCHECK_IS_OFF;
  561. // Resets all thread restrictions on the current thread.
  562. INLINE_IF_DCHECK_IS_OFF void ResetThreadRestrictionsForTesting()
  563. EMPTY_BODY_IF_DCHECK_IS_OFF;
  564. } // namespace internal
  565. // Asserts that running long CPU work is allowed in the current scope.
  566. INLINE_IF_DCHECK_IS_OFF void AssertLongCPUWorkAllowed()
  567. EMPTY_BODY_IF_DCHECK_IS_OFF;
  568. INLINE_IF_DCHECK_IS_OFF void DisallowUnresponsiveTasks()
  569. EMPTY_BODY_IF_DCHECK_IS_OFF;
  570. class BASE_EXPORT ThreadRestrictions {
  571. public:
  572. // Constructing a ScopedAllowIO temporarily allows IO for the current
  573. // thread. Doing this is almost certainly always incorrect.
  574. //
  575. // DEPRECATED. Use ScopedAllowBlocking(ForTesting).
  576. class BASE_EXPORT ScopedAllowIO {
  577. public:
  578. ScopedAllowIO(const Location& from_here = Location::Current());
  579. ~ScopedAllowIO();
  580. private:
  581. #if DCHECK_IS_ON()
  582. const bool was_allowed_;
  583. #endif
  584. DISALLOW_COPY_AND_ASSIGN(ScopedAllowIO);
  585. };
  586. #if DCHECK_IS_ON()
  587. // Set whether the current thread to make IO calls.
  588. // Threads start out in the *allowed* state.
  589. // Returns the previous value.
  590. //
  591. // DEPRECATED. Use ScopedAllowBlocking(ForTesting) or ScopedDisallowBlocking.
  592. static bool SetIOAllowed(bool allowed);
  593. // Set whether the current thread can use singletons. Returns the previous
  594. // value.
  595. static bool SetSingletonAllowed(bool allowed);
  596. // Check whether the current thread is allowed to use singletons (Singleton /
  597. // LazyInstance). DCHECKs if not.
  598. static void AssertSingletonAllowed();
  599. // Disable waiting on the current thread. Threads start out in the *allowed*
  600. // state. Returns the previous value.
  601. //
  602. // DEPRECATED. Use DisallowBaseSyncPrimitives.
  603. static void DisallowWaiting();
  604. #else
  605. // Inline the empty definitions of these functions so that they can be
  606. // compiled out.
  607. static bool SetIOAllowed(bool allowed) { return true; }
  608. static bool SetSingletonAllowed(bool allowed) { return true; }
  609. static void AssertSingletonAllowed() {}
  610. static void DisallowWaiting() {}
  611. #endif
  612. private:
  613. // DO NOT ADD ANY OTHER FRIEND STATEMENTS.
  614. // BEGIN ALLOWED USAGE.
  615. friend class content::BrowserMainLoop;
  616. friend class content::BrowserShutdownProfileDumper;
  617. friend class content::BrowserTestBase;
  618. friend class content::ScopedAllowWaitForDebugURL;
  619. friend class ::HistogramSynchronizer;
  620. friend class internal::TaskTracker;
  621. friend class web::WebMainLoop;
  622. friend class MessagePumpDefault;
  623. friend class PlatformThread;
  624. friend class ui::CommandBufferClientImpl;
  625. friend class ui::CommandBufferLocal;
  626. friend class ui::GpuState;
  627. // END ALLOWED USAGE.
  628. // BEGIN USAGE THAT NEEDS TO BE FIXED.
  629. friend class chrome_browser_net::Predictor; // http://crbug.com/78451
  630. #if !defined(OFFICIAL_BUILD)
  631. friend class content::SoftwareOutputDeviceMus; // Interim non-production code
  632. #endif
  633. // END USAGE THAT NEEDS TO BE FIXED.
  634. #if DCHECK_IS_ON()
  635. // DEPRECATED. Use ScopedAllowBaseSyncPrimitives.
  636. static bool SetWaitAllowed(bool allowed);
  637. #else
  638. static bool SetWaitAllowed(bool allowed) { return true; }
  639. #endif
  640. DISALLOW_IMPLICIT_CONSTRUCTORS(ThreadRestrictions);
  641. };
  642. #undef INLINE_IF_DCHECK_IS_OFF
  643. #undef EMPTY_BODY_IF_DCHECK_IS_OFF
  644. } // namespace base
  645. #endif // BASE_THREADING_THREAD_RESTRICTIONS_H_