electron_main_delegate.cc 16 KB

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