node_bindings.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 <string>
  7. #include <vector>
  8. #include "atom/common/api/event_emitter_caller.h"
  9. #include "atom/common/api/locker.h"
  10. #include "atom/common/atom_command_line.h"
  11. #include "atom/common/native_mate_converters/file_path_converter.h"
  12. #include "base/base_paths.h"
  13. #include "base/command_line.h"
  14. #include "base/environment.h"
  15. #include "base/files/file_path.h"
  16. #include "base/path_service.h"
  17. #include "base/run_loop.h"
  18. #include "base/strings/utf_string_conversions.h"
  19. #include "base/threading/thread_task_runner_handle.h"
  20. #include "base/trace_event/trace_event.h"
  21. #include "content/public/browser/browser_thread.h"
  22. #include "content/public/common/content_paths.h"
  23. #include "native_mate/dictionary.h"
  24. #include "atom/common/node_includes.h"
  25. #define ELECTRON_BUILTIN_MODULES(V) \
  26. V(atom_browser_app) \
  27. V(atom_browser_auto_updater) \
  28. V(atom_browser_browser_view) \
  29. V(atom_browser_content_tracing) \
  30. V(atom_browser_debugger) \
  31. V(atom_browser_desktop_capturer) \
  32. V(atom_browser_dialog) \
  33. V(atom_browser_download_item) \
  34. V(atom_browser_global_shortcut) \
  35. V(atom_browser_in_app_purchase) \
  36. V(atom_browser_menu) \
  37. V(atom_browser_net) \
  38. V(atom_browser_power_monitor) \
  39. V(atom_browser_power_save_blocker) \
  40. V(atom_browser_protocol) \
  41. V(atom_browser_render_process_preferences) \
  42. V(atom_browser_session) \
  43. V(atom_browser_system_preferences) \
  44. V(atom_browser_top_level_window) \
  45. V(atom_browser_tray) \
  46. V(atom_browser_web_contents) \
  47. V(atom_browser_web_contents_view) \
  48. V(atom_browser_view) \
  49. V(atom_browser_web_view_manager) \
  50. V(atom_browser_window) \
  51. V(atom_common_asar) \
  52. V(atom_common_clipboard) \
  53. V(atom_common_crash_reporter) \
  54. V(atom_common_features) \
  55. V(atom_common_native_image) \
  56. V(atom_common_notification) \
  57. V(atom_common_screen) \
  58. V(atom_common_shell) \
  59. V(atom_common_v8_util) \
  60. V(atom_renderer_ipc) \
  61. V(atom_renderer_web_frame)
  62. #define ELECTRON_VIEW_MODULES(V) \
  63. V(atom_browser_box_layout) \
  64. V(atom_browser_layout_manager)
  65. // This is used to load built-in modules. Instead of using
  66. // __attribute__((constructor)), we call the _register_<modname>
  67. // function for each built-in modules explicitly. This is only
  68. // forward declaration. The definitions are in each module's
  69. // implementation when calling the NODE_BUILTIN_MODULE_CONTEXT_AWARE.
  70. #define V(modname) void _register_##modname();
  71. ELECTRON_BUILTIN_MODULES(V)
  72. #if defined(ENABLE_VIEW_API)
  73. ELECTRON_VIEW_MODULES(V)
  74. #endif
  75. #undef V
  76. namespace {
  77. void stop_and_close_uv_loop(uv_loop_t* loop) {
  78. // Close any active handles
  79. uv_stop(loop);
  80. uv_walk(loop,
  81. [](uv_handle_t* handle, void*) {
  82. if (!uv_is_closing(handle)) {
  83. uv_close(handle, nullptr);
  84. }
  85. },
  86. nullptr);
  87. // Run the loop to let it finish all the closing handles
  88. // NB: after uv_stop(), uv_run(UV_RUN_DEFAULT) returns 0 when that's done
  89. for (;;)
  90. if (!uv_run(loop, UV_RUN_DEFAULT))
  91. break;
  92. DCHECK(!uv_loop_alive(loop));
  93. uv_loop_close(loop);
  94. }
  95. } // namespace
  96. namespace atom {
  97. namespace {
  98. // Convert the given vector to an array of C-strings. The strings in the
  99. // returned vector are only guaranteed valid so long as the vector of strings
  100. // is not modified.
  101. std::unique_ptr<const char* []> StringVectorToArgArray(
  102. const std::vector<std::string>& vector) {
  103. std::unique_ptr<const char* []> array(new const char*[vector.size()]);
  104. for (size_t i = 0; i < vector.size(); ++i) {
  105. array[i] = vector[i].c_str();
  106. }
  107. return array;
  108. }
  109. base::FilePath GetResourcesPath(bool is_browser) {
  110. auto* command_line = base::CommandLine::ForCurrentProcess();
  111. base::FilePath exec_path(command_line->GetProgram());
  112. PathService::Get(base::FILE_EXE, &exec_path);
  113. base::FilePath resources_path =
  114. #if defined(OS_MACOSX)
  115. is_browser
  116. ? exec_path.DirName().DirName().Append("Resources")
  117. : exec_path.DirName().DirName().DirName().DirName().DirName().Append(
  118. "Resources");
  119. #else
  120. exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
  121. #endif
  122. return resources_path;
  123. }
  124. } // namespace
  125. NodeBindings::NodeBindings(BrowserEnvironment browser_env)
  126. : browser_env_(browser_env), weak_factory_(this) {
  127. if (browser_env == WORKER) {
  128. uv_loop_init(&worker_loop_);
  129. uv_loop_ = &worker_loop_;
  130. } else {
  131. uv_loop_ = uv_default_loop();
  132. }
  133. }
  134. NodeBindings::~NodeBindings() {
  135. // Quit the embed thread.
  136. embed_closed_ = true;
  137. uv_sem_post(&embed_sem_);
  138. WakeupEmbedThread();
  139. // Wait for everything to be done.
  140. uv_thread_join(&embed_thread_);
  141. // Clear uv.
  142. uv_sem_destroy(&embed_sem_);
  143. uv_close(reinterpret_cast<uv_handle_t*>(&dummy_uv_handle_), nullptr);
  144. // Clean up worker loop
  145. if (uv_loop_ == &worker_loop_)
  146. stop_and_close_uv_loop(uv_loop_);
  147. }
  148. void NodeBindings::RegisterBuiltinModules() {
  149. #define V(modname) _register_##modname();
  150. ELECTRON_BUILTIN_MODULES(V)
  151. #if defined(ENABLE_VIEW_API)
  152. ELECTRON_VIEW_MODULES(V)
  153. #endif
  154. #undef V
  155. }
  156. void NodeBindings::Initialize() {
  157. // Open node's error reporting system for browser process.
  158. node::g_standalone_mode = browser_env_ == BROWSER;
  159. node::g_upstream_node_mode = false;
  160. #if defined(OS_LINUX)
  161. // Get real command line in renderer process forked by zygote.
  162. if (browser_env_ != BROWSER)
  163. AtomCommandLine::InitializeFromCommandLine();
  164. #endif
  165. // Explicitly register electron's builtin modules.
  166. RegisterBuiltinModules();
  167. // Init node.
  168. // (we assume node::Init would not modify the parameters under embedded mode).
  169. node::Init(nullptr, nullptr, nullptr, nullptr);
  170. #if defined(OS_WIN)
  171. // uv_init overrides error mode to suppress the default crash dialog, bring
  172. // it back if user wants to show it.
  173. std::unique_ptr<base::Environment> env(base::Environment::Create());
  174. if (browser_env_ == BROWSER || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
  175. SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
  176. #endif
  177. }
  178. node::Environment* NodeBindings::CreateEnvironment(
  179. v8::Handle<v8::Context> context,
  180. node::MultiIsolatePlatform* platform) {
  181. #if defined(OS_WIN)
  182. auto& atom_args = AtomCommandLine::argv();
  183. std::vector<std::string> args(atom_args.size());
  184. std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(),
  185. [](auto& a) { return base::WideToUTF8(a); });
  186. #else
  187. auto args = AtomCommandLine::argv();
  188. #endif
  189. // Feed node the path to initialization script.
  190. base::FilePath::StringType process_type;
  191. switch (browser_env_) {
  192. case BROWSER:
  193. process_type = FILE_PATH_LITERAL("browser");
  194. break;
  195. case RENDERER:
  196. process_type = FILE_PATH_LITERAL("renderer");
  197. break;
  198. case WORKER:
  199. process_type = FILE_PATH_LITERAL("worker");
  200. break;
  201. }
  202. base::FilePath resources_path = GetResourcesPath(browser_env_ == BROWSER);
  203. base::FilePath script_path =
  204. resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
  205. .Append(process_type)
  206. .Append(FILE_PATH_LITERAL("init.js"));
  207. args.insert(args.begin() + 1, script_path.AsUTF8Unsafe());
  208. std::unique_ptr<const char* []> c_argv = StringVectorToArgArray(args);
  209. node::Environment* env = node::CreateEnvironment(
  210. node::CreateIsolateData(context->GetIsolate(), uv_loop_, platform),
  211. context, args.size(), c_argv.get(), 0, nullptr);
  212. if (browser_env_ == BROWSER) {
  213. // SetAutorunMicrotasks is no longer called in node::CreateEnvironment
  214. // so instead call it here to match expected node behavior
  215. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  216. } else {
  217. // Node uses the deprecated SetAutorunMicrotasks(false) mode, we should
  218. // switch to use the scoped policy to match blink's behavior.
  219. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
  220. }
  221. mate::Dictionary process(context->GetIsolate(), env->process_object());
  222. process.Set("type", process_type);
  223. process.Set("resourcesPath", resources_path);
  224. // Do not set DOM globals for renderer process.
  225. if (browser_env_ != BROWSER)
  226. process.Set("_noBrowserGlobals", resources_path);
  227. // The path to helper app.
  228. base::FilePath helper_exec_path;
  229. PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
  230. process.Set("helperExecPath", helper_exec_path);
  231. return env;
  232. }
  233. void NodeBindings::LoadEnvironment(node::Environment* env) {
  234. node::LoadEnvironment(env);
  235. mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
  236. }
  237. void NodeBindings::PrepareMessageLoop() {
  238. // Add dummy handle for libuv, otherwise libuv would quit when there is
  239. // nothing to do.
  240. uv_async_init(uv_loop_, &dummy_uv_handle_, nullptr);
  241. // Start worker that will interrupt main loop when having uv events.
  242. uv_sem_init(&embed_sem_, 0);
  243. uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
  244. }
  245. void NodeBindings::RunMessageLoop() {
  246. // The MessageLoop should have been created, remember the one in main thread.
  247. task_runner_ = base::ThreadTaskRunnerHandle::Get();
  248. // Run uv loop for once to give the uv__io_poll a chance to add all events.
  249. UvRunOnce();
  250. }
  251. void NodeBindings::UvRunOnce() {
  252. node::Environment* env = uv_env();
  253. // When doing navigation without restarting renderer process, it may happen
  254. // that the node environment is destroyed but the message loop is still there.
  255. // In this case we should not run uv loop.
  256. if (!env)
  257. return;
  258. // Use Locker in browser process.
  259. mate::Locker locker(env->isolate());
  260. v8::HandleScope handle_scope(env->isolate());
  261. // Enter node context while dealing with uv events.
  262. v8::Context::Scope context_scope(env->context());
  263. // Perform microtask checkpoint after running JavaScript.
  264. v8::MicrotasksScope script_scope(env->isolate(),
  265. v8::MicrotasksScope::kRunMicrotasks);
  266. if (browser_env_ != BROWSER)
  267. TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");
  268. // Deal with uv events.
  269. int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
  270. if (browser_env_ != BROWSER)
  271. TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
  272. if (r == 0)
  273. base::RunLoop().QuitWhenIdle(); // Quit from uv.
  274. // Tell the worker thread to continue polling.
  275. uv_sem_post(&embed_sem_);
  276. }
  277. void NodeBindings::WakeupMainThread() {
  278. DCHECK(task_runner_);
  279. task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce,
  280. weak_factory_.GetWeakPtr()));
  281. }
  282. void NodeBindings::WakeupEmbedThread() {
  283. uv_async_send(&dummy_uv_handle_);
  284. }
  285. // static
  286. void NodeBindings::EmbedThreadRunner(void* arg) {
  287. NodeBindings* self = static_cast<NodeBindings*>(arg);
  288. while (true) {
  289. // Wait for the main loop to deal with events.
  290. uv_sem_wait(&self->embed_sem_);
  291. if (self->embed_closed_)
  292. break;
  293. // Wait for something to happen in uv loop.
  294. // Note that the PollEvents() is implemented by derived classes, so when
  295. // this class is being destructed the PollEvents() would not be available
  296. // anymore. Because of it we must make sure we only invoke PollEvents()
  297. // when this class is alive.
  298. self->PollEvents();
  299. if (self->embed_closed_)
  300. break;
  301. // Deal with event in main thread.
  302. self->WakeupMainThread();
  303. }
  304. }
  305. } // namespace atom