protocol: respect requests from partition
[platform/framework/web/crosswalk-tizen.git] / atom / common / node_bindings.cc
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
5 #include "atom/common/node_bindings.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "atom/common/api/event_emitter_caller.h"
11 #include "atom/common/api/locker.h"
12 #include "atom/common/atom_command_line.h"
13 #include "atom/common/native_mate_converters/file_path_converter.h"
14 #include "atom/common/node_includes.h"
15 #include "base/command_line.h"
16 #include "base/base_paths.h"
17 #include "base/environment.h"
18 #include "base/files/file_path.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/path_service.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 "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
25
26 using content::BrowserThread;
27
28 // Force all builtin modules to be referenced so they can actually run their
29 // DSO constructors, see http://git.io/DRIqCg.
30 #define REFERENCE_MODULE(name) \
31   extern "C" void _register_ ## name(void); \
32   void (*fp_register_ ## name)(void) = _register_ ## name
33 // Electron's builtin modules.
34 REFERENCE_MODULE(atom_browser_app);
35 REFERENCE_MODULE(atom_browser_auto_updater);
36 REFERENCE_MODULE(atom_browser_content_tracing);
37 REFERENCE_MODULE(atom_browser_dialog);
38 REFERENCE_MODULE(atom_browser_debugger);
39 REFERENCE_MODULE(atom_browser_desktop_capturer);
40 REFERENCE_MODULE(atom_browser_download_item);
41 REFERENCE_MODULE(atom_browser_menu);
42 REFERENCE_MODULE(atom_browser_power_monitor);
43 REFERENCE_MODULE(atom_browser_power_save_blocker);
44 REFERENCE_MODULE(atom_browser_global_shortcut);
45 REFERENCE_MODULE(atom_browser_session);
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_id_weak_map);
54 REFERENCE_MODULE(atom_common_native_image);
55 REFERENCE_MODULE(atom_common_screen);
56 REFERENCE_MODULE(atom_common_shell);
57 REFERENCE_MODULE(atom_common_v8_util);
58 REFERENCE_MODULE(atom_renderer_ipc);
59 REFERENCE_MODULE(atom_renderer_web_frame);
60 #undef REFERENCE_MODULE
61
62 // The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the
63 // linker can not find it, could be a bug of VS.
64 #if defined(OS_WIN) && !defined(DEBUG)
65 namespace v8 {
66 const int Function::kLineOffsetNotFound = -1;
67 }
68 #endif
69
70 namespace atom {
71
72 namespace {
73
74 // Empty callback for async handle.
75 void UvNoOp(uv_async_t* handle) {
76 }
77
78 // Convert the given vector to an array of C-strings. The strings in the
79 // returned vector are only guaranteed valid so long as the vector of strings
80 // is not modified.
81 scoped_ptr<const char*[]> StringVectorToArgArray(
82     const std::vector<std::string>& vector) {
83   scoped_ptr<const char*[]> array(new const char*[vector.size()]);
84   for (size_t i = 0; i < vector.size(); ++i) {
85     array[i] = vector[i].c_str();
86   }
87   return array.Pass();
88 }
89
90 base::FilePath GetResourcesPath(bool is_browser) {
91   auto command_line = base::CommandLine::ForCurrentProcess();
92   base::FilePath exec_path(command_line->GetProgram());
93   PathService::Get(base::FILE_EXE, &exec_path);
94
95   base::FilePath resources_path =
96 #if defined(OS_MACOSX)
97       is_browser ? exec_path.DirName().DirName().Append("Resources") :
98                    exec_path.DirName().DirName().DirName().DirName().DirName()
99                             .Append("Resources");
100 #else
101       exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
102 #endif
103   return resources_path;
104 }
105
106 }  // namespace
107
108 node::Environment* global_env = nullptr;
109
110 NodeBindings::NodeBindings(bool is_browser)
111     : is_browser_(is_browser),
112       message_loop_(nullptr),
113       uv_loop_(uv_default_loop()),
114       embed_closed_(false),
115       uv_env_(nullptr),
116       weak_factory_(this) {
117 }
118
119 NodeBindings::~NodeBindings() {
120   // Quit the embed thread.
121   embed_closed_ = true;
122   uv_sem_post(&embed_sem_);
123   WakeupEmbedThread();
124
125   // Wait for everything to be done.
126   uv_thread_join(&embed_thread_);
127
128   // Clear uv.
129   uv_sem_destroy(&embed_sem_);
130 }
131
132 void NodeBindings::Initialize() {
133   // Open node's error reporting system for browser process.
134   node::g_standalone_mode = is_browser_;
135   node::g_upstream_node_mode = false;
136
137 #if defined(OS_LINUX)
138   // Get real command line in renderer process forked by zygote.
139   if (!is_browser_)
140     AtomCommandLine::InitializeFromCommandLine();
141 #endif
142
143   // Init node.
144   // (we assume node::Init would not modify the parameters under embedded mode).
145   node::Init(nullptr, nullptr, nullptr, nullptr);
146
147 #if defined(OS_WIN)
148   // uv_init overrides error mode to suppress the default crash dialog, bring
149   // it back if user wants to show it.
150   scoped_ptr<base::Environment> env(base::Environment::Create());
151   if (env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
152     SetErrorMode(0);
153 #endif
154 }
155
156 node::Environment* NodeBindings::CreateEnvironment(
157     v8::Handle<v8::Context> context) {
158   auto args = AtomCommandLine::argv();
159
160   // Feed node the path to initialization script.
161   base::FilePath::StringType process_type = is_browser_ ?
162       FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer");
163   base::FilePath resources_path = GetResourcesPath(is_browser_);
164   base::FilePath script_path =
165       resources_path.Append(FILE_PATH_LITERAL("atom.asar"))
166                     .Append(process_type)
167                     .Append(FILE_PATH_LITERAL("lib"))
168                     .Append(FILE_PATH_LITERAL("init.js"));
169   std::string script_path_str = script_path.AsUTF8Unsafe();
170   args.insert(args.begin() + 1, script_path_str.c_str());
171
172   scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
173   node::Environment* env = node::CreateEnvironment(
174       context->GetIsolate(), uv_default_loop(), context,
175       args.size(), c_argv.get(), 0, nullptr);
176
177   mate::Dictionary process(context->GetIsolate(), env->process_object());
178   process.Set("type", process_type);
179   process.Set("resourcesPath", resources_path);
180   // The path to helper app.
181   base::FilePath helper_exec_path;
182   PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
183   process.Set("helperExecPath", helper_exec_path);
184   return env;
185 }
186
187 void NodeBindings::LoadEnvironment(node::Environment* env) {
188   node::LoadEnvironment(env);
189   mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
190 }
191
192 void NodeBindings::PrepareMessageLoop() {
193   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
194
195   // Add dummy handle for libuv, otherwise libuv would quit when there is
196   // nothing to do.
197   uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);
198
199   // Start worker that will interrupt main loop when having uv events.
200   uv_sem_init(&embed_sem_, 0);
201   uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
202 }
203
204 void NodeBindings::RunMessageLoop() {
205   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
206
207   // The MessageLoop should have been created, remember the one in main thread.
208   message_loop_ = base::MessageLoop::current();
209
210   // Run uv loop for once to give the uv__io_poll a chance to add all events.
211   UvRunOnce();
212 }
213
214 void NodeBindings::UvRunOnce() {
215   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
216
217   // By default the global env would be used unless user specified another one
218   // (this happens for renderer process, which wraps the uv loop with web page
219   // context).
220   node::Environment* env = uv_env() ? uv_env() : global_env;
221
222   // Use Locker in browser process.
223   mate::Locker locker(env->isolate());
224   v8::HandleScope handle_scope(env->isolate());
225
226   // Enter node context while dealing with uv events.
227   v8::Context::Scope context_scope(env->context());
228
229   // Perform microtask checkpoint after running JavaScript.
230   scoped_ptr<blink::WebScopedRunV8Script> script_scope(
231       is_browser_ ? nullptr : new blink::WebScopedRunV8Script);
232
233   // Deal with uv events.
234   int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
235   if (r == 0 || uv_loop_->stop_flag != 0)
236     message_loop_->QuitWhenIdle();  // Quit from uv.
237
238   // Tell the worker thread to continue polling.
239   uv_sem_post(&embed_sem_);
240 }
241
242 void NodeBindings::WakeupMainThread() {
243   DCHECK(message_loop_);
244   message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
245                                                 weak_factory_.GetWeakPtr()));
246 }
247
248 void NodeBindings::WakeupEmbedThread() {
249   uv_async_send(&dummy_uv_handle_);
250 }
251
252 // static
253 void NodeBindings::EmbedThreadRunner(void *arg) {
254   NodeBindings* self = static_cast<NodeBindings*>(arg);
255
256   while (true) {
257     // Wait for the main loop to deal with events.
258     uv_sem_wait(&self->embed_sem_);
259     if (self->embed_closed_)
260       break;
261
262     // Wait for something to happen in uv loop.
263     // Note that the PollEvents() is implemented by derived classes, so when
264     // this class is being destructed the PollEvents() would not be available
265     // anymore. Because of it we must make sure we only invoke PollEvents()
266     // when this class is alive.
267     self->PollEvents();
268     if (self->embed_closed_)
269       break;
270
271     // Deal with event in main thread.
272     self->WakeupMainThread();
273   }
274 }
275
276 }  // namespace atom