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 <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 "base/strings/string_split.h"
  19. #include "chrome/common/chrome_paths.h"
  20. #include "chrome/common/chrome_switches.h"
  21. #include "components/content_settings/core/common/content_settings_pattern.h"
  22. #include "content/public/app/initialize_mojo_core.h"
  23. #include "content/public/common/content_switches.h"
  24. #include "electron/buildflags/buildflags.h"
  25. #include "electron/fuses.h"
  26. #include "extensions/common/constants.h"
  27. #include "ipc/ipc_buildflags.h"
  28. #include "sandbox/policy/switches.h"
  29. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
  30. #include "shell/app/command_line_args.h"
  31. #include "shell/app/electron_content_client.h"
  32. #include "shell/browser/electron_browser_client.h"
  33. #include "shell/browser/electron_gpu_client.h"
  34. #include "shell/browser/feature_list.h"
  35. #include "shell/browser/relauncher.h"
  36. #include "shell/common/application_info.h"
  37. #include "shell/common/electron_paths.h"
  38. #include "shell/common/logging.h"
  39. #include "shell/common/options_switches.h"
  40. #include "shell/common/platform_util.h"
  41. #include "shell/common/process_util.h"
  42. #include "shell/common/thread_restrictions.h"
  43. #include "shell/renderer/electron_renderer_client.h"
  44. #include "shell/renderer/electron_sandboxed_renderer_client.h"
  45. #include "shell/utility/electron_content_utility_client.h"
  46. #include "third_party/abseil-cpp/absl/types/variant.h"
  47. #include "ui/base/resource/resource_bundle.h"
  48. #include "ui/base/ui_base_switches.h"
  49. #if BUILDFLAG(IS_MAC)
  50. #include "shell/app/electron_main_delegate_mac.h"
  51. #endif
  52. #if BUILDFLAG(IS_WIN)
  53. #include "base/win/win_util.h"
  54. #include "chrome/child/v8_crashpad_support_win.h"
  55. #endif
  56. #if BUILDFLAG(IS_LINUX)
  57. #include "base/nix/xdg_util.h"
  58. #include "v8/include/v8-wasm-trap-handler-posix.h"
  59. #include "v8/include/v8.h"
  60. #endif
  61. #if !IS_MAS_BUILD()
  62. #include "components/crash/core/app/crash_switches.h" // nogncheck
  63. #include "components/crash/core/app/crashpad.h" // nogncheck
  64. #include "components/crash/core/common/crash_key.h"
  65. #include "components/crash/core/common/crash_keys.h"
  66. #include "shell/app/electron_crash_reporter_client.h"
  67. #include "shell/browser/api/electron_api_crash_reporter.h"
  68. #include "shell/common/crash_keys.h"
  69. #endif
  70. namespace electron {
  71. namespace {
  72. const char kRelauncherProcess[] = "relauncher";
  73. constexpr std::string_view kElectronDisableSandbox{"ELECTRON_DISABLE_SANDBOX"};
  74. constexpr std::string_view kElectronEnableStackDumping{
  75. "ELECTRON_ENABLE_STACK_DUMPING"};
  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. ScopedAllowBlockingForElectron allow_blocking;
  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::apple::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. std::optional<int> ElectronMainDelegate::BasicStartupComplete() {
  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())
  223. std::wcout << std::endl;
  224. #endif // !BUILDFLAG(IS_WIN)
  225. auto env = base::Environment::Create();
  226. // Enable convenient stack printing. This is enabled by default in
  227. // non-official builds.
  228. if (env->HasVar(kElectronEnableStackDumping))
  229. base::debug::EnableInProcessStackDumping();
  230. if (env->HasVar(kElectronDisableSandbox))
  231. command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
  232. tracing_sampler_profiler_ =
  233. tracing::TracingSamplerProfiler::CreateOnMainThread();
  234. chrome::RegisterPathProvider();
  235. electron::RegisterPathProvider();
  236. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  237. ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes(
  238. kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize);
  239. #endif
  240. #if BUILDFLAG(IS_MAC)
  241. OverrideChildProcessPath();
  242. OverrideFrameworkBundlePath();
  243. SetUpBundleOverrides();
  244. #endif
  245. #if BUILDFLAG(IS_WIN)
  246. // Ignore invalid parameter errors.
  247. _set_invalid_parameter_handler(InvalidParameterHandler);
  248. // Disable the ActiveVerifier, which is used by Chrome to track possible
  249. // bugs, but no use in Electron.
  250. base::win::DisableHandleVerifier();
  251. if (IsBrowserProcess())
  252. base::win::PinUser32();
  253. #endif
  254. #if BUILDFLAG(IS_LINUX)
  255. // Check for --no-sandbox parameter when running as root.
  256. if (getuid() == 0 && IsSandboxEnabled(command_line))
  257. LOG(FATAL) << "Running as root without --"
  258. << sandbox::policy::switches::kNoSandbox
  259. << " is not supported. See https://crbug.com/638180.";
  260. #endif
  261. #if IS_MAS_BUILD()
  262. // In MAS build we are using --disable-remote-core-animation.
  263. //
  264. // According to ccameron:
  265. // If you're running with --disable-remote-core-animation, you may want to
  266. // also run with --disable-gpu-memory-buffer-compositor-resources as well.
  267. // That flag makes it so we use regular GL textures instead of IOSurfaces
  268. // for compositor resources. IOSurfaces are very heavyweight to
  269. // create/destroy, but they can be displayed directly by CoreAnimation (and
  270. // --disable-remote-core-animation makes it so we don't use this property,
  271. // so they're just heavyweight with no upside).
  272. command_line->AppendSwitch(
  273. ::switches::kDisableGpuMemoryBufferCompositorResources);
  274. #endif
  275. return std::nullopt;
  276. }
  277. void ElectronMainDelegate::PreSandboxStartup() {
  278. auto* command_line = base::CommandLine::ForCurrentProcess();
  279. std::string process_type = GetProcessType();
  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(
  295. *command_line,
  296. /* is_preinit = */ IsBrowserProcess() || IsZygoteProcess());
  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 (!IsBrowserProcess()) {
  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 (!IsZygoteProcess() && !IsBrowserProcess()) {
  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. std::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. #if BUILDFLAG(IS_LINUX)
  360. // Set the global activation token sent as an environment variable.
  361. auto env = base::Environment::Create();
  362. base::nix::ExtractXdgActivationTokenFromEnv(*env);
  363. #endif
  364. return std::nullopt;
  365. }
  366. base::StringPiece ElectronMainDelegate::GetBrowserV8SnapshotFilename() {
  367. bool load_browser_process_specific_v8_snapshot =
  368. IsBrowserProcess() &&
  369. electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled();
  370. if (load_browser_process_specific_v8_snapshot) {
  371. return "browser_v8_context_snapshot.bin";
  372. }
  373. return ContentMainDelegate::GetBrowserV8SnapshotFilename();
  374. }
  375. content::ContentClient* ElectronMainDelegate::CreateContentClient() {
  376. content_client_ = std::make_unique<ElectronContentClient>();
  377. return content_client_.get();
  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 absl::holds_alternative<InvokedInChildProcess>(invoked_in);
  414. }
  415. bool ElectronMainDelegate::ShouldInitializeMojo(InvokedIn invoked_in) {
  416. return ShouldCreateFeatureList(invoked_in);
  417. }
  418. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  419. return false;
  420. }
  421. #if BUILDFLAG(IS_LINUX)
  422. void ElectronMainDelegate::ZygoteForked() {
  423. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  424. // this up for the browser process in a different manner.
  425. ElectronCrashReporterClient::Create();
  426. const base::CommandLine* command_line =
  427. base::CommandLine::ForCurrentProcess();
  428. std::string process_type =
  429. command_line->GetSwitchValueASCII(::switches::kProcessType);
  430. if (command_line->HasSwitch(crash_reporter::switches::kCrashpadHandlerPid)) {
  431. crash_reporter::InitializeCrashpad(false, process_type);
  432. crash_reporter::SetFirstChanceExceptionHandler(
  433. v8::TryHandleWebAssemblyTrapPosix);
  434. }
  435. // Reset the command line for the newly spawned process.
  436. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  437. }
  438. #endif // BUILDFLAG(IS_LINUX)
  439. } // namespace electron