node_bindings.cc 9.3 KB

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