node_bindings.cc 15 KB

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