electron_main_delegate.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/environment.h"
  12. #include "base/files/file_util.h"
  13. #include "base/logging.h"
  14. #include "base/mac/bundle_locations.h"
  15. #include "base/path_service.h"
  16. #include "base/strings/string_split.h"
  17. #include "chrome/common/chrome_paths.h"
  18. #include "chrome/common/chrome_switches.h"
  19. #include "components/content_settings/core/common/content_settings_pattern.h"
  20. #include "content/public/common/content_switches.h"
  21. #include "electron/buildflags/buildflags.h"
  22. #include "extensions/common/constants.h"
  23. #include "ipc/ipc_buildflags.h"
  24. #include "sandbox/policy/switches.h"
  25. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
  26. #include "shell/app/command_line_args.h"
  27. #include "shell/app/electron_content_client.h"
  28. #include "shell/browser/electron_browser_client.h"
  29. #include "shell/browser/electron_gpu_client.h"
  30. #include "shell/browser/feature_list.h"
  31. #include "shell/browser/relauncher.h"
  32. #include "shell/common/application_info.h"
  33. #include "shell/common/electron_paths.h"
  34. #include "shell/common/logging.h"
  35. #include "shell/common/options_switches.h"
  36. #include "shell/common/platform_util.h"
  37. #include "shell/renderer/electron_renderer_client.h"
  38. #include "shell/renderer/electron_sandboxed_renderer_client.h"
  39. #include "shell/utility/electron_content_utility_client.h"
  40. #include "ui/base/resource/resource_bundle.h"
  41. #include "ui/base/ui_base_switches.h"
  42. #if defined(OS_MAC)
  43. #include "shell/app/electron_main_delegate_mac.h"
  44. #endif
  45. #if defined(OS_WIN)
  46. #include "base/win/win_util.h"
  47. #include "chrome/child/v8_crashpad_support_win.h"
  48. #endif
  49. #if defined(OS_LINUX)
  50. #include "base/nix/xdg_util.h"
  51. #include "components/crash/core/app/breakpad_linux.h"
  52. #include "v8/include/v8-wasm-trap-handler-posix.h"
  53. #include "v8/include/v8.h"
  54. #endif
  55. #if !defined(MAS_BUILD)
  56. #include "components/crash/core/app/crash_switches.h" // nogncheck
  57. #include "components/crash/core/app/crashpad.h" // nogncheck
  58. #include "components/crash/core/common/crash_key.h"
  59. #include "components/crash/core/common/crash_keys.h"
  60. #include "shell/app/electron_crash_reporter_client.h"
  61. #include "shell/browser/api/electron_api_crash_reporter.h"
  62. #include "shell/common/crash_keys.h"
  63. #endif
  64. namespace electron {
  65. namespace {
  66. const char kRelauncherProcess[] = "relauncher";
  67. constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX");
  68. constexpr base::StringPiece kElectronEnableStackDumping(
  69. "ELECTRON_ENABLE_STACK_DUMPING");
  70. bool IsBrowserProcess(base::CommandLine* cmd) {
  71. std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType);
  72. return process_type.empty();
  73. }
  74. // Returns true if this subprocess type needs the ResourceBundle initialized
  75. // and resources loaded.
  76. bool SubprocessNeedsResourceBundle(const std::string& process_type) {
  77. return
  78. #if defined(OS_LINUX)
  79. // The zygote process opens the resources for the renderers.
  80. process_type == ::switches::kZygoteProcess ||
  81. #endif
  82. #if defined(OS_MAC)
  83. // Mac needs them too for scrollbar related images and for sandbox
  84. // profiles.
  85. process_type == ::switches::kGpuProcess ||
  86. #endif
  87. process_type == ::switches::kPpapiPluginProcess ||
  88. process_type == ::switches::kRendererProcess ||
  89. process_type == ::switches::kUtilityProcess;
  90. }
  91. #if defined(OS_WIN)
  92. void InvalidParameterHandler(const wchar_t*,
  93. const wchar_t*,
  94. const wchar_t*,
  95. unsigned int,
  96. uintptr_t) {
  97. // noop.
  98. }
  99. #endif
  100. // TODO(nornagon): move path provider overriding to its own file in
  101. // shell/common
  102. bool ElectronPathProvider(int key, base::FilePath* result) {
  103. bool create_dir = false;
  104. base::FilePath cur;
  105. switch (key) {
  106. case chrome::DIR_USER_DATA:
  107. if (!base::PathService::Get(DIR_APP_DATA, &cur))
  108. return false;
  109. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  110. GetPossiblyOverriddenApplicationName()));
  111. create_dir = true;
  112. break;
  113. case DIR_CRASH_DUMPS:
  114. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  115. return false;
  116. cur = cur.Append(FILE_PATH_LITERAL("Crashpad"));
  117. create_dir = true;
  118. break;
  119. case chrome::DIR_APP_DICTIONARIES:
  120. // TODO(nornagon): can we just default to using Chrome's logic here?
  121. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  122. return false;
  123. cur = cur.Append(base::FilePath::FromUTF8Unsafe("Dictionaries"));
  124. create_dir = true;
  125. break;
  126. case DIR_USER_CACHE: {
  127. #if defined(OS_POSIX)
  128. int parent_key = base::DIR_CACHE;
  129. #else
  130. // On Windows, there's no OS-level centralized location for caches, so
  131. // store the cache in the app data directory.
  132. int parent_key = base::DIR_ROAMING_APP_DATA;
  133. #endif
  134. if (!base::PathService::Get(parent_key, &cur))
  135. return false;
  136. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  137. GetPossiblyOverriddenApplicationName()));
  138. create_dir = true;
  139. break;
  140. }
  141. #if defined(OS_LINUX)
  142. case DIR_APP_DATA: {
  143. auto env = base::Environment::Create();
  144. cur = base::nix::GetXDGDirectory(
  145. env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir);
  146. break;
  147. }
  148. #endif
  149. #if defined(OS_WIN)
  150. case DIR_RECENT:
  151. if (!platform_util::GetFolderPath(DIR_RECENT, &cur))
  152. return false;
  153. create_dir = true;
  154. break;
  155. #endif
  156. case DIR_APP_LOGS:
  157. #if defined(OS_MAC)
  158. if (!base::PathService::Get(base::DIR_HOME, &cur))
  159. return false;
  160. cur = cur.Append(FILE_PATH_LITERAL("Library"));
  161. cur = cur.Append(FILE_PATH_LITERAL("Logs"));
  162. cur = cur.Append(base::FilePath::FromUTF8Unsafe(
  163. GetPossiblyOverriddenApplicationName()));
  164. #else
  165. if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
  166. return false;
  167. cur = cur.Append(base::FilePath::FromUTF8Unsafe("logs"));
  168. #endif
  169. create_dir = true;
  170. break;
  171. default:
  172. return false;
  173. }
  174. // TODO(bauerb): http://crbug.com/259796
  175. base::ThreadRestrictions::ScopedAllowIO allow_io;
  176. if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur)) {
  177. return false;
  178. }
  179. *result = cur;
  180. return true;
  181. }
  182. void RegisterPathProvider() {
  183. base::PathService::RegisterProvider(ElectronPathProvider, PATH_START,
  184. PATH_END);
  185. }
  186. } // namespace
  187. std::string LoadResourceBundle(const std::string& locale) {
  188. const bool initialized = ui::ResourceBundle::HasSharedInstance();
  189. DCHECK(!initialized);
  190. // Load other resource files.
  191. base::FilePath pak_dir;
  192. #if defined(OS_MAC)
  193. pak_dir =
  194. base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
  195. #else
  196. base::PathService::Get(base::DIR_MODULE, &pak_dir);
  197. #endif
  198. std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
  199. locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
  200. ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  201. bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")),
  202. ui::kScaleFactorNone);
  203. return loaded_locale;
  204. }
  205. ElectronMainDelegate::ElectronMainDelegate() = default;
  206. ElectronMainDelegate::~ElectronMainDelegate() = default;
  207. const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = {
  208. extensions::kExtensionScheme};
  209. const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize =
  210. base::size(kNonWildcardDomainNonPortSchemes);
  211. bool ElectronMainDelegate::BasicStartupComplete(int* exit_code) {
  212. auto* command_line = base::CommandLine::ForCurrentProcess();
  213. #if defined(OS_WIN)
  214. v8_crashpad_support::SetUp();
  215. // On Windows the terminal returns immediately, so we add a new line to
  216. // prevent output in the same line as the prompt.
  217. if (IsBrowserProcess(command_line))
  218. std::wcout << std::endl;
  219. #endif // !defined(OS_WIN)
  220. auto env = base::Environment::Create();
  221. // Enable convenient stack printing. This is enabled by default in
  222. // non-official builds.
  223. if (env->HasVar(kElectronEnableStackDumping))
  224. base::debug::EnableInProcessStackDumping();
  225. if (env->HasVar(kElectronDisableSandbox))
  226. command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
  227. tracing_sampler_profiler_ =
  228. tracing::TracingSamplerProfiler::CreateOnMainThread();
  229. chrome::RegisterPathProvider();
  230. electron::RegisterPathProvider();
  231. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  232. ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes(
  233. kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize);
  234. #endif
  235. #if defined(OS_MAC)
  236. OverrideChildProcessPath();
  237. OverrideFrameworkBundlePath();
  238. SetUpBundleOverrides();
  239. #endif
  240. #if defined(OS_WIN)
  241. // Ignore invalid parameter errors.
  242. _set_invalid_parameter_handler(InvalidParameterHandler);
  243. // Disable the ActiveVerifier, which is used by Chrome to track possible
  244. // bugs, but no use in Electron.
  245. base::win::DisableHandleVerifier();
  246. if (IsBrowserProcess(command_line))
  247. base::win::PinUser32();
  248. #endif
  249. #if defined(OS_LINUX)
  250. // Check for --no-sandbox parameter when running as root.
  251. if (getuid() == 0 && IsSandboxEnabled(command_line))
  252. LOG(FATAL) << "Running as root without --"
  253. << sandbox::policy::switches::kNoSandbox
  254. << " is not supported. See https://crbug.com/638180.";
  255. #endif
  256. #if defined(MAS_BUILD)
  257. // In MAS build we are using --disable-remote-core-animation.
  258. //
  259. // According to ccameron:
  260. // If you're running with --disable-remote-core-animation, you may want to
  261. // also run with --disable-gpu-memory-buffer-compositor-resources as well.
  262. // That flag makes it so we use regular GL textures instead of IOSurfaces
  263. // for compositor resources. IOSurfaces are very heavyweight to
  264. // create/destroy, but they can be displayed directly by CoreAnimation (and
  265. // --disable-remote-core-animation makes it so we don't use this property,
  266. // so they're just heavyweight with no upside).
  267. command_line->AppendSwitch(
  268. ::switches::kDisableGpuMemoryBufferCompositorResources);
  269. #endif
  270. content_client_ = std::make_unique<ElectronContentClient>();
  271. SetContentClient(content_client_.get());
  272. return false;
  273. }
  274. void ElectronMainDelegate::PreSandboxStartup() {
  275. auto* command_line = base::CommandLine::ForCurrentProcess();
  276. std::string process_type =
  277. command_line->GetSwitchValueASCII(::switches::kProcessType);
  278. base::FilePath user_data_dir =
  279. command_line->GetSwitchValuePath(::switches::kUserDataDir);
  280. if (!user_data_dir.empty()) {
  281. base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
  282. user_data_dir, false, true);
  283. }
  284. #if !defined(OS_WIN)
  285. // For windows we call InitLogging later, after the sandbox is initialized.
  286. //
  287. // On Linux, we force a "preinit" in the zygote (i.e. never log to a default
  288. // log file), because the zygote is booted prior to JS running, so it can't
  289. // know the correct user-data directory. (And, further, accessing the
  290. // application name on Linux can cause glib calls that end up spawning
  291. // threads, which if done before the zygote is booted, causes a CHECK().)
  292. logging::InitElectronLogging(*command_line,
  293. /* is_preinit = */ process_type.empty() ||
  294. process_type == ::switches::kZygoteProcess);
  295. #endif
  296. #if !defined(MAS_BUILD)
  297. crash_reporter::InitializeCrashKeys();
  298. #endif
  299. // Initialize ResourceBundle which handles files loaded from external
  300. // sources. The language should have been passed in to us from the
  301. // browser process as a command line flag.
  302. if (SubprocessNeedsResourceBundle(process_type)) {
  303. std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
  304. LoadResourceBundle(locale);
  305. }
  306. #if defined(OS_WIN) || (defined(OS_MAC) && !defined(MAS_BUILD))
  307. // In the main process, we wait for JS to call crashReporter.start() before
  308. // initializing crashpad. If we're in the renderer, we want to initialize it
  309. // immediately at boot.
  310. if (!process_type.empty()) {
  311. ElectronCrashReporterClient::Create();
  312. crash_reporter::InitializeCrashpad(false, process_type);
  313. }
  314. #endif
  315. #if defined(OS_LINUX)
  316. // Zygote needs to call InitCrashReporter() in RunZygote().
  317. if (process_type != ::switches::kZygoteProcess && !process_type.empty()) {
  318. ElectronCrashReporterClient::Create();
  319. if (crash_reporter::IsCrashpadEnabled()) {
  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. } else {
  327. breakpad::InitCrashReporter(process_type);
  328. }
  329. }
  330. #endif
  331. #if !defined(MAS_BUILD)
  332. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  333. crash_keys::SetPlatformCrashKey();
  334. #endif
  335. if (IsBrowserProcess(command_line)) {
  336. // Only append arguments for browser process.
  337. // Allow file:// URIs to read other file:// URIs by default.
  338. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
  339. #if defined(OS_MAC)
  340. // Enable AVFoundation.
  341. command_line->AppendSwitch("enable-avfoundation");
  342. #endif
  343. }
  344. }
  345. void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) {
  346. #if defined(OS_WIN)
  347. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
  348. /* is_preinit = */ process_type.empty());
  349. #endif
  350. }
  351. void ElectronMainDelegate::PreBrowserMain() {
  352. // This is initialized early because the service manager reads some feature
  353. // flags and we need to make sure the feature list is initialized before the
  354. // service manager reads the features.
  355. InitializeFeatureList();
  356. #if defined(OS_MAC)
  357. RegisterAtomCrApp();
  358. #endif
  359. }
  360. content::ContentBrowserClient*
  361. ElectronMainDelegate::CreateContentBrowserClient() {
  362. browser_client_ = std::make_unique<ElectronBrowserClient>();
  363. return browser_client_.get();
  364. }
  365. content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() {
  366. gpu_client_ = std::make_unique<ElectronGpuClient>();
  367. return gpu_client_.get();
  368. }
  369. content::ContentRendererClient*
  370. ElectronMainDelegate::CreateContentRendererClient() {
  371. auto* command_line = base::CommandLine::ForCurrentProcess();
  372. if (IsSandboxEnabled(command_line)) {
  373. renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
  374. } else {
  375. renderer_client_ = std::make_unique<ElectronRendererClient>();
  376. }
  377. return renderer_client_.get();
  378. }
  379. content::ContentUtilityClient*
  380. ElectronMainDelegate::CreateContentUtilityClient() {
  381. utility_client_ = std::make_unique<ElectronContentUtilityClient>();
  382. return utility_client_.get();
  383. }
  384. absl::variant<int, content::MainFunctionParams>
  385. ElectronMainDelegate::RunProcess(
  386. const std::string& process_type,
  387. content::MainFunctionParams main_function_params) {
  388. if (process_type == kRelauncherProcess)
  389. return relauncher::RelauncherMain(main_function_params);
  390. else
  391. return std::move(main_function_params);
  392. }
  393. bool ElectronMainDelegate::ShouldCreateFeatureList() {
  394. return false;
  395. }
  396. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  397. return false;
  398. }
  399. #if defined(OS_LINUX)
  400. void ElectronMainDelegate::ZygoteForked() {
  401. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  402. // this up for the browser process in a different manner.
  403. ElectronCrashReporterClient::Create();
  404. const base::CommandLine* command_line =
  405. base::CommandLine::ForCurrentProcess();
  406. std::string process_type =
  407. command_line->GetSwitchValueASCII(::switches::kProcessType);
  408. if (crash_reporter::IsCrashpadEnabled()) {
  409. if (command_line->HasSwitch(
  410. crash_reporter::switches::kCrashpadHandlerPid)) {
  411. crash_reporter::InitializeCrashpad(false, process_type);
  412. crash_reporter::SetFirstChanceExceptionHandler(
  413. v8::TryHandleWebAssemblyTrapPosix);
  414. }
  415. } else {
  416. breakpad::InitCrashReporter(process_type);
  417. }
  418. // Reset the command line for the newly spawned process.
  419. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  420. }
  421. #endif // defined(OS_LINUX)
  422. } // namespace electron