thread_restrictions.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 <memory>
  7. #include "base/base_export.h"
  8. #include "base/compiler_specific.h"
  9. #include "base/dcheck_is_on.h"
  10. #include "base/gtest_prod_util.h"
  11. #include "base/location.h"
  12. #include "build/build_config.h"
  13. // -----------------------------------------------------------------------------
  14. // Usage documentation
  15. // -----------------------------------------------------------------------------
  16. //
  17. // Overview:
  18. // This file exposes functions to ban and allow certain slow operations
  19. // on a per-thread basis. To annotate *usage* of such slow operations, refer to
  20. // scoped_blocking_call.h instead.
  21. //
  22. // Specific allowances that can be controlled in this file are:
  23. // - Blocking call: Refers to any call that causes the calling thread to wait
  24. // off-CPU. It includes but is not limited to calls that wait on synchronous
  25. // file I/O operations: read or write a file from disk, interact with a pipe
  26. // or a socket, rename or delete a file, enumerate files in a directory, etc.
  27. // Acquiring a low contention lock is not considered a blocking call.
  28. //
  29. // - Waiting on a //base sync primitive: Refers to calling one of these methods:
  30. // - base::WaitableEvent::*Wait*
  31. // - base::ConditionVariable::*Wait*
  32. // - base::Process::WaitForExit*
  33. //
  34. // - Accessing singletons: Accessing global state (Singleton / LazyInstance) is
  35. // problematic on threads whom aren't joined on shutdown as they can be using
  36. // the state as it becomes invalid during tear down. base::NoDestructor is the
  37. // preferred alternative for global state and doesn't have this restriction.
  38. //
  39. // - Long CPU work: Refers to any code that takes more than 100 ms to
  40. // run when there is no CPU contention and no hard page faults and therefore,
  41. // is not suitable to run on a thread required to keep the browser responsive
  42. // (where jank could be visible to the user).
  43. //
  44. // The following disallowance functions are offered:
  45. // - DisallowBlocking(): Disallows blocking calls on the current thread.
  46. // - DisallowBaseSyncPrimitives(): Disallows waiting on a //base sync primitive
  47. // on the current thread.
  48. // - DisallowSingleton(): Disallows using singletons on the current thread.
  49. // - DisallowUnresponsiveTasks() Disallows blocking calls, waiting on a //base
  50. // sync primitive, and long CPU work on the current thread.
  51. //
  52. // In addition, scoped-allowance mechanisms are offered to make an exception
  53. // within a scope for a behavior that is normally disallowed.
  54. // - ScopedAllowBlocking(ForTesting): Allows blocking calls.
  55. // - ScopedAllowBaseSyncPrimitives(ForTesting)(OutsideBlockingScope): Allow
  56. // waiting on a //base sync primitive. The OutsideBlockingScope suffix allows
  57. // uses in a scope where blocking is also disallowed.
  58. //
  59. // Avoid using allowances outside of unit tests. In unit tests, use allowances
  60. // with the suffix "ForTesting".
  61. //
  62. // Prefer making blocking calls from tasks posted to base::ThreadPoolInstance
  63. // with base::MayBlock().
  64. //
  65. // Instead of waiting on a WaitableEvent or a ConditionVariable, prefer putting
  66. // the work that should happen after the wait in a continuation callback and
  67. // post it from where the WaitableEvent or ConditionVariable would have been
  68. // signaled. If something needs to be scheduled after many tasks have executed,
  69. // use base::BarrierClosure.
  70. //
  71. // On Windows, join processes asynchronously using base::win::ObjectWatcher.
  72. //
  73. // Where unavoidable, put ScopedAllow* instances in the narrowest scope possible
  74. // in the caller making the blocking call but no further down. For example: if a
  75. // Cleanup() method needs to do a blocking call, document Cleanup() as blocking
  76. // and add a ScopedAllowBlocking instance in callers that can't avoid making
  77. // this call from a context where blocking is banned, as such:
  78. //
  79. // void Client::MyMethod() {
  80. // (...)
  81. // {
  82. // // Blocking is okay here because XYZ.
  83. // ScopedAllowBlocking allow_blocking;
  84. // my_foo_->Cleanup();
  85. // }
  86. // (...)
  87. // }
  88. //
  89. // // This method can block.
  90. // void Foo::Cleanup() {
  91. // // Do NOT add the ScopedAllowBlocking in Cleanup() directly as that hides
  92. // // its blocking nature from unknowing callers and defeats the purpose of
  93. // // these checks.
  94. // FlushStateToDisk();
  95. // }
  96. //
  97. // Note: In rare situations where the blocking call is an implementation detail
  98. // (i.e. the impl makes a call that invokes AssertBlockingAllowed() but it
  99. // somehow knows that in practice this will not block), it might be okay to hide
  100. // the ScopedAllowBlocking instance in the impl with a comment explaining why
  101. // that's okay.
  102. class BrowserProcessImpl;
  103. class ChromeNSSCryptoModuleDelegate;
  104. class KeyStorageLinux;
  105. class NativeBackendKWallet;
  106. class NativeDesktopMediaList;
  107. class Profile;
  108. class StartupTabProviderImpl;
  109. class GaiaConfig;
  110. class WebEngineBrowserMainParts;
  111. Profile* GetLastProfileMac();
  112. namespace android_webview {
  113. class AwFormDatabaseService;
  114. class CookieManager;
  115. class ScopedAllowInitGLBindings;
  116. class VizCompositorThreadRunnerWebView;
  117. } // namespace android_webview
  118. namespace ash {
  119. class MojoUtils;
  120. class BrowserDataMigrator;
  121. bool CameraAppUIShouldEnableLocalOverride(const std::string&);
  122. } // namespace ash
  123. namespace audio {
  124. class OutputDevice;
  125. }
  126. namespace blink {
  127. class CategorizedWorkerPool;
  128. class DiskDataAllocator;
  129. class IdentifiabilityActiveSampler;
  130. class RTCVideoDecoderAdapter;
  131. class RTCVideoEncoder;
  132. class SourceStream;
  133. class VideoFrameResourceProvider;
  134. class WebRtcVideoFrameAdapter;
  135. class LegacyWebRtcVideoFrameAdapter;
  136. class WorkerThread;
  137. namespace scheduler {
  138. class NonMainThreadImpl;
  139. }
  140. } // namespace blink
  141. namespace cc {
  142. class CompletionEvent;
  143. class TileTaskManagerImpl;
  144. } // namespace cc
  145. namespace chromecast {
  146. class CrashUtil;
  147. }
  148. namespace chromeos {
  149. class BlockingMethodCaller;
  150. namespace system {
  151. class StatisticsProviderImpl;
  152. bool IsCoreSchedulingAvailable();
  153. int NumberOfPhysicalCores();
  154. } // namespace system
  155. } // namespace chromeos
  156. namespace chrome_cleaner {
  157. class ResetShortcutsComponent;
  158. class SystemReportComponent;
  159. } // namespace chrome_cleaner
  160. namespace content {
  161. class BrowserGpuChannelHostFactory;
  162. class BrowserMainLoop;
  163. class BrowserProcessIOThread;
  164. class BrowserTestBase;
  165. class DesktopCaptureDevice;
  166. class DWriteFontCollectionProxy;
  167. class DWriteFontProxyImpl;
  168. class EmergencyTraceFinalisationCoordinator;
  169. class InProcessUtilityThread;
  170. class NestedMessagePumpAndroid;
  171. class NetworkServiceInstancePrivate;
  172. class PepperPrintSettingsManagerImpl;
  173. class RenderProcessHostImpl;
  174. class RenderProcessHost;
  175. class RenderWidgetHostViewMac;
  176. class RendererBlinkPlatformImpl;
  177. class RTCVideoDecoder;
  178. class SandboxHostLinux;
  179. class ScopedAllowWaitForDebugURL;
  180. class ServiceWorkerContextClient;
  181. class ShellPathProvider;
  182. class SynchronousCompositor;
  183. class SynchronousCompositorHost;
  184. class SynchronousCompositorSyncCallBridge;
  185. class TextInputClientMac;
  186. class WebContentsImpl;
  187. class WebContentsViewMac;
  188. } // namespace content
  189. namespace cronet {
  190. class CronetPrefsManager;
  191. class CronetContext;
  192. } // namespace cronet
  193. namespace crosapi {
  194. class LacrosThreadTypeDelegate;
  195. } // namespace crosapi
  196. namespace dbus {
  197. class Bus;
  198. }
  199. namespace device {
  200. class UsbContext;
  201. }
  202. namespace base {
  203. class FilePath;
  204. }
  205. namespace disk_cache {
  206. class BackendImpl;
  207. class InFlightIO;
  208. bool CleanupDirectorySync(const base::FilePath&);
  209. } // namespace disk_cache
  210. namespace enterprise_connectors {
  211. class LinuxKeyRotationCommand;
  212. } // namespace enterprise_connectors
  213. namespace functions {
  214. class ExecScriptScopedAllowBaseSyncPrimitives;
  215. }
  216. namespace history_report {
  217. class HistoryReportJniBridge;
  218. }
  219. namespace ios_web_view {
  220. class WebViewBrowserState;
  221. }
  222. namespace leveldb::port {
  223. class ScopedAllowWait;
  224. } // namespace leveldb::port
  225. namespace location::nearby::chrome {
  226. class ScheduledExecutor;
  227. class SubmittableExecutor;
  228. } // namespace location::nearby::chrome
  229. namespace media {
  230. class AudioInputDevice;
  231. class AudioOutputDevice;
  232. class BlockingUrlProtocol;
  233. class FileVideoCaptureDeviceFactory;
  234. class PaintCanvasVideoRenderer;
  235. } // namespace media
  236. namespace memory_instrumentation {
  237. class OSMetrics;
  238. }
  239. namespace metrics {
  240. class AndroidMetricsServiceClient;
  241. class CleanExitBeacon;
  242. } // namespace metrics
  243. namespace midi {
  244. class TaskService; // https://crbug.com/796830
  245. }
  246. namespace module_installer {
  247. class ScopedAllowModulePakLoad;
  248. }
  249. namespace mojo {
  250. class CoreLibraryInitializer;
  251. class SyncCallRestrictions;
  252. namespace core {
  253. class ScopedIPCSupport;
  254. }
  255. } // namespace mojo
  256. namespace printing {
  257. class LocalPrinterHandlerDefault;
  258. #if BUILDFLAG(IS_MAC)
  259. class PrintBackendServiceImpl;
  260. #endif
  261. class PrintBackendServiceManager;
  262. class PrintJobWorker;
  263. class PrinterQuery;
  264. } // namespace printing
  265. namespace rlz_lib {
  266. class FinancialPing;
  267. }
  268. namespace storage {
  269. class ObfuscatedFileUtil;
  270. }
  271. namespace syncer {
  272. class GetLocalChangesRequest;
  273. class HttpBridge;
  274. } // namespace syncer
  275. namespace ui {
  276. class DrmThreadProxy;
  277. }
  278. namespace value_store {
  279. class LeveldbValueStore;
  280. }
  281. namespace weblayer {
  282. class BrowserContextImpl;
  283. class ContentBrowserClientImpl;
  284. class ProfileImpl;
  285. class WebLayerPathProvider;
  286. } // namespace weblayer
  287. namespace net {
  288. class MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
  289. class MultiThreadedProxyResolverScopedAllowJoinOnIO;
  290. class NetworkChangeNotifierMac;
  291. class NetworkConfigWatcherMacThread;
  292. namespace internal {
  293. class AddressTrackerLinux;
  294. }
  295. } // namespace net
  296. namespace proxy_resolver {
  297. class ScopedAllowThreadJoinForProxyResolverV8Tracing;
  298. }
  299. namespace remote_cocoa {
  300. class DroppedScreenShotCopierMac;
  301. } // namespace remote_cocoa
  302. namespace remoting {
  303. class AutoThread;
  304. class ScopedBypassIOThreadRestrictions;
  305. namespace protocol {
  306. class ScopedAllowSyncPrimitivesForWebRtcTransport;
  307. class ScopedAllowThreadJoinForWebRtcTransport;
  308. } // namespace protocol
  309. } // namespace remoting
  310. namespace service_manager {
  311. class ServiceProcessLauncher;
  312. }
  313. namespace shell_integration_linux {
  314. class LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
  315. }
  316. namespace ui {
  317. class WindowResizeHelperMac;
  318. }
  319. namespace viz {
  320. class HostGpuMemoryBufferManager;
  321. }
  322. namespace vr {
  323. class VrShell;
  324. }
  325. namespace web {
  326. class WebMainLoop;
  327. class WebSubThread;
  328. } // namespace web
  329. namespace webrtc {
  330. class DesktopConfigurationMonitor;
  331. }
  332. namespace base {
  333. class Environment;
  334. }
  335. bool HasWaylandDisplay(base::Environment* env);
  336. namespace base {
  337. namespace sequence_manager::internal {
  338. class TaskQueueImpl;
  339. } // namespace sequence_manager::internal
  340. namespace android {
  341. class JavaHandlerThread;
  342. }
  343. namespace internal {
  344. class GetAppOutputScopedAllowBaseSyncPrimitives;
  345. class JobTaskSource;
  346. class TaskTracker;
  347. } // namespace internal
  348. class AdjustOOMScoreHelper;
  349. class FileDescriptorWatcher;
  350. class FilePath;
  351. class ScopedAllowThreadRecallForStackSamplingProfiler;
  352. class StackSamplingProfiler;
  353. class TestCustomDisallow;
  354. class SimpleThread;
  355. class Thread;
  356. class BooleanWithStack;
  357. bool PathProviderWin(int, FilePath*);
  358. #if DCHECK_IS_ON()
  359. // NOT_TAIL_CALLED if dcheck-is-on so it's always evident who irrevocably
  360. // altered the allowance (dcheck-builds will provide the setter's stack on
  361. // assertion) or who made a failing Assert*() call.
  362. #define INLINE_OR_NOT_TAIL_CALLED BASE_EXPORT NOT_TAIL_CALLED
  363. #define EMPTY_BODY_IF_DCHECK_IS_OFF
  364. #else
  365. // inline if dcheck-is-off so it's no overhead
  366. #define INLINE_OR_NOT_TAIL_CALLED inline
  367. // The static_assert() eats follow-on semicolons. `= default` would work
  368. // too, but it makes clang realize that all the Scoped classes are no-ops in
  369. // non-dcheck builds and it starts emitting many -Wunused-variable warnings.
  370. #define EMPTY_BODY_IF_DCHECK_IS_OFF \
  371. {} \
  372. static_assert(true, "")
  373. #endif // DCHECK_IS_ON()
  374. namespace internal {
  375. // Asserts that blocking calls are allowed in the current scope. This is an
  376. // internal call, external code should use ScopedBlockingCall instead, which
  377. // serves as a precise annotation of the scope that may/will block.
  378. INLINE_OR_NOT_TAIL_CALLED void AssertBlockingAllowed()
  379. EMPTY_BODY_IF_DCHECK_IS_OFF;
  380. INLINE_OR_NOT_TAIL_CALLED void AssertBlockingDisallowedForTesting()
  381. EMPTY_BODY_IF_DCHECK_IS_OFF;
  382. } // namespace internal
  383. // Disallows blocking on the current thread.
  384. INLINE_OR_NOT_TAIL_CALLED void DisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  385. // Disallows blocking calls within its scope.
  386. class BASE_EXPORT ScopedDisallowBlocking {
  387. public:
  388. ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  389. ScopedDisallowBlocking(const ScopedDisallowBlocking&) = delete;
  390. ScopedDisallowBlocking& operator=(const ScopedDisallowBlocking&) = delete;
  391. ~ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  392. private:
  393. #if DCHECK_IS_ON()
  394. std::unique_ptr<BooleanWithStack> was_disallowed_;
  395. #endif
  396. };
  397. class BASE_EXPORT ScopedAllowBlocking {
  398. public:
  399. ScopedAllowBlocking(const ScopedAllowBlocking&) = delete;
  400. ScopedAllowBlocking& operator=(const ScopedAllowBlocking&) = delete;
  401. private:
  402. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  403. NestedAllowRestoresPreviousStack);
  404. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest, ScopedAllowBlocking);
  405. friend class ScopedAllowBlockingForTesting;
  406. // This can only be instantiated by friends. Use ScopedAllowBlockingForTesting
  407. // in unit tests to avoid the friend requirement.
  408. friend class ::GaiaConfig;
  409. friend class ::StartupTabProviderImpl;
  410. friend class android_webview::ScopedAllowInitGLBindings;
  411. friend class ash::MojoUtils; // http://crbug.com/1055467
  412. friend class ash::BrowserDataMigrator;
  413. friend class base::AdjustOOMScoreHelper;
  414. friend class base::StackSamplingProfiler;
  415. friend class blink::DiskDataAllocator;
  416. friend class chromecast::CrashUtil;
  417. friend class content::BrowserProcessIOThread;
  418. friend class content::DWriteFontProxyImpl;
  419. friend class content::NetworkServiceInstancePrivate;
  420. friend class content::PepperPrintSettingsManagerImpl;
  421. friend class content::RenderProcessHostImpl;
  422. friend class content::RenderWidgetHostViewMac; // http://crbug.com/121917
  423. friend class content::ShellPathProvider;
  424. #if BUILDFLAG(IS_WIN)
  425. friend class content::WebContentsImpl; // http://crbug.com/1262162
  426. #endif
  427. friend class content::WebContentsViewMac;
  428. friend class cronet::CronetPrefsManager;
  429. friend class cronet::CronetContext;
  430. friend class crosapi::LacrosThreadTypeDelegate;
  431. friend class ios_web_view::WebViewBrowserState;
  432. friend class media::FileVideoCaptureDeviceFactory;
  433. friend class memory_instrumentation::OSMetrics;
  434. friend class metrics::AndroidMetricsServiceClient;
  435. friend class metrics::CleanExitBeacon;
  436. friend class module_installer::ScopedAllowModulePakLoad;
  437. friend class mojo::CoreLibraryInitializer;
  438. friend class printing::LocalPrinterHandlerDefault;
  439. #if BUILDFLAG(IS_MAC)
  440. friend class printing::PrintBackendServiceImpl;
  441. #endif
  442. friend class printing::PrintBackendServiceManager;
  443. friend class printing::PrintJobWorker;
  444. friend class remote_cocoa::
  445. DroppedScreenShotCopierMac; // https://crbug.com/1148078
  446. friend class remoting::ScopedBypassIOThreadRestrictions; // crbug.com/1144161
  447. friend class web::WebSubThread;
  448. friend class ::WebEngineBrowserMainParts;
  449. friend class weblayer::BrowserContextImpl;
  450. friend class weblayer::ContentBrowserClientImpl;
  451. friend class weblayer::ProfileImpl;
  452. friend class weblayer::WebLayerPathProvider;
  453. // Sorting with function name (with namespace), ignoring the return type.
  454. friend Profile* ::GetLastProfileMac(); // crbug.com/1176734
  455. friend bool ::HasWaylandDisplay(base::Environment* env); // crbug.com/1246928
  456. friend bool PathProviderWin(int, FilePath*);
  457. friend bool ash::CameraAppUIShouldEnableLocalOverride(const std::string&);
  458. friend bool chromeos::system::IsCoreSchedulingAvailable();
  459. friend int chromeos::system::NumberOfPhysicalCores();
  460. friend bool disk_cache::CleanupDirectorySync(const base::FilePath&);
  461. ScopedAllowBlocking(const Location& from_here = Location::Current());
  462. ~ScopedAllowBlocking();
  463. #if DCHECK_IS_ON()
  464. std::unique_ptr<BooleanWithStack> was_disallowed_;
  465. #endif
  466. };
  467. class ScopedAllowBlockingForTesting {
  468. public:
  469. ScopedAllowBlockingForTesting() {}
  470. ScopedAllowBlockingForTesting(const ScopedAllowBlockingForTesting&) = delete;
  471. ScopedAllowBlockingForTesting& operator=(
  472. const ScopedAllowBlockingForTesting&) = delete;
  473. ~ScopedAllowBlockingForTesting() {}
  474. private:
  475. #if DCHECK_IS_ON()
  476. ScopedAllowBlocking scoped_allow_blocking_;
  477. #endif
  478. };
  479. INLINE_OR_NOT_TAIL_CALLED void DisallowBaseSyncPrimitives()
  480. EMPTY_BODY_IF_DCHECK_IS_OFF;
  481. // Disallows singletons within its scope.
  482. class BASE_EXPORT ScopedDisallowBaseSyncPrimitives {
  483. public:
  484. ScopedDisallowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  485. ScopedDisallowBaseSyncPrimitives(const ScopedDisallowBaseSyncPrimitives&) =
  486. delete;
  487. ScopedDisallowBaseSyncPrimitives& operator=(
  488. const ScopedDisallowBaseSyncPrimitives&) = delete;
  489. ~ScopedDisallowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  490. private:
  491. #if DCHECK_IS_ON()
  492. std::unique_ptr<BooleanWithStack> was_disallowed_;
  493. #endif
  494. };
  495. class BASE_EXPORT ScopedAllowBaseSyncPrimitives {
  496. public:
  497. ScopedAllowBaseSyncPrimitives(const ScopedAllowBaseSyncPrimitives&) = delete;
  498. ScopedAllowBaseSyncPrimitives& operator=(
  499. const ScopedAllowBaseSyncPrimitives&) = delete;
  500. private:
  501. // This can only be instantiated by friends. Use
  502. // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
  503. // requirement.
  504. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  505. ScopedAllowBaseSyncPrimitives);
  506. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  507. ScopedAllowBaseSyncPrimitivesResetsState);
  508. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  509. ScopedAllowBaseSyncPrimitivesWithBlockingDisallowed);
  510. // Allowed usage:
  511. friend class ::ChromeNSSCryptoModuleDelegate;
  512. friend class base::internal::GetAppOutputScopedAllowBaseSyncPrimitives;
  513. friend class base::SimpleThread;
  514. friend class blink::IdentifiabilityActiveSampler;
  515. friend class blink::SourceStream;
  516. friend class blink::WorkerThread;
  517. friend class blink::scheduler::NonMainThreadImpl;
  518. friend class chrome_cleaner::ResetShortcutsComponent;
  519. friend class chrome_cleaner::SystemReportComponent;
  520. friend class content::BrowserMainLoop;
  521. friend class content::BrowserProcessIOThread;
  522. friend class content::RendererBlinkPlatformImpl;
  523. friend class content::DWriteFontCollectionProxy;
  524. friend class content::ServiceWorkerContextClient;
  525. friend class device::UsbContext;
  526. friend class enterprise_connectors::LinuxKeyRotationCommand;
  527. friend class functions::ExecScriptScopedAllowBaseSyncPrimitives;
  528. friend class history_report::HistoryReportJniBridge;
  529. friend class internal::TaskTracker;
  530. friend class leveldb::port::ScopedAllowWait;
  531. friend class location::nearby::chrome::ScheduledExecutor;
  532. friend class location::nearby::chrome::SubmittableExecutor;
  533. friend class media::BlockingUrlProtocol;
  534. friend class mojo::core::ScopedIPCSupport;
  535. friend class net::MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
  536. friend class rlz_lib::FinancialPing;
  537. friend class shell_integration_linux::
  538. LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
  539. friend class storage::ObfuscatedFileUtil;
  540. friend class syncer::HttpBridge;
  541. friend class syncer::GetLocalChangesRequest;
  542. friend class webrtc::DesktopConfigurationMonitor;
  543. // Usage that should be fixed:
  544. friend class ::NativeBackendKWallet; // http://crbug.com/125331
  545. friend class ::chromeos::system::
  546. StatisticsProviderImpl; // http://crbug.com/125385
  547. friend class blink::VideoFrameResourceProvider; // http://crbug.com/878070
  548. friend class value_store::LeveldbValueStore; // http://crbug.com/1330845
  549. ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  550. ~ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  551. #if DCHECK_IS_ON()
  552. std::unique_ptr<BooleanWithStack> was_disallowed_;
  553. #endif
  554. };
  555. class BASE_EXPORT ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {
  556. public:
  557. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope(
  558. const ScopedAllowBaseSyncPrimitivesOutsideBlockingScope&) = delete;
  559. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope& operator=(
  560. const ScopedAllowBaseSyncPrimitivesOutsideBlockingScope&) = delete;
  561. private:
  562. // This can only be instantiated by friends. Use
  563. // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
  564. // requirement.
  565. FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
  566. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope);
  567. FRIEND_TEST_ALL_PREFIXES(
  568. ThreadRestrictionsTest,
  569. ScopedAllowBaseSyncPrimitivesOutsideBlockingScopeResetsState);
  570. // Allowed usage:
  571. friend class ::BrowserProcessImpl; // http://crbug.com/125207
  572. friend class ::KeyStorageLinux;
  573. friend class ::NativeDesktopMediaList;
  574. friend class android::JavaHandlerThread;
  575. friend class android_webview::
  576. AwFormDatabaseService; // http://crbug.com/904431
  577. friend class android_webview::CookieManager;
  578. friend class android_webview::VizCompositorThreadRunnerWebView;
  579. friend class audio::OutputDevice;
  580. friend class base::sequence_manager::internal::TaskQueueImpl;
  581. friend class base::FileDescriptorWatcher;
  582. friend class base::internal::JobTaskSource;
  583. friend class base::ScopedAllowThreadRecallForStackSamplingProfiler;
  584. friend class base::StackSamplingProfiler;
  585. friend class blink::CategorizedWorkerPool;
  586. friend class blink::RTCVideoDecoderAdapter;
  587. friend class blink::RTCVideoEncoder;
  588. friend class blink::WebRtcVideoFrameAdapter;
  589. friend class blink::LegacyWebRtcVideoFrameAdapter;
  590. friend class cc::TileTaskManagerImpl;
  591. friend class content::DesktopCaptureDevice;
  592. friend class content::EmergencyTraceFinalisationCoordinator;
  593. friend class content::InProcessUtilityThread;
  594. friend class content::RTCVideoDecoder;
  595. friend class content::SandboxHostLinux;
  596. friend class content::ScopedAllowWaitForDebugURL;
  597. friend class content::SynchronousCompositor;
  598. friend class content::SynchronousCompositorHost;
  599. friend class content::SynchronousCompositorSyncCallBridge;
  600. friend class content::RenderProcessHost;
  601. friend class media::AudioInputDevice;
  602. friend class media::AudioOutputDevice;
  603. friend class media::PaintCanvasVideoRenderer;
  604. friend class mojo::SyncCallRestrictions;
  605. friend class net::NetworkConfigWatcherMacThread;
  606. friend class ui::DrmThreadProxy;
  607. friend class viz::HostGpuMemoryBufferManager;
  608. friend class vr::VrShell;
  609. // Usage that should be fixed:
  610. friend class ::chromeos::BlockingMethodCaller; // http://crbug.com/125360
  611. friend class base::Thread; // http://crbug.com/918039
  612. friend class cc::CompletionEvent; // http://crbug.com/902653
  613. friend class content::
  614. BrowserGpuChannelHostFactory; // http://crbug.com/125248
  615. friend class dbus::Bus; // http://crbug.com/125222
  616. friend class disk_cache::BackendImpl; // http://crbug.com/74623
  617. friend class disk_cache::InFlightIO; // http://crbug.com/74623
  618. friend class midi::TaskService; // https://crbug.com/796830
  619. friend class net::internal::AddressTrackerLinux; // http://crbug.com/125097
  620. friend class net::
  621. MultiThreadedProxyResolverScopedAllowJoinOnIO; // http://crbug.com/69710
  622. friend class net::NetworkChangeNotifierMac; // http://crbug.com/125097
  623. friend class printing::PrinterQuery; // http://crbug.com/66082
  624. friend class proxy_resolver::
  625. ScopedAllowThreadJoinForProxyResolverV8Tracing; // http://crbug.com/69710
  626. friend class remoting::AutoThread; // https://crbug.com/944316
  627. friend class remoting::protocol::
  628. ScopedAllowSyncPrimitivesForWebRtcTransport; // http://crbug.com/1198501
  629. friend class remoting::protocol::
  630. ScopedAllowThreadJoinForWebRtcTransport; // http://crbug.com/660081
  631. // Not used in production yet, https://crbug.com/844078.
  632. friend class service_manager::ServiceProcessLauncher;
  633. friend class ui::WindowResizeHelperMac; // http://crbug.com/902829
  634. friend class content::TextInputClientMac; // http://crbug.com/121917
  635. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope(
  636. const Location& from_here = Location::Current());
  637. ~ScopedAllowBaseSyncPrimitivesOutsideBlockingScope();
  638. #if DCHECK_IS_ON()
  639. std::unique_ptr<BooleanWithStack> was_disallowed_;
  640. #endif
  641. };
  642. // Allow base-sync-primitives in tests, doesn't require explicit friend'ing like
  643. // ScopedAllowBaseSyncPrimitives-types aimed at production do.
  644. // Note: For WaitableEvents in the test logic, base::TestWaitableEvent is
  645. // exposed as a convenience to avoid the need for
  646. // ScopedAllowBaseSyncPrimitivesForTesting.
  647. class BASE_EXPORT ScopedAllowBaseSyncPrimitivesForTesting {
  648. public:
  649. ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  650. ScopedAllowBaseSyncPrimitivesForTesting(
  651. const ScopedAllowBaseSyncPrimitivesForTesting&) = delete;
  652. ScopedAllowBaseSyncPrimitivesForTesting& operator=(
  653. const ScopedAllowBaseSyncPrimitivesForTesting&) = delete;
  654. ~ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  655. private:
  656. #if DCHECK_IS_ON()
  657. std::unique_ptr<BooleanWithStack> was_disallowed_;
  658. #endif
  659. };
  660. // Counterpart to base::DisallowUnresponsiveTasks() for tests to allow them to
  661. // block their thread after it was banned.
  662. class BASE_EXPORT ScopedAllowUnresponsiveTasksForTesting {
  663. public:
  664. ScopedAllowUnresponsiveTasksForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  665. ScopedAllowUnresponsiveTasksForTesting(
  666. const ScopedAllowUnresponsiveTasksForTesting&) = delete;
  667. ScopedAllowUnresponsiveTasksForTesting& operator=(
  668. const ScopedAllowUnresponsiveTasksForTesting&) = delete;
  669. ~ScopedAllowUnresponsiveTasksForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
  670. private:
  671. #if DCHECK_IS_ON()
  672. std::unique_ptr<BooleanWithStack> was_disallowed_base_sync_;
  673. std::unique_ptr<BooleanWithStack> was_disallowed_blocking_;
  674. std::unique_ptr<BooleanWithStack> was_disallowed_cpu_;
  675. #endif
  676. };
  677. namespace internal {
  678. // Asserts that waiting on a //base sync primitive is allowed in the current
  679. // scope.
  680. INLINE_OR_NOT_TAIL_CALLED void AssertBaseSyncPrimitivesAllowed()
  681. EMPTY_BODY_IF_DCHECK_IS_OFF;
  682. // Resets all thread restrictions on the current thread.
  683. INLINE_OR_NOT_TAIL_CALLED void ResetThreadRestrictionsForTesting()
  684. EMPTY_BODY_IF_DCHECK_IS_OFF;
  685. // Check whether the current thread is allowed to use singletons (Singleton /
  686. // LazyInstance). DCHECKs if not.
  687. INLINE_OR_NOT_TAIL_CALLED void AssertSingletonAllowed()
  688. EMPTY_BODY_IF_DCHECK_IS_OFF;
  689. } // namespace internal
  690. // Disallow using singleton on the current thread.
  691. INLINE_OR_NOT_TAIL_CALLED void DisallowSingleton() EMPTY_BODY_IF_DCHECK_IS_OFF;
  692. // Disallows singletons within its scope.
  693. class BASE_EXPORT ScopedDisallowSingleton {
  694. public:
  695. ScopedDisallowSingleton() EMPTY_BODY_IF_DCHECK_IS_OFF;
  696. ScopedDisallowSingleton(const ScopedDisallowSingleton&) = delete;
  697. ScopedDisallowSingleton& operator=(const ScopedDisallowSingleton&) = delete;
  698. ~ScopedDisallowSingleton() EMPTY_BODY_IF_DCHECK_IS_OFF;
  699. private:
  700. #if DCHECK_IS_ON()
  701. std::unique_ptr<BooleanWithStack> was_disallowed_;
  702. #endif
  703. };
  704. // Asserts that running long CPU work is allowed in the current scope.
  705. INLINE_OR_NOT_TAIL_CALLED void AssertLongCPUWorkAllowed()
  706. EMPTY_BODY_IF_DCHECK_IS_OFF;
  707. INLINE_OR_NOT_TAIL_CALLED void DisallowUnresponsiveTasks()
  708. EMPTY_BODY_IF_DCHECK_IS_OFF;
  709. class BASE_EXPORT ThreadRestrictions {
  710. public:
  711. ThreadRestrictions() = delete;
  712. // Constructing a ScopedAllowIO temporarily allows IO for the current
  713. // thread. Doing this is almost certainly always incorrect.
  714. //
  715. // DEPRECATED. Use ScopedAllowBlocking(ForTesting).
  716. // TODO(crbug.com/766678): Migrate remaining users.
  717. class BASE_EXPORT ScopedAllowIO {
  718. public:
  719. ScopedAllowIO(const Location& from_here = Location::Current());
  720. ScopedAllowIO(const ScopedAllowIO&) = delete;
  721. ScopedAllowIO& operator=(const ScopedAllowIO&) = delete;
  722. ~ScopedAllowIO();
  723. private:
  724. #if DCHECK_IS_ON()
  725. std::unique_ptr<BooleanWithStack> was_disallowed_;
  726. #endif
  727. };
  728. };
  729. // Friend-only methods to permanently allow the current thread to use
  730. // blocking/sync-primitives calls. Threads start out in the *allowed* state but
  731. // are typically *disallowed* via the above base::Disallow*() methods after
  732. // being initialized.
  733. //
  734. // Only use these to permanently set the allowance on a thread, e.g. on
  735. // shutdown. For temporary allowances, use scopers above.
  736. class BASE_EXPORT PermanentThreadAllowance {
  737. public:
  738. // Class is merely a namespace-with-friends.
  739. PermanentThreadAllowance() = delete;
  740. private:
  741. friend class base::TestCustomDisallow;
  742. friend class content::BrowserMainLoop;
  743. friend class content::BrowserTestBase;
  744. friend class web::WebMainLoop;
  745. static void AllowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
  746. static void AllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
  747. };
  748. // Similar to PermanentThreadAllowance but separate because it's dangerous and
  749. // should have even fewer friends.
  750. class BASE_EXPORT PermanentSingletonAllowance {
  751. public:
  752. // Class is merely a namespace-with-friends.
  753. PermanentSingletonAllowance() = delete;
  754. private:
  755. // Re-allow singletons on this thread. Since //base APIs DisallowSingleton()
  756. // when they risk running past shutdown, this should only be called in rare
  757. // cases where the caller knows the process will be killed rather than
  758. // shutdown.
  759. static void AllowSingleton() EMPTY_BODY_IF_DCHECK_IS_OFF;
  760. };
  761. #undef INLINE_OR_NOT_TAIL_CALLED
  762. #undef EMPTY_BODY_IF_DCHECK_IS_OFF
  763. } // namespace base
  764. #endif // BASE_THREADING_THREAD_RESTRICTIONS_H_