node_bindings.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 <string>
  6. #include <vector>
  7. #include "atom/common/api/event_emitter_caller.h"
  8. #include "atom/common/api/locker.h"
  9. #include "atom/common/atom_command_line.h"
  10. #include "atom/common/native_mate_converters/file_path_converter.h"
  11. #include "base/base_paths.h"
  12. #include "base/command_line.h"
  13. #include "base/environment.h"
  14. #include "base/files/file_path.h"
  15. #include "base/path_service.h"
  16. #include "base/run_loop.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "base/trace_event/trace_event.h"
  19. #include "content/public/browser/browser_thread.h"
  20. #include "content/public/common/content_paths.h"
  21. #include "native_mate/dictionary.h"
  22. #include "atom/common/node_includes.h"
  23. using content::BrowserThread;
  24. // Force all builtin modules to be referenced so they can actually run their
  25. // DSO constructors, see http://git.io/DRIqCg.
  26. #define REFERENCE_MODULE(name) \
  27. extern "C" void _register_ ## name(void); \
  28. void (*fp_register_ ## name)(void) = _register_ ## name
  29. // Electron's builtin modules.
  30. REFERENCE_MODULE(atom_browser_app);
  31. REFERENCE_MODULE(atom_browser_auto_updater);
  32. REFERENCE_MODULE(atom_browser_content_tracing);
  33. REFERENCE_MODULE(atom_browser_dialog);
  34. REFERENCE_MODULE(atom_browser_debugger);
  35. REFERENCE_MODULE(atom_browser_desktop_capturer);
  36. REFERENCE_MODULE(atom_browser_download_item);
  37. REFERENCE_MODULE(atom_browser_menu);
  38. REFERENCE_MODULE(atom_browser_net);
  39. REFERENCE_MODULE(atom_browser_power_monitor);
  40. REFERENCE_MODULE(atom_browser_power_save_blocker);
  41. REFERENCE_MODULE(atom_browser_protocol);
  42. REFERENCE_MODULE(atom_browser_global_shortcut);
  43. REFERENCE_MODULE(atom_browser_render_process_preferences);
  44. REFERENCE_MODULE(atom_browser_session);
  45. REFERENCE_MODULE(atom_browser_system_preferences);
  46. REFERENCE_MODULE(atom_browser_tray);
  47. REFERENCE_MODULE(atom_browser_web_contents);
  48. REFERENCE_MODULE(atom_browser_web_view_manager);
  49. REFERENCE_MODULE(atom_browser_window);
  50. REFERENCE_MODULE(atom_common_asar);
  51. REFERENCE_MODULE(atom_common_clipboard);
  52. REFERENCE_MODULE(atom_common_crash_reporter);
  53. REFERENCE_MODULE(atom_common_native_image);
  54. REFERENCE_MODULE(atom_common_screen);
  55. REFERENCE_MODULE(atom_common_shell);
  56. REFERENCE_MODULE(atom_common_v8_util);
  57. REFERENCE_MODULE(atom_renderer_ipc);
  58. REFERENCE_MODULE(atom_renderer_web_frame);
  59. #undef REFERENCE_MODULE
  60. namespace atom {
  61. namespace {
  62. // Convert the given vector to an array of C-strings. The strings in the
  63. // returned vector are only guaranteed valid so long as the vector of strings
  64. // is not modified.
  65. std::unique_ptr<const char*[]> StringVectorToArgArray(
  66. const std::vector<std::string>& vector) {
  67. std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
  68. for (size_t i = 0; i < vector.size(); ++i) {
  69. array[i] = vector[i].c_str();
  70. }
  71. return array;
  72. }
  73. base::FilePath GetResourcesPath(bool is_browser) {
  74. auto command_line = base::CommandLine::ForCurrentProcess();
  75. base::FilePath exec_path(command_line->GetProgram());
  76. PathService::Get(base::FILE_EXE, &exec_path);
  77. base::FilePath resources_path =
  78. #if defined(OS_MACOSX)
  79. is_browser ? exec_path.DirName().DirName().Append("Resources") :
  80. exec_path.DirName().DirName().DirName().DirName().DirName()
  81. .Append("Resources");
  82. #else
  83. exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
  84. #endif
  85. return resources_path;
  86. }
  87. } // namespace
  88. NodeBindings::NodeBindings(bool is_browser)
  89. : is_browser_(is_browser),
  90. uv_loop_(uv_default_loop()),
  91. embed_closed_(false),
  92. uv_env_(nullptr),
  93. weak_factory_(this) {
  94. }
  95. NodeBindings::~NodeBindings() {
  96. // Quit the embed thread.
  97. embed_closed_ = true;
  98. uv_sem_post(&embed_sem_);
  99. WakeupEmbedThread();
  100. // Wait for everything to be done.
  101. uv_thread_join(&embed_thread_);
  102. // Clear uv.
  103. uv_sem_destroy(&embed_sem_);
  104. }
  105. void NodeBindings::Initialize() {
  106. // Open node's error reporting system for browser process.
  107. node::g_standalone_mode = is_browser_;
  108. node::g_upstream_node_mode = false;
  109. #if defined(OS_LINUX)
  110. // Get real command line in renderer process forked by zygote.
  111. if (!is_browser_)
  112. AtomCommandLine::InitializeFromCommandLine();
  113. #endif
  114. // Init node.
  115. // (we assume node::Init would not modify the parameters under embedded mode).
  116. node::Init(nullptr, nullptr, nullptr, nullptr);
  117. #if defined(OS_WIN)
  118. // uv_init overrides error mode to suppress the default crash dialog, bring
  119. // it back if user wants to show it.
  120. std::unique_ptr<base::Environment> env(base::Environment::Create());
  121. if (is_browser_ || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
  122. SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
  123. #endif
  124. }
  125. node::Environment* NodeBindings::CreateEnvironment(
  126. v8::Handle<v8::Context> context) {
  127. auto args = AtomCommandLine::argv();
  128. // Feed node the path to initialization script.
  129. base::FilePath::StringType process_type = is_browser_ ?
  130. FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer");
  131. base::FilePath resources_path = GetResourcesPath(is_browser_);
  132. base::FilePath script_path =
  133. resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
  134. .Append(process_type)
  135. .Append(FILE_PATH_LITERAL("init.js"));
  136. std::string script_path_str = script_path.AsUTF8Unsafe();
  137. args.insert(args.begin() + 1, script_path_str.c_str());
  138. std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
  139. node::Environment* env = node::CreateEnvironment(
  140. new node::IsolateData(context->GetIsolate(), uv_default_loop()), context,
  141. args.size(), c_argv.get(), 0, nullptr);
  142. if (is_browser_) {
  143. // SetAutorunMicrotasks is no longer called in node::CreateEnvironment
  144. // so instead call it here to match expected node behavior
  145. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  146. } else {
  147. // Node uses the deprecated SetAutorunMicrotasks(false) mode, we should
  148. // switch to use the scoped policy to match blink's behavior.
  149. context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
  150. }
  151. mate::Dictionary process(context->GetIsolate(), env->process_object());
  152. process.Set("type", process_type);
  153. process.Set("resourcesPath", resources_path);
  154. // Do not set DOM globals for renderer process.
  155. if (!is_browser_)
  156. process.Set("_noBrowserGlobals", resources_path);
  157. // The path to helper app.
  158. base::FilePath helper_exec_path;
  159. PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
  160. process.Set("helperExecPath", helper_exec_path);
  161. // Set process._debugWaitConnect if --debug-brk was specified to stop
  162. // the debugger on the first line
  163. if (is_browser_ &&
  164. base::CommandLine::ForCurrentProcess()->HasSwitch("debug-brk"))
  165. process.Set("_debugWaitConnect", true);
  166. return env;
  167. }
  168. void NodeBindings::LoadEnvironment(node::Environment* env) {
  169. node::LoadEnvironment(env);
  170. mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
  171. }
  172. void NodeBindings::PrepareMessageLoop() {
  173. DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
  174. // Add dummy handle for libuv, otherwise libuv would quit when there is
  175. // nothing to do.
  176. uv_async_init(uv_loop_, &dummy_uv_handle_, nullptr);
  177. // Start worker that will interrupt main loop when having uv events.
  178. uv_sem_init(&embed_sem_, 0);
  179. uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
  180. }
  181. void NodeBindings::RunMessageLoop() {
  182. DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
  183. // The MessageLoop should have been created, remember the one in main thread.
  184. task_runner_ = base::ThreadTaskRunnerHandle::Get();
  185. // Run uv loop for once to give the uv__io_poll a chance to add all events.
  186. UvRunOnce();
  187. }
  188. void NodeBindings::UvRunOnce() {
  189. DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
  190. node::Environment* env = uv_env();
  191. // Use Locker in browser process.
  192. mate::Locker locker(env->isolate());
  193. v8::HandleScope handle_scope(env->isolate());
  194. // Enter node context while dealing with uv events.
  195. v8::Context::Scope context_scope(env->context());
  196. // Perform microtask checkpoint after running JavaScript.
  197. v8::MicrotasksScope script_scope(env->isolate(),
  198. v8::MicrotasksScope::kRunMicrotasks);
  199. if (!is_browser_)
  200. TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");
  201. // Deal with uv events.
  202. int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
  203. if (!is_browser_)
  204. TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
  205. if (r == 0)
  206. base::RunLoop().QuitWhenIdle(); // Quit from uv.
  207. // Tell the worker thread to continue polling.
  208. uv_sem_post(&embed_sem_);
  209. }
  210. void NodeBindings::WakeupMainThread() {
  211. DCHECK(task_runner_);
  212. task_runner_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
  213. weak_factory_.GetWeakPtr()));
  214. }
  215. void NodeBindings::WakeupEmbedThread() {
  216. uv_async_send(&dummy_uv_handle_);
  217. }
  218. // static
  219. void NodeBindings::EmbedThreadRunner(void *arg) {
  220. NodeBindings* self = static_cast<NodeBindings*>(arg);
  221. while (true) {
  222. // Wait for the main loop to deal with events.
  223. uv_sem_wait(&self->embed_sem_);
  224. if (self->embed_closed_)
  225. break;
  226. // Wait for something to happen in uv loop.
  227. // Note that the PollEvents() is implemented by derived classes, so when
  228. // this class is being destructed the PollEvents() would not be available
  229. // anymore. Because of it we must make sure we only invoke PollEvents()
  230. // when this class is alive.
  231. self->PollEvents();
  232. if (self->embed_closed_)
  233. break;
  234. // Deal with event in main thread.
  235. self->WakeupMainThread();
  236. }
  237. }
  238. } // namespace atom