node_bindings.cc 14 KB

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