node_bindings.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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/common/node_bindings.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/base_paths.h"
  12. #include "base/command_line.h"
  13. #include "base/environment.h"
  14. #include "base/path_service.h"
  15. #include "base/run_loop.h"
  16. #include "base/strings/string_split.h"
  17. #include "base/strings/utf_string_conversions.h"
  18. #include "base/threading/thread_task_runner_handle.h"
  19. #include "base/trace_event/trace_event.h"
  20. #include "content/public/browser/browser_thread.h"
  21. #include "content/public/common/content_paths.h"
  22. #include "electron/buildflags/buildflags.h"
  23. #include "native_mate/microtasks_scope.h"
  24. #include "shell/common/api/locker.h"
  25. #include "shell/common/electron_command_line.h"
  26. #include "shell/common/gin_converters/file_path_converter.h"
  27. #include "shell/common/gin_helper/dictionary.h"
  28. #include "shell/common/gin_helper/event_emitter_caller.h"
  29. #include "shell/common/mac/main_application_bundle.h"
  30. #include "shell/common/node_includes.h"
  31. #define ELECTRON_BUILTIN_MODULES(V) \
  32. V(atom_browser_app) \
  33. V(atom_browser_auto_updater) \
  34. V(atom_browser_browser_view) \
  35. V(atom_browser_content_tracing) \
  36. V(atom_browser_debugger) \
  37. V(atom_browser_dialog) \
  38. V(atom_browser_download_item) \
  39. V(atom_browser_event) \
  40. V(atom_browser_global_shortcut) \
  41. V(atom_browser_in_app_purchase) \
  42. V(atom_browser_menu) \
  43. V(atom_browser_net) \
  44. V(atom_browser_power_monitor) \
  45. V(atom_browser_power_save_blocker) \
  46. V(atom_browser_protocol) \
  47. V(atom_browser_session) \
  48. V(atom_browser_system_preferences) \
  49. V(atom_browser_top_level_window) \
  50. V(atom_browser_tray) \
  51. V(atom_browser_web_contents) \
  52. V(atom_browser_web_contents_view) \
  53. V(atom_browser_view) \
  54. V(atom_browser_web_view_manager) \
  55. V(atom_browser_window) \
  56. V(atom_common_asar) \
  57. V(atom_common_clipboard) \
  58. V(atom_common_command_line) \
  59. V(atom_common_crash_reporter) \
  60. V(atom_common_features) \
  61. V(atom_common_native_image) \
  62. V(atom_common_native_theme) \
  63. V(atom_common_notification) \
  64. V(atom_common_screen) \
  65. V(atom_common_shell) \
  66. V(atom_common_v8_util) \
  67. V(atom_renderer_context_bridge) \
  68. V(atom_renderer_ipc) \
  69. V(atom_renderer_web_frame)
  70. #define ELECTRON_VIEW_MODULES(V) \
  71. V(atom_browser_box_layout) \
  72. V(atom_browser_button) \
  73. V(atom_browser_label_button) \
  74. V(atom_browser_layout_manager) \
  75. V(atom_browser_md_text_button) \
  76. V(atom_browser_resize_area) \
  77. V(atom_browser_text_field)
  78. #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(atom_browser_desktop_capturer)
  79. // This is used to load built-in modules. Instead of using
  80. // __attribute__((constructor)), we call the _register_<modname>
  81. // function for each built-in modules explicitly. This is only
  82. // forward declaration. The definitions are in each module's
  83. // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE.
  84. #define V(modname) void _register_##modname();
  85. ELECTRON_BUILTIN_MODULES(V)
  86. #if BUILDFLAG(ENABLE_VIEW_API)
  87. ELECTRON_VIEW_MODULES(V)
  88. #endif
  89. #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
  90. ELECTRON_DESKTOP_CAPTURER_MODULE(V)
  91. #endif
  92. #undef V
  93. namespace {
  94. void stop_and_close_uv_loop(uv_loop_t* loop) {
  95. uv_stop(loop);
  96. int error = uv_loop_close(loop);
  97. while (error) {
  98. uv_run(loop, UV_RUN_DEFAULT);
  99. uv_stop(loop);
  100. uv_walk(
  101. loop,
  102. [](uv_handle_t* handle, void*) {
  103. if (!uv_is_closing(handle)) {
  104. uv_close(handle, nullptr);
  105. }
  106. },
  107. nullptr);
  108. uv_run(loop, UV_RUN_DEFAULT);
  109. error = uv_loop_close(loop);
  110. }
  111. DCHECK_EQ(error, 0);
  112. }
  113. bool g_is_initialized = false;
  114. bool IsPackagedApp() {
  115. base::FilePath exe_path;
  116. base::PathService::Get(base::FILE_EXE, &exe_path);
  117. base::FilePath::StringType base_name =
  118. base::ToLowerASCII(exe_path.BaseName().value());
  119. #if defined(OS_WIN)
  120. return base_name != FILE_PATH_LITERAL("electron.exe");
  121. #else
  122. return base_name != FILE_PATH_LITERAL("electron");
  123. #endif
  124. }
  125. // Initialize NODE_OPTIONS to pass to Node.js
  126. void SetNodeOptions(base::Environment* env) {
  127. // Options that are unilaterally disallowed
  128. const std::set<std::string> disallowed = {
  129. "--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
  130. "--force-fips", "--enable-fips"};
  131. // Subset of options allowed in packaged apps
  132. const std::set<std::string> allowed_in_packaged = {"--max-http-header-size",
  133. "--http-parser"};
  134. if (env->HasVar("NODE_OPTIONS")) {
  135. std::string options;
  136. env->GetVar("NODE_OPTIONS", &options);
  137. std::vector<std::string> parts = base::SplitString(
  138. options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  139. bool is_packaged_app = IsPackagedApp();
  140. for (const auto& part : parts) {
  141. // Strip off values passed to individual NODE_OPTIONs
  142. std::string option = part.substr(0, part.find("="));
  143. if (is_packaged_app &&
  144. allowed_in_packaged.find(option) == allowed_in_packaged.end()) {
  145. // Explicitly disallow majority of NODE_OPTIONS in packaged apps
  146. LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps."
  147. << " See documentation for more details.";
  148. options.erase(options.find(option), part.length());
  149. } else if (disallowed.find(option) != disallowed.end()) {
  150. // Remove NODE_OPTIONS specifically disallowed for use in Node.js
  151. // through Electron owing to constraints like BoringSSL.
  152. LOG(ERROR) << "The NODE_OPTION " << option
  153. << " is not supported in Electron";
  154. options.erase(options.find(option), part.length());
  155. }
  156. }
  157. // overwrite new NODE_OPTIONS without unsupported variables
  158. env->SetVar("NODE_OPTIONS", options);
  159. }
  160. }
  161. } // namespace
  162. namespace electron {
  163. namespace {
  164. // Convert the given vector to an array of C-strings. The strings in the
  165. // returned vector are only guaranteed valid so long as the vector of strings
  166. // is not modified.
  167. std::unique_ptr<const char* []> StringVectorToArgArray(
  168. const std::vector<std::string>& vector) {
  169. std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
  170. for (size_t i = 0; i < vector.size(); ++i) {
  171. array[i] = vector[i].c_str();
  172. }
  173. return array;
  174. }
  175. base::FilePath GetResourcesPath() {
  176. #if defined(OS_MACOSX)
  177. return MainApplicationBundlePath().Append("Contents").Append("Resources");
  178. #else
  179. auto* command_line = base::CommandLine::ForCurrentProcess();
  180. base::FilePath exec_path(command_line->GetProgram());
  181. base::PathService::Get(base::FILE_EXE, &exec_path);
  182. return exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
  183. #endif
  184. }
  185. } // namespace
  186. NodeBindings::NodeBindings(BrowserEnvironment browser_env)
  187. : browser_env_(browser_env), weak_factory_(this) {
  188. if (browser_env == BrowserEnvironment::WORKER) {
  189. uv_loop_init(&worker_loop_);
  190. uv_loop_ = &worker_loop_;
  191. } else {
  192. uv_loop_ = uv_default_loop();
  193. }
  194. }
  195. NodeBindings::~NodeBindings() {
  196. // Quit the embed thread.
  197. embed_closed_ = true;
  198. uv_sem_post(&embed_sem_);
  199. WakeupEmbedThread();
  200. // Wait for everything to be done.
  201. uv_thread_join(&embed_thread_);
  202. // Clear uv.
  203. uv_sem_destroy(&embed_sem_);
  204. uv_close(reinterpret_cast<uv_handle_t*>(&dummy_uv_handle_), nullptr);
  205. // Clean up worker loop
  206. if (in_worker_loop())
  207. stop_and_close_uv_loop(uv_loop_);
  208. }
  209. void NodeBindings::RegisterBuiltinModules() {
  210. #define V(modname) _register_##modname();
  211. ELECTRON_BUILTIN_MODULES(V)
  212. #if BUILDFLAG(ENABLE_VIEW_API)
  213. ELECTRON_VIEW_MODULES(V)
  214. #endif
  215. #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
  216. ELECTRON_DESKTOP_CAPTURER_MODULE(V)
  217. #endif
  218. #undef V
  219. }
  220. bool NodeBindings::IsInitialized() {
  221. return g_is_initialized;
  222. }
  223. void NodeBindings::Initialize() {
  224. TRACE_EVENT0("electron", "NodeBindings::Initialize");
  225. // Open node's error reporting system for browser process.
  226. node::g_standalone_mode = browser_env_ == BrowserEnvironment::BROWSER;
  227. node::g_upstream_node_mode = false;
  228. #if defined(OS_LINUX)
  229. // Get real command line in renderer process forked by zygote.
  230. if (browser_env_ != BrowserEnvironment::BROWSER)
  231. ElectronCommandLine::InitializeFromCommandLine();
  232. #endif
  233. // Explicitly register electron's builtin modules.
  234. RegisterBuiltinModules();
  235. // pass non-null program name to argv so it doesn't crash
  236. // trying to index into a nullptr
  237. int argc = 1;
  238. int exec_argc = 0;
  239. const char* prog_name = "electron";
  240. const char** argv = &prog_name;
  241. const char** exec_argv = nullptr;
  242. std::unique_ptr<base::Environment> env(base::Environment::Create());
  243. SetNodeOptions(env.get());
  244. // TODO(codebytere): this is going to be deprecated in the near future
  245. // in favor of Init(std::vector<std::string>* argv,
  246. // std::vector<std::string>* exec_argv)
  247. node::Init(&argc, argv, &exec_argc, &exec_argv);
  248. #if defined(OS_WIN)
  249. // uv_init overrides error mode to suppress the default crash dialog, bring
  250. // it back if user wants to show it.
  251. if (browser_env_ == BrowserEnvironment::BROWSER ||
  252. env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
  253. SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
  254. #endif
  255. g_is_initialized = true;
  256. }
  257. node::Environment* NodeBindings::CreateEnvironment(
  258. v8::Handle<v8::Context> context,
  259. node::MultiIsolatePlatform* platform) {
  260. #if defined(OS_WIN)
  261. auto& atom_args = ElectronCommandLine::argv();
  262. std::vector<std::string> args(atom_args.size());
  263. std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(),
  264. [](auto& a) { return base::WideToUTF8(a); });
  265. #else
  266. auto args = ElectronCommandLine::argv();
  267. #endif
  268. // Feed node the path to initialization script.
  269. std::string process_type;
  270. switch (browser_env_) {
  271. case BrowserEnvironment::BROWSER:
  272. process_type = "browser";
  273. break;
  274. case BrowserEnvironment::RENDERER:
  275. process_type = "renderer";
  276. break;
  277. case BrowserEnvironment::WORKER:
  278. process_type = "worker";
  279. break;
  280. }
  281. gin_helper::Dictionary global(context->GetIsolate(), context->Global());
  282. // Do not set DOM globals for renderer process.
  283. // We must set this before the node bootstrapper which is run inside
  284. // CreateEnvironment
  285. if (browser_env_ != BrowserEnvironment::BROWSER)
  286. global.Set("_noBrowserGlobals", true);
  287. base::FilePath resources_path = GetResourcesPath();
  288. std::string init_script = "electron/js2c/" + process_type + "_init";
  289. args.insert(args.begin() + 1, init_script);
  290. std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
  291. node::Environment* env;
  292. if (browser_env_ != BrowserEnvironment::BROWSER) {
  293. v8::TryCatch try_catch(context->GetIsolate());
  294. env = node::CreateEnvironment(
  295. node::CreateIsolateData(context->GetIsolate(), uv_loop_, platform),
  296. context, args.size(), c_argv.get(), 0, nullptr);
  297. DCHECK(env);
  298. // This will only be caught when something has gone terrible wrong as all
  299. // electron scripts are wrapped in a try {} catch {} in run-compiler.js
  300. if (try_catch.HasCaught()) {
  301. LOG(ERROR) << "Failed to initialize node environment in process: "
  302. << process_type;
  303. }
  304. } else {
  305. env = node::CreateEnvironment(
  306. node::CreateIsolateData(context->GetIsolate(), uv_loop_, platform),
  307. context, args.size(), c_argv.get(), 0, nullptr);
  308. DCHECK(env);
  309. }
  310. // Clean up the global _noBrowserGlobals that we unironically injected into
  311. // the global scope
  312. if (browser_env_ != BrowserEnvironment::BROWSER) {
  313. // We need to bootstrap the env in non-browser processes so that
  314. // _noBrowserGlobals is read correctly before we remove it
  315. global.Delete("_noBrowserGlobals");
  316. }
  317. if (browser_env_ == BrowserEnvironment::BROWSER) {
  318. // SetAutorunMicrotasks is no longer called in node::CreateEnvironment
  319. // so instead call it here to match expected node behavior
  320. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  321. } else {
  322. // Node uses the deprecated SetAutorunMicrotasks(false) mode, we should
  323. // switch to use the scoped policy to match blink's behavior.
  324. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
  325. }
  326. gin_helper::Dictionary process(context->GetIsolate(), env->process_object());
  327. process.SetReadOnly("type", process_type);
  328. process.Set("resourcesPath", resources_path);
  329. // The path to helper app.
  330. base::FilePath helper_exec_path;
  331. base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
  332. process.Set("helperExecPath", helper_exec_path);
  333. return env;
  334. }
  335. void NodeBindings::LoadEnvironment(node::Environment* env) {
  336. node::LoadEnvironment(env);
  337. gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded");
  338. }
  339. void NodeBindings::PrepareMessageLoop() {
  340. // Add dummy handle for libuv, otherwise libuv would quit when there is
  341. // nothing to do.
  342. uv_async_init(uv_loop_, &dummy_uv_handle_, nullptr);
  343. // Start worker that will interrupt main loop when having uv events.
  344. uv_sem_init(&embed_sem_, 0);
  345. uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
  346. }
  347. void NodeBindings::RunMessageLoop() {
  348. // The MessageLoop should have been created, remember the one in main thread.
  349. task_runner_ = base::ThreadTaskRunnerHandle::Get();
  350. // Run uv loop for once to give the uv__io_poll a chance to add all events.
  351. UvRunOnce();
  352. }
  353. void NodeBindings::UvRunOnce() {
  354. node::Environment* env = uv_env();
  355. // When doing navigation without restarting renderer process, it may happen
  356. // that the node environment is destroyed but the message loop is still there.
  357. // In this case we should not run uv loop.
  358. if (!env)
  359. return;
  360. // Use Locker in browser process.
  361. mate::Locker locker(env->isolate());
  362. v8::HandleScope handle_scope(env->isolate());
  363. // Enter node context while dealing with uv events.
  364. v8::Context::Scope context_scope(env->context());
  365. // Perform microtask checkpoint after running JavaScript.
  366. mate::MicrotasksScope microtasks_scope(env->isolate());
  367. if (browser_env_ != BrowserEnvironment::BROWSER)
  368. TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");
  369. // Deal with uv events.
  370. int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
  371. if (browser_env_ != BrowserEnvironment::BROWSER)
  372. TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
  373. if (r == 0)
  374. base::RunLoop().QuitWhenIdle(); // Quit from uv.
  375. // Tell the worker thread to continue polling.
  376. uv_sem_post(&embed_sem_);
  377. }
  378. void NodeBindings::WakeupMainThread() {
  379. DCHECK(task_runner_);
  380. task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce,
  381. weak_factory_.GetWeakPtr()));
  382. }
  383. void NodeBindings::WakeupEmbedThread() {
  384. if (!in_worker_loop())
  385. uv_async_send(&dummy_uv_handle_);
  386. }
  387. // static
  388. void NodeBindings::EmbedThreadRunner(void* arg) {
  389. NodeBindings* self = static_cast<NodeBindings*>(arg);
  390. while (true) {
  391. // Wait for the main loop to deal with events.
  392. uv_sem_wait(&self->embed_sem_);
  393. if (self->embed_closed_)
  394. break;
  395. // Wait for something to happen in uv loop.
  396. // Note that the PollEvents() is implemented by derived classes, so when
  397. // this class is being destructed the PollEvents() would not be available
  398. // anymore. Because of it we must make sure we only invoke PollEvents()
  399. // when this class is alive.
  400. self->PollEvents();
  401. if (self->embed_closed_)
  402. break;
  403. // Deal with event in main thread.
  404. self->WakeupMainThread();
  405. }
  406. }
  407. } // namespace electron