electron_main_delegate.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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/command_line.h"
  9. #include "base/debug/stack_trace.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 "components/content_settings/core/common/content_settings_pattern.h"
  18. #include "content/public/common/content_switches.h"
  19. #include "electron/buildflags/buildflags.h"
  20. #include "extensions/common/constants.h"
  21. #include "ipc/ipc_buildflags.h"
  22. #include "services/service_manager/embedder/switches.h"
  23. #include "services/service_manager/sandbox/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/electron_paths.h"
  31. #include "shell/common/options_switches.h"
  32. #include "shell/renderer/electron_renderer_client.h"
  33. #include "shell/renderer/electron_sandboxed_renderer_client.h"
  34. #include "shell/utility/electron_content_utility_client.h"
  35. #include "ui/base/resource/resource_bundle.h"
  36. #include "ui/base/ui_base_switches.h"
  37. #if defined(OS_MACOSX)
  38. #include "shell/app/electron_main_delegate_mac.h"
  39. #endif
  40. #if defined(OS_WIN)
  41. #include "base/win/win_util.h"
  42. #include "chrome/child/v8_crashpad_support_win.h"
  43. #endif
  44. #if defined(OS_LINUX)
  45. #include "components/crash/core/app/breakpad_linux.h"
  46. #include "v8/include/v8-wasm-trap-handler-posix.h"
  47. #include "v8/include/v8.h"
  48. #endif
  49. #if !defined(MAS_BUILD)
  50. #include "components/crash/core/app/crashpad.h" // nogncheck
  51. #include "components/crash/core/common/crash_key.h"
  52. #include "components/crash/core/common/crash_keys.h"
  53. #include "shell/app/electron_crash_reporter_client.h"
  54. #include "shell/browser/api/electron_api_crash_reporter.h"
  55. #include "shell/common/crash_keys.h"
  56. #endif
  57. namespace electron {
  58. namespace {
  59. const char* kRelauncherProcess = "relauncher";
  60. bool IsBrowserProcess(base::CommandLine* cmd) {
  61. std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType);
  62. return process_type.empty();
  63. }
  64. bool IsSandboxEnabled(base::CommandLine* command_line) {
  65. return command_line->HasSwitch(switches::kEnableSandbox) ||
  66. !command_line->HasSwitch(service_manager::switches::kNoSandbox);
  67. }
  68. // Returns true if this subprocess type needs the ResourceBundle initialized
  69. // and resources loaded.
  70. bool SubprocessNeedsResourceBundle(const std::string& process_type) {
  71. return
  72. #if defined(OS_LINUX)
  73. // The zygote process opens the resources for the renderers.
  74. process_type == service_manager::switches::kZygoteProcess ||
  75. #endif
  76. #if defined(OS_MACOSX)
  77. // Mac needs them too for scrollbar related images and for sandbox
  78. // profiles.
  79. process_type == ::switches::kPpapiPluginProcess ||
  80. process_type == ::switches::kPpapiBrokerProcess ||
  81. process_type == ::switches::kGpuProcess ||
  82. #endif
  83. process_type == ::switches::kRendererProcess ||
  84. process_type == ::switches::kUtilityProcess;
  85. }
  86. #if defined(OS_WIN)
  87. void InvalidParameterHandler(const wchar_t*,
  88. const wchar_t*,
  89. const wchar_t*,
  90. unsigned int,
  91. uintptr_t) {
  92. // noop.
  93. }
  94. #endif
  95. // TODO(nornagon): move path provider overriding to its own file in
  96. // shell/common
  97. bool GetDefaultCrashDumpsPath(base::FilePath* path) {
  98. base::FilePath cur;
  99. if (!base::PathService::Get(DIR_USER_DATA, &cur))
  100. return false;
  101. #if defined(OS_MACOSX) || defined(OS_WIN)
  102. cur = cur.Append(FILE_PATH_LITERAL("Crashpad"));
  103. #else
  104. cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
  105. #endif
  106. // TODO(bauerb): http://crbug.com/259796
  107. base::ThreadRestrictions::ScopedAllowIO allow_io;
  108. if (!base::PathExists(cur) && !base::CreateDirectory(cur))
  109. return false;
  110. *path = cur;
  111. return true;
  112. }
  113. bool ElectronPathProvider(int key, base::FilePath* path) {
  114. if (key == DIR_CRASH_DUMPS) {
  115. return GetDefaultCrashDumpsPath(path);
  116. }
  117. return false;
  118. }
  119. void RegisterPathProvider() {
  120. base::PathService::RegisterProvider(ElectronPathProvider, PATH_START,
  121. PATH_END);
  122. }
  123. } // namespace
  124. std::string LoadResourceBundle(const std::string& locale) {
  125. const bool initialized = ui::ResourceBundle::HasSharedInstance();
  126. DCHECK(!initialized);
  127. // Load other resource files.
  128. base::FilePath pak_dir;
  129. #if defined(OS_MACOSX)
  130. pak_dir =
  131. base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
  132. #else
  133. base::PathService::Get(base::DIR_MODULE, &pak_dir);
  134. #endif
  135. std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
  136. locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
  137. ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  138. bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")),
  139. ui::SCALE_FACTOR_NONE);
  140. return loaded_locale;
  141. }
  142. ElectronMainDelegate::ElectronMainDelegate() = default;
  143. ElectronMainDelegate::~ElectronMainDelegate() = default;
  144. const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = {
  145. extensions::kExtensionScheme};
  146. const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize =
  147. base::size(kNonWildcardDomainNonPortSchemes);
  148. bool ElectronMainDelegate::BasicStartupComplete(int* exit_code) {
  149. auto* command_line = base::CommandLine::ForCurrentProcess();
  150. logging::LoggingSettings settings;
  151. #if defined(OS_WIN)
  152. v8_crashpad_support::SetUp();
  153. // On Windows the terminal returns immediately, so we add a new line to
  154. // prevent output in the same line as the prompt.
  155. if (IsBrowserProcess(command_line))
  156. std::wcout << std::endl;
  157. #if defined(DEBUG)
  158. // Print logging to debug.log on Windows
  159. settings.logging_dest = logging::LOG_TO_ALL;
  160. base::FilePath log_filename;
  161. base::PathService::Get(base::DIR_EXE, &log_filename);
  162. log_filename = log_filename.AppendASCII("debug.log");
  163. settings.log_file_path = log_filename.value().c_str();
  164. settings.lock_log = logging::LOCK_LOG_FILE;
  165. settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  166. #else
  167. settings.logging_dest =
  168. logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
  169. #endif // defined(DEBUG)
  170. #else // defined(OS_WIN)
  171. settings.logging_dest =
  172. logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
  173. #endif // !defined(OS_WIN)
  174. // Only enable logging when --enable-logging is specified.
  175. auto env = base::Environment::Create();
  176. if (!command_line->HasSwitch(::switches::kEnableLogging) &&
  177. !env->HasVar("ELECTRON_ENABLE_LOGGING")) {
  178. settings.logging_dest = logging::LOG_NONE;
  179. logging::SetMinLogLevel(logging::LOG_NUM_SEVERITIES);
  180. }
  181. logging::InitLogging(settings);
  182. // Logging with pid and timestamp.
  183. logging::SetLogItems(true, false, true, false);
  184. // Enable convient stack printing. This is enabled by default in non-official
  185. // builds.
  186. if (env->HasVar("ELECTRON_ENABLE_STACK_DUMPING"))
  187. base::debug::EnableInProcessStackDumping();
  188. if (env->HasVar("ELECTRON_DISABLE_SANDBOX"))
  189. command_line->AppendSwitch(service_manager::switches::kNoSandbox);
  190. tracing_sampler_profiler_ =
  191. tracing::TracingSamplerProfiler::CreateOnMainThread();
  192. chrome::RegisterPathProvider();
  193. electron::RegisterPathProvider();
  194. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  195. ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes(
  196. kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize);
  197. #endif
  198. #if defined(OS_MACOSX)
  199. OverrideChildProcessPath();
  200. OverrideFrameworkBundlePath();
  201. SetUpBundleOverrides();
  202. #endif
  203. #if defined(OS_WIN)
  204. // Ignore invalid parameter errors.
  205. _set_invalid_parameter_handler(InvalidParameterHandler);
  206. // Disable the ActiveVerifier, which is used by Chrome to track possible
  207. // bugs, but no use in Electron.
  208. base::win::DisableHandleVerifier();
  209. if (IsBrowserProcess(command_line))
  210. base::win::PinUser32();
  211. #endif
  212. #if defined(OS_LINUX)
  213. // Check for --no-sandbox parameter when running as root.
  214. if (getuid() == 0 && IsSandboxEnabled(command_line))
  215. LOG(FATAL) << "Running as root without --"
  216. << service_manager::switches::kNoSandbox
  217. << " is not supported. See https://crbug.com/638180.";
  218. #endif
  219. #if defined(MAS_BUILD)
  220. // In MAS build we are using --disable-remote-core-animation.
  221. //
  222. // According to ccameron:
  223. // If you're running with --disable-remote-core-animation, you may want to
  224. // also run with --disable-gpu-memory-buffer-compositor-resources as well.
  225. // That flag makes it so we use regular GL textures instead of IOSurfaces
  226. // for compositor resources. IOSurfaces are very heavyweight to
  227. // create/destroy, but they can be displayed directly by CoreAnimation (and
  228. // --disable-remote-core-animation makes it so we don't use this property,
  229. // so they're just heavyweight with no upside).
  230. command_line->AppendSwitch(
  231. ::switches::kDisableGpuMemoryBufferCompositorResources);
  232. #endif
  233. content_client_ = std::make_unique<ElectronContentClient>();
  234. SetContentClient(content_client_.get());
  235. return false;
  236. }
  237. void ElectronMainDelegate::PreSandboxStartup() {
  238. auto* command_line = base::CommandLine::ForCurrentProcess();
  239. std::string process_type =
  240. command_line->GetSwitchValueASCII(::switches::kProcessType);
  241. #if !defined(MAS_BUILD)
  242. crash_reporter::InitializeCrashKeys();
  243. #endif
  244. // Initialize ResourceBundle which handles files loaded from external
  245. // sources. The language should have been passed in to us from the
  246. // browser process as a command line flag.
  247. if (SubprocessNeedsResourceBundle(process_type)) {
  248. std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
  249. LoadResourceBundle(locale);
  250. }
  251. #if defined(OS_WIN) || (defined(OS_MACOSX) && !defined(MAS_BUILD))
  252. // In the main process, we wait for JS to call crashReporter.start() before
  253. // initializing crashpad. If we're in the renderer, we want to initialize it
  254. // immediately at boot.
  255. if (!process_type.empty()) {
  256. ElectronCrashReporterClient::Create();
  257. crash_reporter::InitializeCrashpad(false, process_type);
  258. }
  259. #endif
  260. #if defined(OS_LINUX)
  261. if (process_type != service_manager::switches::kZygoteProcess &&
  262. !process_type.empty()) {
  263. ElectronCrashReporterClient::Create();
  264. breakpad::InitCrashReporter(process_type);
  265. }
  266. #endif
  267. #if !defined(MAS_BUILD)
  268. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  269. crash_keys::SetPlatformCrashKey();
  270. #endif
  271. if (IsBrowserProcess(command_line)) {
  272. // Only append arguments for browser process.
  273. // Allow file:// URIs to read other file:// URIs by default.
  274. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
  275. #if defined(OS_MACOSX)
  276. // Enable AVFoundation.
  277. command_line->AppendSwitch("enable-avfoundation");
  278. #endif
  279. }
  280. }
  281. void ElectronMainDelegate::PreCreateMainMessageLoop() {
  282. // This is initialized early because the service manager reads some feature
  283. // flags and we need to make sure the feature list is initialized before the
  284. // service manager reads the features.
  285. InitializeFeatureList();
  286. #if defined(OS_MACOSX)
  287. RegisterAtomCrApp();
  288. #endif
  289. }
  290. content::ContentBrowserClient*
  291. ElectronMainDelegate::CreateContentBrowserClient() {
  292. browser_client_ = std::make_unique<ElectronBrowserClient>();
  293. return browser_client_.get();
  294. }
  295. content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() {
  296. gpu_client_ = std::make_unique<ElectronGpuClient>();
  297. return gpu_client_.get();
  298. }
  299. content::ContentRendererClient*
  300. ElectronMainDelegate::CreateContentRendererClient() {
  301. auto* command_line = base::CommandLine::ForCurrentProcess();
  302. if (IsSandboxEnabled(command_line)) {
  303. renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
  304. } else {
  305. renderer_client_ = std::make_unique<ElectronRendererClient>();
  306. }
  307. return renderer_client_.get();
  308. }
  309. content::ContentUtilityClient*
  310. ElectronMainDelegate::CreateContentUtilityClient() {
  311. utility_client_ = std::make_unique<ElectronContentUtilityClient>();
  312. return utility_client_.get();
  313. }
  314. int ElectronMainDelegate::RunProcess(
  315. const std::string& process_type,
  316. const content::MainFunctionParams& main_function_params) {
  317. if (process_type == kRelauncherProcess)
  318. return relauncher::RelauncherMain(main_function_params);
  319. else
  320. return -1;
  321. }
  322. bool ElectronMainDelegate::ShouldCreateFeatureList() {
  323. return false;
  324. }
  325. bool ElectronMainDelegate::ShouldLockSchemeRegistry() {
  326. return false;
  327. }
  328. #if defined(OS_LINUX)
  329. void ElectronMainDelegate::ZygoteForked() {
  330. // Needs to be called after we have DIR_USER_DATA. BrowserMain sets
  331. // this up for the browser process in a different manner.
  332. ElectronCrashReporterClient::Create();
  333. const base::CommandLine* command_line =
  334. base::CommandLine::ForCurrentProcess();
  335. std::string process_type =
  336. command_line->GetSwitchValueASCII(::switches::kProcessType);
  337. breakpad::InitCrashReporter(process_type);
  338. // Reset the command line for the newly spawned process.
  339. crash_keys::SetCrashKeysFromCommandLine(*command_line);
  340. }
  341. #endif // defined(OS_LINUX)
  342. } // namespace electron