node_bindings.cc 12 KB

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