electron_main_delegate.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 "extensions/common/constants.h"
  24. #include "ipc/ipc_buildflags.h"
  25. #include "sandbox/policy/switches.h"
  26. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
  27. #include "shell/app/command_line_args.h"
  28. #include "shell/app/electron_content_client.h"
  29. #include "shell/browser/electron_browser_client.h"
  30. #include "shell/browser/electron_gpu_client.h"
  31. #include "shell/browser/feature_list.h"
  32. #include "shell/browser/relauncher.h"
  33. #include "shell/common/application_info.h"
  34. #include "shell/common/electron_paths.h"
  35. #include "shell/common/logging.h"
  36. #include "shell/common/options_switches.h"
  37. #include "shell/common/platform_util.h"
  38. #include "shell/renderer/electron_renderer_client.h"
  39. #include "shell/renderer/electron_sandboxed_renderer_client.h"
  40. #include "shell/utility/electron_content_utility_client.h"
  41. #include "ui/base/resource/resource_bundle.h"
  42. #include "ui/base/ui_base_switches.h"
  43. #if BUILDFLAG(IS_MAC)
  44. #include "shell/app/electron_main_delegate_mac.h"
  45. #endif
  46. #if BUILDFLAG(IS_WIN)
  47. #include "base/win/win_util.h"
  48. #include "chrome/child/v8_crashpad_support_win.h"
  49. #endif
  50. #if BUILDFLAG(IS_LINUX)
  51. #include "base/nix/xdg_util.h"
  52. #include "components/crash/core/app/breakpad_linux.h"
  53. #include "v8/include/v8-wasm-trap-handler-posix.h"
  54. #include "v8/include/v8.h"
  55. #endif
  56. #if !defined(MAS_BUILD)
  57. #include "components/crash/core/app/crash_switches.h" // nogncheck
  58. #include "components/crash/core/app/crashpad.h" // nogncheck
  59. #include "components/crash/core/common/crash_key.h"
  60. #include "components/crash/core/common/crash_keys.h"
  61. #include "shell/app/electron_crash_reporter_client.h"
  62. #include "shell/browser/api/electron_api_crash_reporter.h"
  63. #include "shell/common/crash_keys.h"
  64. #endif
  65. namespace electron {
  66. namespace {
  67. const char kRelauncherProcess[] = "relauncher";
  68. constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX");
  69. constexpr base::StringPiece kElectronEnableStackDumping(
  70. "ELECTRON_ENABLE_STACK_DUMPING");
  71. bool IsBrowserProcess(base::CommandLine* cmd) {
  72. std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType);
  73. return process_type.empty();
  74. }
  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(chrome::DIR_USER_DATA, &cur))
  123. return false;
  124. cur = cur.Append(base::FilePath::FromUTF8Unsafe("Dictionaries"));
  125. create_dir = true;
  126. break;
  127. case DIR_USER_CACHE: {
  128. #if BUILDFLAG(IS_POSIX)
  129. int parent_key = base::DIR_CACHE;
  130. #else
  131. // On Windows, there's no OS-level centralized location for caches, so
  132. // store the cache in the app data directory.
  133. int parent_key = base::DIR_ROAMING_APP_DATA;
  134. #endif
  135. if (!base::PathService::Get(parent_key, &cur))
  136. return false;
  137. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  138. GetPossiblyOverriddenApplicationName()));
  139. create_dir = true;
  140. break;
  141. }
  142. #if BUILDFLAG(IS_LINUX)
  143. case DIR_APP_DATA: {
  144. auto env = base::Environment::Create();
  145. cur = base::nix::GetXDGDirectory(
  146. env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir);
  147. break;
  148. }
  149. #endif
  150. #if BUILDFLAG(IS_WIN)
  151. case DIR_RECENT:
  152. if (!platform_util::GetFolderPath(DIR_RECENT, &cur))
  153. return false;
  154. create_dir = true;
  155. break;
  156. #endif
  157. case DIR_APP_LOGS:
  158. #if BUILDFLAG(IS_MAC)
  159. if (!base::PathService::Get(base::DIR_HOME, &cur))
  160. return false;
  161. cur = cur.Append(FILE_PATH_LITERAL("Library"));
  162. cur = cur.Append(FILE_PATH_LITERAL("Logs"));
  163. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  164. GetPossiblyOverriddenApplicationName()));
  165. #else
  166. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  167. return false;
  168. cur = cur.Append(base::FilePath::FromUTF8Unsafe("logs"));
  169. #endif
  170. create_dir = true;
  171. break;
  172. default:
  173. return false;
  174. }
  175. // TODO(bauerb): http://crbug.com/259796
  176. base::ThreadRestrictions::ScopedAllowIO allow_io;
  177. if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur)) {
  178. return false;
  179. }
  180. *result = cur;
  181. return true;
  182. }
  183. void RegisterPathProvider() {
  184. base::PathService::RegisterProvider(ElectronPathProvider, PATH_START,
  185. PATH_END);
  186. }
  187. } // namespace
  188. std::string LoadResourceBundle(const std::string& locale) {
  189. const bool initialized = ui::ResourceBundle::HasSharedInstance();
  190. DCHECK(!initialized);
  191. // Load other resource files.
  192. base::FilePath pak_dir;
  193. #if BUILDFLAG(IS_MAC)
  194. pak_dir =
  195. base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
  196. #else
  197. base::PathService::Get(base::DIR_MODULE, &pak_dir);
  198. #endif
  199. std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
  200. locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
  201. ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  202. bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")),
  203. ui::kScaleFactorNone);
  204. return loaded_locale;
  205. }
  206. ElectronMainDelegate::ElectronMainDelegate() = default;
  207. ElectronMainDelegate::~ElectronMainDelegate() = default;
  208. const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = {
  209. extensions::kExtensionScheme};
  210. const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize =
  211. base::size(kNonWildcardDomainNonPortSchemes);
  212. bool ElectronMainDelegate::BasicStartupComplete(int* exit_code) {
  213. auto* command_line = base::CommandLine::ForCurrentProcess();
  214. #if BUILDFLAG(IS_WIN)
  215. v8_crashpad_support::SetUp();
  216. // On Windows the terminal returns immediately, so we add a new line to
  217. // prevent output in the same line as the prompt.
  218. if (IsBrowserProcess(command_line))
  219. std::wcout << std::endl;
  220. #endif // !BUILDFLAG(IS_WIN)
  221. auto env = base::Environment::Create();
  222. // Enable convenient stack printing. This is enabled by default in
  223. // non-official builds.
  224. if (env->HasVar(kElectronEnableStackDumping))
  225. base::debug::EnableInProcessStackDumping();
  226. if (env->HasVar(kElectronDisableSandbox))
  227. command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
  228. tracing_sampler_profiler_ =
  229. tracing::TracingSamplerProfiler::CreateOnMainThread();
  230. chrome::RegisterPathProvider();
  231. electron::RegisterPathProvider();
  232. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  233. ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes(
  234. kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize);
  235. #endif
  236. #if BUILDFLAG(IS_MAC)
  237. OverrideChildProcessPath();
  238. OverrideFrameworkBundlePath();
  239. SetUpBundleOverrides();
  240. #endif
  241. #if BUILDFLAG(IS_WIN)
  242. // Ignore invalid parameter errors.
  243. _set_invalid_parameter_handler(InvalidParameterHandler);
  244. // Disable the ActiveVerifier, which is used by Chrome to track possible
  245. // bugs, but no use in Electron.
  246. base::win::DisableHandleVerifier();
  247. if (IsBrowserProcess(command_line))
  248. base::win::PinUser32();
  249. #endif
  250. #if BUILDFLAG(IS_LINUX)
  251. // Check for --no-sandbox parameter when running as root.
  252. if (getuid() == 0 && IsSandboxEnabled(command_line))
  253. LOG(FATAL) << "Running as root without --"
  254. << sandbox::policy::switches::kNoSandbox
  255. << " is not supported. See https://crbug.com/638180.";
  256. #endif
  257. #if defined(MAS_BUILD)
  258. // In MAS build we are using --disable-remote-core-animation.
  259. //
  260. // According to ccameron:
  261. // If you're running with --disable-remote-core-animation, you may want to
  262. // also run with --disable-gpu-memory-buffer-compositor-resources as well.
  263. // That flag makes it so we use regular GL textures instead of IOSurfaces
  264. // for compositor resources. IOSurfaces are very heavyweight to
  265. // create/destroy, but they can be displayed directly by CoreAnimation (and
  266. // --disable-remote-core-animation makes it so we don't use this property,
  267. // so they're just heavyweight with no upside).
  268. command_line->AppendSwitch(
  269. ::switches::kDisableGpuMemoryBufferCompositorResources);
  270. #endif
  271. content_client_ = std::make_unique<ElectronContentClient>();
  272. SetContentClient(content_client_.get());
  273. return false;
  274. }
  275. void ElectronMainDelegate::PreSandboxStartup() {
  276. auto* command_line = base::CommandLine::ForCurrentProcess();
  277. std::string process_type =
  278. command_line->GetSwitchValueASCII(::switches::kProcessType);
  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(*command_line,
  294. /* is_preinit = */ process_type.empty() ||
  295. process_type == ::switches::kZygoteProcess);
  296. #endif
  297. #if !defined(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) && !defined(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 (!process_type.empty()) {
  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 (process_type != ::switches::kZygoteProcess && !process_type.empty()) {
  319. ElectronCrashReporterClient::Create();
  320. if (crash_reporter::IsCrashpadEnabled()) {
  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. } else {
  328. breakpad::InitCrashReporter(process_type);
  329. }
  330. }
  331. #endif
  332. #if !defined(MAS_BUILD)
  333. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  334. crash_keys::SetPlatformCrashKey();
  335. #endif
  336. if (IsBrowserProcess(command_line)) {
  337. // Only append arguments for browser process.
  338. // Allow file:// URIs to read other file:// URIs by default.
  339. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
  340. #if BUILDFLAG(IS_MAC)
  341. // Enable AVFoundation.
  342. command_line->AppendSwitch("enable-avfoundation");
  343. #endif
  344. }
  345. }
  346. void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) {
  347. #if BUILDFLAG(IS_WIN)
  348. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
  349. /* is_preinit = */ process_type.empty());
  350. #endif
  351. }
  352. void ElectronMainDelegate::PreBrowserMain() {
  353. // This is initialized early because the service manager reads some feature
  354. // flags and we need to make sure the feature list is initialized before the
  355. // service manager reads the features.
  356. InitializeFeatureList();
  357. #if BUILDFLAG(IS_MAC)
  358. RegisterAtomCrApp();
  359. #endif
  360. }
  361. content::ContentBrowserClient*
  362. ElectronMainDelegate::CreateContentBrowserClient() {
  363. browser_client_ = std::make_unique<ElectronBrowserClient>();
  364. return browser_client_.get();
  365. }
  366. content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() {
  367. gpu_client_ = std::make_unique<ElectronGpuClient>();
  368. return gpu_client_.get();
  369. }
  370. content::ContentRendererClient*
  371. ElectronMainDelegate::CreateContentRendererClient() {
  372. auto* command_line = base::CommandLine::ForCurrentProcess();
  373. if (IsSandboxEnabled(command_line)) {
  374. renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
  375. } else {
  376. renderer_client_ = std::make_unique<ElectronRendererClient>();
  377. }
  378. return renderer_client_.get();
  379. }
  380. content::ContentUtilityClient*
  381. ElectronMainDelegate::CreateContentUtilityClient() {
  382. utility_client_ = std::make_unique<ElectronContentUtilityClient>();
  383. return utility_client_.get();
  384. }
  385. absl::variant<int, content::MainFunctionParams>
  386. ElectronMainDelegate::RunProcess(
  387. const std::string& process_type,
  388. content::MainFunctionParams main_function_params) {
  389. if (process_type == kRelauncherProcess)
  390. return relauncher::RelauncherMain(main_function_params);
  391. else
  392. return std::move(main_function_params);
  393. }
  394. bool ElectronMainDelegate::ShouldCreateFeatureList() {
  395. return false;
  396. }
  397. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  398. return false;
  399. }
  400. #if BUILDFLAG(IS_LINUX)
  401. void ElectronMainDelegate::ZygoteForked() {
  402. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  403. // this up for the browser process in a different manner.
  404. ElectronCrashReporterClient::Create();
  405. const base::CommandLine* command_line =
  406. base::CommandLine::ForCurrentProcess();
  407. std::string process_type =
  408. command_line->GetSwitchValueASCII(::switches::kProcessType);
  409. if (crash_reporter::IsCrashpadEnabled()) {
  410. if (command_line->HasSwitch(
  411. crash_reporter::switches::kCrashpadHandlerPid)) {
  412. crash_reporter::InitializeCrashpad(false, process_type);
  413. crash_reporter::SetFirstChanceExceptionHandler(
  414. v8::TryHandleWebAssemblyTrapPosix);
  415. }
  416. } else {
  417. breakpad::InitCrashReporter(process_type);
  418. }
  419. // Reset the command line for the newly spawned process.
  420. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  421. }
  422. #endif // BUILDFLAG(IS_LINUX)
  423. } // namespace electron