electron_main_delegate.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/app/electron_main_delegate.h"
  5. #include <iostream>
  6. #include <memory>
  7. #include <string>
  8. #include <string_view>
  9. #include <utility>
  10. #include "base/apple/bundle_locations.h"
  11. #include "base/base_switches.h"
  12. #include "base/command_line.h"
  13. #include "base/debug/stack_trace.h"
  14. #include "base/environment.h"
  15. #include "base/files/file_util.h"
  16. #include "base/logging.h"
  17. #include "base/path_service.h"
  18. #include "chrome/common/chrome_paths.h"
  19. #include "chrome/common/chrome_switches.h"
  20. #include "components/content_settings/core/common/content_settings_pattern.h"
  21. #include "content/public/app/initialize_mojo_core.h"
  22. #include "content/public/common/content_switches.h"
  23. #include "electron/buildflags/buildflags.h"
  24. #include "electron/fuses.h"
  25. #include "extensions/common/constants.h"
  26. #include "ipc/ipc_buildflags.h"
  27. #include "sandbox/policy/switches.h"
  28. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
  29. #include "shell/app/command_line_args.h"
  30. #include "shell/app/electron_content_client.h"
  31. #include "shell/browser/electron_browser_client.h"
  32. #include "shell/browser/electron_gpu_client.h"
  33. #include "shell/browser/feature_list.h"
  34. #include "shell/browser/relauncher.h"
  35. #include "shell/common/application_info.h"
  36. #include "shell/common/electron_paths.h"
  37. #include "shell/common/logging.h"
  38. #include "shell/common/options_switches.h"
  39. #include "shell/common/platform_util.h"
  40. #include "shell/common/process_util.h"
  41. #include "shell/common/thread_restrictions.h"
  42. #include "shell/renderer/electron_renderer_client.h"
  43. #include "shell/renderer/electron_sandboxed_renderer_client.h"
  44. #include "shell/utility/electron_content_utility_client.h"
  45. #include "third_party/abseil-cpp/absl/types/variant.h"
  46. #include "ui/base/resource/resource_bundle.h"
  47. #include "ui/base/ui_base_switches.h"
  48. #if BUILDFLAG(IS_MAC)
  49. #include "shell/app/electron_main_delegate_mac.h"
  50. #endif
  51. #if BUILDFLAG(IS_WIN)
  52. #include "base/win/win_util.h"
  53. #include "chrome/child/v8_crashpad_support_win.h"
  54. #endif
  55. #if BUILDFLAG(IS_LINUX)
  56. #include "base/nix/xdg_util.h"
  57. #include "v8/include/v8-wasm-trap-handler-posix.h"
  58. #include "v8/include/v8.h"
  59. #endif
  60. #if !IS_MAS_BUILD()
  61. #include "components/crash/core/app/crash_switches.h" // nogncheck
  62. #include "components/crash/core/app/crashpad.h" // nogncheck
  63. #include "components/crash/core/common/crash_key.h"
  64. #include "components/crash/core/common/crash_keys.h"
  65. #include "shell/app/electron_crash_reporter_client.h"
  66. #include "shell/browser/api/electron_api_crash_reporter.h"
  67. #include "shell/common/crash_keys.h"
  68. #endif
  69. namespace electron {
  70. namespace {
  71. const char kRelauncherProcess[] = "relauncher";
  72. constexpr std::string_view kElectronDisableSandbox{"ELECTRON_DISABLE_SANDBOX"};
  73. constexpr std::string_view kElectronEnableStackDumping{
  74. "ELECTRON_ENABLE_STACK_DUMPING"};
  75. // Returns true if this subprocess type needs the ResourceBundle initialized
  76. // and resources loaded.
  77. bool SubprocessNeedsResourceBundle(const std::string& process_type) {
  78. return
  79. #if BUILDFLAG(IS_LINUX)
  80. // The zygote process opens the resources for the renderers.
  81. process_type == ::switches::kZygoteProcess ||
  82. #endif
  83. #if BUILDFLAG(IS_MAC)
  84. // Mac needs them too for scrollbar related images and for sandbox
  85. // profiles.
  86. process_type == ::switches::kGpuProcess ||
  87. #endif
  88. process_type == ::switches::kRendererProcess ||
  89. process_type == ::switches::kUtilityProcess;
  90. }
  91. #if BUILDFLAG(IS_WIN)
  92. void InvalidParameterHandler(const wchar_t*,
  93. const wchar_t*,
  94. const wchar_t*,
  95. unsigned int,
  96. uintptr_t) {
  97. // noop.
  98. }
  99. #endif
  100. // TODO(nornagon): move path provider overriding to its own file in
  101. // shell/common
  102. bool ElectronPathProvider(int key, base::FilePath* result) {
  103. bool create_dir = false;
  104. base::FilePath cur;
  105. switch (key) {
  106. case chrome::DIR_USER_DATA:
  107. if (!base::PathService::Get(DIR_APP_DATA, &cur))
  108. return false;
  109. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  110. GetPossiblyOverriddenApplicationName()));
  111. create_dir = true;
  112. break;
  113. case DIR_CRASH_DUMPS:
  114. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  115. return false;
  116. cur = cur.Append(FILE_PATH_LITERAL("Crashpad"));
  117. create_dir = true;
  118. break;
  119. case chrome::DIR_APP_DICTIONARIES:
  120. // TODO(nornagon): can we just default to using Chrome's logic here?
  121. if (!base::PathService::Get(DIR_SESSION_DATA, &cur))
  122. return false;
  123. cur = cur.Append(base::FilePath::FromUTF8Unsafe("Dictionaries"));
  124. create_dir = true;
  125. break;
  126. case DIR_SESSION_DATA:
  127. // By default and for backward, equivalent to DIR_USER_DATA.
  128. return base::PathService::Get(chrome::DIR_USER_DATA, result);
  129. case DIR_USER_CACHE: {
  130. #if BUILDFLAG(IS_POSIX)
  131. int parent_key = base::DIR_CACHE;
  132. #else
  133. // On Windows, there's no OS-level centralized location for caches, so
  134. // store the cache in the app data directory.
  135. int parent_key = base::DIR_ROAMING_APP_DATA;
  136. #endif
  137. if (!base::PathService::Get(parent_key, &cur))
  138. return false;
  139. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  140. GetPossiblyOverriddenApplicationName()));
  141. create_dir = true;
  142. break;
  143. }
  144. #if BUILDFLAG(IS_LINUX)
  145. case DIR_APP_DATA: {
  146. auto env = base::Environment::Create();
  147. cur = base::nix::GetXDGDirectory(
  148. env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir);
  149. break;
  150. }
  151. #endif
  152. #if BUILDFLAG(IS_WIN)
  153. case DIR_RECENT:
  154. if (!platform_util::GetFolderPath(DIR_RECENT, &cur))
  155. return false;
  156. create_dir = true;
  157. break;
  158. #endif
  159. case DIR_APP_LOGS:
  160. #if BUILDFLAG(IS_MAC)
  161. if (!base::PathService::Get(base::DIR_HOME, &cur))
  162. return false;
  163. cur = cur.Append(FILE_PATH_LITERAL("Library"));
  164. cur = cur.Append(FILE_PATH_LITERAL("Logs"));
  165. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  166. GetPossiblyOverriddenApplicationName()));
  167. #else
  168. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  169. return false;
  170. cur = cur.Append(base::FilePath::FromUTF8Unsafe("logs"));
  171. #endif
  172. create_dir = true;
  173. break;
  174. default:
  175. return false;
  176. }
  177. // TODO(bauerb): http://crbug.com/259796
  178. ScopedAllowBlockingForElectron allow_blocking;
  179. if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur)) {
  180. return false;
  181. }
  182. *result = cur;
  183. return true;
  184. }
  185. void RegisterPathProvider() {
  186. base::PathService::RegisterProvider(ElectronPathProvider, PATH_START,
  187. PATH_END);
  188. }
  189. } // namespace
  190. std::string LoadResourceBundle(const std::string& locale) {
  191. const bool initialized = ui::ResourceBundle::HasSharedInstance();
  192. DCHECK(!initialized);
  193. // Load other resource files.
  194. base::FilePath pak_dir;
  195. #if BUILDFLAG(IS_MAC)
  196. pak_dir =
  197. base::apple::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
  198. #else
  199. base::PathService::Get(base::DIR_MODULE, &pak_dir);
  200. #endif
  201. std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
  202. locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
  203. ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  204. bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")),
  205. ui::kScaleFactorNone);
  206. return loaded_locale;
  207. }
  208. ElectronMainDelegate::ElectronMainDelegate() = default;
  209. ElectronMainDelegate::~ElectronMainDelegate() = default;
  210. const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = {
  211. extensions::kExtensionScheme};
  212. const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize =
  213. std::size(kNonWildcardDomainNonPortSchemes);
  214. std::optional<int> ElectronMainDelegate::BasicStartupComplete() {
  215. auto* command_line = base::CommandLine::ForCurrentProcess();
  216. #if BUILDFLAG(IS_WIN)
  217. v8_crashpad_support::SetUp();
  218. // On Windows the terminal returns immediately, so we add a new line to
  219. // prevent output in the same line as the prompt.
  220. if (IsBrowserProcess())
  221. std::wcout << std::endl;
  222. #endif // !BUILDFLAG(IS_WIN)
  223. auto env = base::Environment::Create();
  224. // Enable convenient stack printing. This is enabled by default in
  225. // non-official builds.
  226. if (env->HasVar(kElectronEnableStackDumping))
  227. base::debug::EnableInProcessStackDumping();
  228. if (env->HasVar(kElectronDisableSandbox))
  229. command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
  230. tracing_sampler_profiler_ =
  231. tracing::TracingSamplerProfiler::CreateOnMainThread();
  232. chrome::RegisterPathProvider();
  233. electron::RegisterPathProvider();
  234. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  235. ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes(
  236. kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize);
  237. #endif
  238. #if BUILDFLAG(IS_MAC)
  239. OverrideChildProcessPath();
  240. OverrideFrameworkBundlePath();
  241. SetUpBundleOverrides();
  242. #endif
  243. #if BUILDFLAG(IS_WIN)
  244. // Ignore invalid parameter errors.
  245. _set_invalid_parameter_handler(InvalidParameterHandler);
  246. // Disable the ActiveVerifier, which is used by Chrome to track possible
  247. // bugs, but no use in Electron.
  248. base::win::DisableHandleVerifier();
  249. if (IsBrowserProcess())
  250. base::win::PinUser32();
  251. #endif
  252. #if BUILDFLAG(IS_LINUX)
  253. // Check for --no-sandbox parameter when running as root.
  254. if (getuid() == 0 && IsSandboxEnabled(command_line))
  255. LOG(FATAL) << "Running as root without --"
  256. << sandbox::policy::switches::kNoSandbox
  257. << " is not supported. See https://crbug.com/638180.";
  258. #endif
  259. #if IS_MAS_BUILD()
  260. // In MAS build we are using --disable-remote-core-animation.
  261. //
  262. // According to ccameron:
  263. // If you're running with --disable-remote-core-animation, you may want to
  264. // also run with --disable-gpu-memory-buffer-compositor-resources as well.
  265. // That flag makes it so we use regular GL textures instead of IOSurfaces
  266. // for compositor resources. IOSurfaces are very heavyweight to
  267. // create/destroy, but they can be displayed directly by CoreAnimation (and
  268. // --disable-remote-core-animation makes it so we don't use this property,
  269. // so they're just heavyweight with no upside).
  270. command_line->AppendSwitch(
  271. ::switches::kDisableGpuMemoryBufferCompositorResources);
  272. #endif
  273. return std::nullopt;
  274. }
  275. void ElectronMainDelegate::PreSandboxStartup() {
  276. auto* command_line = base::CommandLine::ForCurrentProcess();
  277. std::string process_type = GetProcessType();
  278. base::FilePath user_data_dir =
  279. command_line->GetSwitchValuePath(::switches::kUserDataDir);
  280. if (!user_data_dir.empty()) {
  281. base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
  282. user_data_dir, false, true);
  283. }
  284. #if !BUILDFLAG(IS_WIN)
  285. // For windows we call InitLogging later, after the sandbox is initialized.
  286. //
  287. // On Linux, we force a "preinit" in the zygote (i.e. never log to a default
  288. // log file), because the zygote is booted prior to JS running, so it can't
  289. // know the correct user-data directory. (And, further, accessing the
  290. // application name on Linux can cause glib calls that end up spawning
  291. // threads, which if done before the zygote is booted, causes a CHECK().)
  292. logging::InitElectronLogging(
  293. *command_line,
  294. /* is_preinit = */ IsBrowserProcess() || IsZygoteProcess());
  295. #endif
  296. #if !IS_MAS_BUILD()
  297. crash_reporter::InitializeCrashKeys();
  298. #endif
  299. // Initialize ResourceBundle which handles files loaded from external
  300. // sources. The language should have been passed in to us from the
  301. // browser process as a command line flag.
  302. if (SubprocessNeedsResourceBundle(process_type)) {
  303. std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
  304. LoadResourceBundle(locale);
  305. }
  306. #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  307. // In the main process, we wait for JS to call crashReporter.start() before
  308. // initializing crashpad. If we're in the renderer, we want to initialize it
  309. // immediately at boot.
  310. if (!IsBrowserProcess()) {
  311. ElectronCrashReporterClient::Create();
  312. crash_reporter::InitializeCrashpad(false, process_type);
  313. }
  314. #endif
  315. #if BUILDFLAG(IS_LINUX)
  316. // Zygote needs to call InitCrashReporter() in RunZygote().
  317. if (!IsZygoteProcess() && !IsBrowserProcess()) {
  318. ElectronCrashReporterClient::Create();
  319. if (command_line->HasSwitch(
  320. crash_reporter::switches::kCrashpadHandlerPid)) {
  321. crash_reporter::InitializeCrashpad(false, process_type);
  322. crash_reporter::SetFirstChanceExceptionHandler(
  323. v8::TryHandleWebAssemblyTrapPosix);
  324. }
  325. }
  326. #endif
  327. #if !IS_MAS_BUILD()
  328. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  329. crash_keys::SetPlatformCrashKey();
  330. #endif
  331. if (IsBrowserProcess()) {
  332. // Only append arguments for browser process.
  333. // Allow file:// URIs to read other file:// URIs by default.
  334. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
  335. #if BUILDFLAG(IS_MAC)
  336. // Enable AVFoundation.
  337. command_line->AppendSwitch("enable-avfoundation");
  338. #endif
  339. }
  340. }
  341. void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) {
  342. #if BUILDFLAG(IS_WIN)
  343. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
  344. /* is_preinit = */ process_type.empty());
  345. #endif
  346. }
  347. std::optional<int> ElectronMainDelegate::PreBrowserMain() {
  348. // This is initialized early because the service manager reads some feature
  349. // flags and we need to make sure the feature list is initialized before the
  350. // service manager reads the features.
  351. InitializeFeatureList();
  352. // Initialize mojo core as soon as we have a valid feature list
  353. content::InitializeMojoCore();
  354. #if BUILDFLAG(IS_MAC)
  355. RegisterAtomCrApp();
  356. #endif
  357. return std::nullopt;
  358. }
  359. std::string_view ElectronMainDelegate::GetBrowserV8SnapshotFilename() {
  360. bool load_browser_process_specific_v8_snapshot =
  361. IsBrowserProcess() &&
  362. electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled();
  363. if (load_browser_process_specific_v8_snapshot) {
  364. return "browser_v8_context_snapshot.bin";
  365. }
  366. return ContentMainDelegate::GetBrowserV8SnapshotFilename();
  367. }
  368. content::ContentClient* ElectronMainDelegate::CreateContentClient() {
  369. content_client_ = std::make_unique<ElectronContentClient>();
  370. return content_client_.get();
  371. }
  372. content::ContentBrowserClient*
  373. ElectronMainDelegate::CreateContentBrowserClient() {
  374. browser_client_ = std::make_unique<ElectronBrowserClient>();
  375. return browser_client_.get();
  376. }
  377. content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() {
  378. gpu_client_ = std::make_unique<ElectronGpuClient>();
  379. return gpu_client_.get();
  380. }
  381. content::ContentRendererClient*
  382. ElectronMainDelegate::CreateContentRendererClient() {
  383. auto* command_line = base::CommandLine::ForCurrentProcess();
  384. if (IsSandboxEnabled(command_line)) {
  385. renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
  386. } else {
  387. renderer_client_ = std::make_unique<ElectronRendererClient>();
  388. }
  389. return renderer_client_.get();
  390. }
  391. content::ContentUtilityClient*
  392. ElectronMainDelegate::CreateContentUtilityClient() {
  393. utility_client_ = std::make_unique<ElectronContentUtilityClient>();
  394. return utility_client_.get();
  395. }
  396. absl::variant<int, content::MainFunctionParams>
  397. ElectronMainDelegate::RunProcess(
  398. const std::string& process_type,
  399. content::MainFunctionParams main_function_params) {
  400. if (process_type == kRelauncherProcess)
  401. return relauncher::RelauncherMain(main_function_params);
  402. else
  403. return std::move(main_function_params);
  404. }
  405. bool ElectronMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) {
  406. return absl::holds_alternative<InvokedInChildProcess>(invoked_in);
  407. }
  408. bool ElectronMainDelegate::ShouldInitializeMojo(InvokedIn invoked_in) {
  409. return ShouldCreateFeatureList(invoked_in);
  410. }
  411. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  412. return false;
  413. }
  414. #if BUILDFLAG(IS_LINUX)
  415. void ElectronMainDelegate::ZygoteForked() {
  416. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  417. // this up for the browser process in a different manner.
  418. ElectronCrashReporterClient::Create();
  419. const base::CommandLine* command_line =
  420. base::CommandLine::ForCurrentProcess();
  421. std::string process_type =
  422. command_line->GetSwitchValueASCII(::switches::kProcessType);
  423. if (command_line->HasSwitch(crash_reporter::switches::kCrashpadHandlerPid)) {
  424. crash_reporter::InitializeCrashpad(false, process_type);
  425. crash_reporter::SetFirstChanceExceptionHandler(
  426. v8::TryHandleWebAssemblyTrapPosix);
  427. }
  428. // Reset the command line for the newly spawned process.
  429. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  430. }
  431. #endif // BUILDFLAG(IS_LINUX)
  432. } // namespace electron