node_bindings.cc 12 KB

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