node_bindings.cc 17 KB

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