electron_main_delegate.cc 17 KB

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