node_bindings.cc 15 KB

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