electron_main_delegate.cc 17 KB

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