electron_main_delegate.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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/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::mac::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 =
  279. command_line->GetSwitchValueASCII(::switches::kProcessType);
  280. base::FilePath user_data_dir =
  281. command_line->GetSwitchValuePath(::switches::kUserDataDir);
  282. if (!user_data_dir.empty()) {
  283. base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
  284. user_data_dir, false, true);
  285. }
  286. #if !BUILDFLAG(IS_WIN)
  287. // For windows we call InitLogging later, after the sandbox is initialized.
  288. //
  289. // On Linux, we force a "preinit" in the zygote (i.e. never log to a default
  290. // log file), because the zygote is booted prior to JS running, so it can't
  291. // know the correct user-data directory. (And, further, accessing the
  292. // application name on Linux can cause glib calls that end up spawning
  293. // threads, which if done before the zygote is booted, causes a CHECK().)
  294. logging::InitElectronLogging(*command_line,
  295. /* is_preinit = */ process_type.empty() ||
  296. process_type == ::switches::kZygoteProcess);
  297. #endif
  298. #if !IS_MAS_BUILD()
  299. crash_reporter::InitializeCrashKeys();
  300. #endif
  301. // Initialize ResourceBundle which handles files loaded from external
  302. // sources. The language should have been passed in to us from the
  303. // browser process as a command line flag.
  304. if (SubprocessNeedsResourceBundle(process_type)) {
  305. std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
  306. LoadResourceBundle(locale);
  307. }
  308. #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  309. // In the main process, we wait for JS to call crashReporter.start() before
  310. // initializing crashpad. If we're in the renderer, we want to initialize it
  311. // immediately at boot.
  312. if (!process_type.empty()) {
  313. ElectronCrashReporterClient::Create();
  314. crash_reporter::InitializeCrashpad(false, process_type);
  315. }
  316. #endif
  317. #if BUILDFLAG(IS_LINUX)
  318. // Zygote needs to call InitCrashReporter() in RunZygote().
  319. if (process_type != ::switches::kZygoteProcess && !process_type.empty()) {
  320. ElectronCrashReporterClient::Create();
  321. if (command_line->HasSwitch(
  322. crash_reporter::switches::kCrashpadHandlerPid)) {
  323. crash_reporter::InitializeCrashpad(false, process_type);
  324. crash_reporter::SetFirstChanceExceptionHandler(
  325. v8::TryHandleWebAssemblyTrapPosix);
  326. }
  327. }
  328. #endif
  329. #if !IS_MAS_BUILD()
  330. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  331. crash_keys::SetPlatformCrashKey();
  332. #endif
  333. if (IsBrowserProcess()) {
  334. // Only append arguments for browser process.
  335. // Allow file:// URIs to read other file:// URIs by default.
  336. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
  337. #if BUILDFLAG(IS_MAC)
  338. // Enable AVFoundation.
  339. command_line->AppendSwitch("enable-avfoundation");
  340. #endif
  341. }
  342. }
  343. void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) {
  344. #if BUILDFLAG(IS_WIN)
  345. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
  346. /* is_preinit = */ process_type.empty());
  347. #endif
  348. }
  349. absl::optional<int> ElectronMainDelegate::PreBrowserMain() {
  350. // This is initialized early because the service manager reads some feature
  351. // flags and we need to make sure the feature list is initialized before the
  352. // service manager reads the features.
  353. InitializeFeatureList();
  354. // Initialize mojo core as soon as we have a valid feature list
  355. content::InitializeMojoCore();
  356. #if BUILDFLAG(IS_MAC)
  357. RegisterAtomCrApp();
  358. #endif
  359. return absl::nullopt;
  360. }
  361. base::StringPiece ElectronMainDelegate::GetBrowserV8SnapshotFilename() {
  362. const base::CommandLine* command_line =
  363. base::CommandLine::ForCurrentProcess();
  364. std::string process_type =
  365. command_line->GetSwitchValueASCII(::switches::kProcessType);
  366. bool load_browser_process_specific_v8_snapshot =
  367. process_type.empty() &&
  368. electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled();
  369. if (load_browser_process_specific_v8_snapshot) {
  370. return "browser_v8_context_snapshot.bin";
  371. }
  372. return ContentMainDelegate::GetBrowserV8SnapshotFilename();
  373. }
  374. content::ContentClient* ElectronMainDelegate::CreateContentClient() {
  375. content_client_ = std::make_unique<ElectronContentClient>();
  376. return content_client_.get();
  377. }
  378. content::ContentBrowserClient*
  379. ElectronMainDelegate::CreateContentBrowserClient() {
  380. browser_client_ = std::make_unique<ElectronBrowserClient>();
  381. return browser_client_.get();
  382. }
  383. content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() {
  384. gpu_client_ = std::make_unique<ElectronGpuClient>();
  385. return gpu_client_.get();
  386. }
  387. content::ContentRendererClient*
  388. ElectronMainDelegate::CreateContentRendererClient() {
  389. auto* command_line = base::CommandLine::ForCurrentProcess();
  390. if (IsSandboxEnabled(command_line)) {
  391. renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
  392. } else {
  393. renderer_client_ = std::make_unique<ElectronRendererClient>();
  394. }
  395. return renderer_client_.get();
  396. }
  397. content::ContentUtilityClient*
  398. ElectronMainDelegate::CreateContentUtilityClient() {
  399. utility_client_ = std::make_unique<ElectronContentUtilityClient>();
  400. return utility_client_.get();
  401. }
  402. absl::variant<int, content::MainFunctionParams>
  403. ElectronMainDelegate::RunProcess(
  404. const std::string& process_type,
  405. content::MainFunctionParams main_function_params) {
  406. if (process_type == kRelauncherProcess)
  407. return relauncher::RelauncherMain(main_function_params);
  408. else
  409. return std::move(main_function_params);
  410. }
  411. bool ElectronMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) {
  412. return absl::holds_alternative<InvokedInChildProcess>(invoked_in);
  413. }
  414. bool ElectronMainDelegate::ShouldInitializeMojo(InvokedIn invoked_in) {
  415. return ShouldCreateFeatureList(invoked_in);
  416. }
  417. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  418. return false;
  419. }
  420. #if BUILDFLAG(IS_LINUX)
  421. void ElectronMainDelegate::ZygoteForked() {
  422. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  423. // this up for the browser process in a different manner.
  424. ElectronCrashReporterClient::Create();
  425. const base::CommandLine* command_line =
  426. base::CommandLine::ForCurrentProcess();
  427. std::string process_type =
  428. command_line->GetSwitchValueASCII(::switches::kProcessType);
  429. if (command_line->HasSwitch(crash_reporter::switches::kCrashpadHandlerPid)) {
  430. crash_reporter::InitializeCrashpad(false, process_type);
  431. crash_reporter::SetFirstChanceExceptionHandler(
  432. v8::TryHandleWebAssemblyTrapPosix);
  433. }
  434. // Reset the command line for the newly spawned process.
  435. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  436. }
  437. #endif // BUILDFLAG(IS_LINUX)
  438. } // namespace electron