blob: 21883412334a8edf57280f5eafde55174142f36d [file] [log] [blame]
[email protected]f55c90ee62014-04-12 00:50:031// Copyright 2014 The Chromium Authors. All rights reserved.
[email protected]58e10452012-02-22 03:34:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f55c90ee62014-04-12 00:50:035#include "extensions/renderer/module_system.h"
[email protected]58e10452012-02-22 03:34:456
7#include "base/bind.h"
[email protected]ad6aa8f92013-06-22 15:34:168#include "base/command_line.h"
[email protected]68e63ea12013-06-05 05:00:549#include "base/debug/trace_event.h"
[email protected]a714e462013-01-26 06:33:1010#include "base/stl_util.h"
[email protected]a19a16d82013-06-11 17:45:1211#include "base/strings/string_util.h"
12#include "base/strings/stringprintf.h"
[email protected]4f1633f2013-03-09 14:26:2413#include "content/public/renderer/render_view.h"
thestigb012bc3d2014-09-18 22:57:1314#include "extensions/common/extension.h"
[email protected]f55c90ee62014-04-12 00:50:0315#include "extensions/common/extensions_client.h"
16#include "extensions/renderer/console.h"
17#include "extensions/renderer/safe_builtins.h"
18#include "extensions/renderer/script_context.h"
[email protected]d9f51dad2014-07-09 05:39:3819#include "gin/modules/module_registry.h"
[email protected]2255a9332013-06-17 05:12:3120#include "third_party/WebKit/public/web/WebFrame.h"
21#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
[email protected]58e10452012-02-22 03:34:4522
[email protected]95ee77da2013-03-19 21:11:1123namespace extensions {
24
[email protected]58e10452012-02-22 03:34:4525namespace {
26
[email protected]561ddce2012-03-22 01:18:5527const char* kModuleSystem = "module_system";
28const char* kModuleName = "module_name";
29const char* kModuleField = "module_field";
[email protected]bad9a5f2012-04-13 19:16:5430const char* kModulesField = "modules";
[email protected]cc0457712012-03-21 03:56:3831
[email protected]662c48b2013-07-12 03:50:5232// Logs a fatal error for the calling context, with some added metadata about
33// the context:
34// - Its type (blessed, unblessed, etc).
35// - Whether it's valid.
36// - The extension ID, if one exists.
37//
[email protected]d84ecbf2013-07-30 22:48:1638// This will only actual be fatal in in dev/canary, since in too many cases
39// we're at the mercy of the extension or web page's environment. They can mess
40// up our JS in unexpected ways. Hopefully dev/canary channel will pick up such
41// problems, but given the wider variety on stable/beta it's impossible to know.
[email protected]f55c90ee62014-04-12 00:50:0342void Fatal(ScriptContext* context, const std::string& message) {
[email protected]662c48b2013-07-12 03:50:5243 // Prepend some context metadata.
44 std::string full_message = "(";
45 if (!context->is_valid())
46 full_message += "Invalid ";
47 full_message += context->GetContextTypeDescription();
48 full_message += " context";
49 if (context->extension()) {
50 full_message += " for ";
51 full_message += context->extension()->id();
52 }
53 full_message += ") ";
54 full_message += message;
55
[email protected]f55c90ee62014-04-12 00:50:0356 if (ExtensionsClient::Get()->ShouldSuppressFatalErrors())
[email protected]95c6b3012013-12-02 14:30:3157 console::Error(context->isolate()->GetCallingContext(), full_message);
[email protected]f55c90ee62014-04-12 00:50:0358 else
59 console::Fatal(context->isolate()->GetCallingContext(), full_message);
[email protected]ad6aa8f92013-06-22 15:34:1660}
61
[email protected]95c6b3012013-12-02 14:30:3162void Warn(v8::Isolate* isolate, const std::string& message) {
63 console::Warn(isolate->GetCallingContext(), message);
[email protected]ad6aa8f92013-06-22 15:34:1664}
65
[email protected]68e63ea12013-06-05 05:00:5466// Default exception handler which logs the exception.
67class DefaultExceptionHandler : public ModuleSystem::ExceptionHandler {
68 public:
[email protected]f55c90ee62014-04-12 00:50:0369 explicit DefaultExceptionHandler(ScriptContext* context)
[email protected]662c48b2013-07-12 03:50:5270 : context_(context) {}
[email protected]ad6aa8f92013-06-22 15:34:1671
[email protected]68e63ea12013-06-05 05:00:5472 // Fatally dumps the debug info from |try_catch| to the console.
73 // Make sure this is never used for exceptions that originate in external
74 // code!
75 virtual void HandleUncaughtException(const v8::TryCatch& try_catch) OVERRIDE {
[email protected]dc3d06e2013-09-06 12:21:0376 v8::HandleScope handle_scope(context_->isolate());
[email protected]68e63ea12013-06-05 05:00:5477 std::string stack_trace = "<stack trace unavailable>";
78 if (!try_catch.StackTrace().IsEmpty()) {
79 v8::String::Utf8Value stack_value(try_catch.StackTrace());
80 if (*stack_value)
81 stack_trace.assign(*stack_value, stack_value.length());
82 else
83 stack_trace = "<could not convert stack trace to string>";
84 }
[email protected]662c48b2013-07-12 03:50:5285 Fatal(context_, CreateExceptionString(try_catch) + "{" + stack_trace + "}");
[email protected]68e63ea12013-06-05 05:00:5486 }
[email protected]ad6aa8f92013-06-22 15:34:1687
88 private:
[email protected]f55c90ee62014-04-12 00:50:0389 ScriptContext* context_;
[email protected]68e63ea12013-06-05 05:00:5490};
91
[email protected]f55c90ee62014-04-12 00:50:0392} // namespace
[email protected]68e63ea12013-06-05 05:00:5493
94std::string ModuleSystem::ExceptionHandler::CreateExceptionString(
95 const v8::TryCatch& try_catch) {
[email protected]95ee77da2013-03-19 21:11:1196 v8::Handle<v8::Message> message(try_catch.Message());
97 if (message.IsEmpty()) {
98 return "try_catch has no message";
99 }
[email protected]58e10452012-02-22 03:34:45100
[email protected]95ee77da2013-03-19 21:11:11101 std::string resource_name = "<unknown resource>";
[email protected]bce20ba2014-06-27 18:18:45102 if (!message->GetScriptOrigin().ResourceName().IsEmpty()) {
[email protected]95ee77da2013-03-19 21:11:11103 v8::String::Utf8Value resource_name_v8(
[email protected]bce20ba2014-06-27 18:18:45104 message->GetScriptOrigin().ResourceName()->ToString());
[email protected]95ee77da2013-03-19 21:11:11105 resource_name.assign(*resource_name_v8, resource_name_v8.length());
106 }
107
108 std::string error_message = "<no error message>";
109 if (!message->Get().IsEmpty()) {
110 v8::String::Utf8Value error_message_v8(message->Get());
111 error_message.assign(*error_message_v8, error_message_v8.length());
112 }
113
114 return base::StringPrintf("%s:%d: %s",
115 resource_name.c_str(),
116 message->GetLineNumber(),
117 error_message.c_str());
118}
119
[email protected]f55c90ee62014-04-12 00:50:03120ModuleSystem::ModuleSystem(ScriptContext* context, SourceMap* source_map)
[email protected]4f1633f2013-03-09 14:26:24121 : ObjectBackedNativeHandler(context),
[email protected]68e63ea12013-06-05 05:00:54122 context_(context),
[email protected]bad9a5f2012-04-13 19:16:54123 source_map_(source_map),
[email protected]68e63ea12013-06-05 05:00:54124 natives_enabled_(0),
[email protected]d9f51dad2014-07-09 05:39:38125 exception_handler_(new DefaultExceptionHandler(context)),
126 weak_factory_(this) {
[email protected]f55c90ee62014-04-12 00:50:03127 RouteFunction(
128 "require",
[email protected]ecde1912012-03-16 06:25:31129 base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this)));
[email protected]f55c90ee62014-04-12 00:50:03130 RouteFunction(
131 "requireNative",
[email protected]4f1633f2013-03-09 14:26:24132 base::Bind(&ModuleSystem::RequireNative, base::Unretained(this)));
[email protected]d9f51dad2014-07-09 05:39:38133 RouteFunction(
134 "requireAsync",
135 base::Bind(&ModuleSystem::RequireAsync, base::Unretained(this)));
[email protected]ca557292013-12-11 08:44:27136 RouteFunction("privates",
[email protected]f55c90ee62014-04-12 00:50:03137 base::Bind(&ModuleSystem::Private, base::Unretained(this)));
[email protected]ecde1912012-03-16 06:25:31138
[email protected]9a598442013-06-04 16:39:12139 v8::Handle<v8::Object> global(context->v8_context()->Global());
[email protected]505ffde2013-12-19 15:47:13140 v8::Isolate* isolate = context->isolate();
[email protected]f55c90ee62014-04-12 00:50:03141 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModulesField),
142 v8::Object::New(isolate));
143 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModuleSystem),
144 v8::External::New(isolate, this));
[email protected]d9f51dad2014-07-09 05:39:38145
146 gin::ModuleRegistry::From(context->v8_context())->AddObserver(this);
[email protected]58e10452012-02-22 03:34:45147}
148
[email protected]f55c90ee62014-04-12 00:50:03149ModuleSystem::~ModuleSystem() { Invalidate(); }
[email protected]4f1633f2013-03-09 14:26:24150
151void ModuleSystem::Invalidate() {
152 if (!is_valid())
153 return;
[email protected]079532242013-03-12 06:01:10154
155 // Clear the module system properties from the global context. It's polite,
156 // and we use this as a signal in lazy handlers that we no longer exist.
157 {
[email protected]dc3d06e2013-09-06 12:21:03158 v8::HandleScope scope(GetIsolate());
[email protected]9a598442013-06-04 16:39:12159 v8::Handle<v8::Object> global = context()->v8_context()->Global();
[email protected]9c47471e2013-11-28 14:41:21160 global->DeleteHiddenValue(
161 v8::String::NewFromUtf8(GetIsolate(), kModulesField));
162 global->DeleteHiddenValue(
163 v8::String::NewFromUtf8(GetIsolate(), kModuleSystem));
[email protected]079532242013-03-12 06:01:10164 }
165
166 // Invalidate all of the successfully required handlers we own.
[email protected]4f1633f2013-03-09 14:26:24167 for (NativeHandlerMap::iterator it = native_handler_map_.begin();
[email protected]f55c90ee62014-04-12 00:50:03168 it != native_handler_map_.end();
169 ++it) {
[email protected]4f1633f2013-03-09 14:26:24170 it->second->Invalidate();
171 }
[email protected]079532242013-03-12 06:01:10172
[email protected]4f1633f2013-03-09 14:26:24173 ObjectBackedNativeHandler::Invalidate();
[email protected]58e10452012-02-22 03:34:45174}
175
[email protected]b6aad81c2012-03-27 08:45:15176ModuleSystem::NativesEnabledScope::NativesEnabledScope(
177 ModuleSystem* module_system)
178 : module_system_(module_system) {
179 module_system_->natives_enabled_++;
180}
181
182ModuleSystem::NativesEnabledScope::~NativesEnabledScope() {
183 module_system_->natives_enabled_--;
184 CHECK_GE(module_system_->natives_enabled_, 0);
185}
186
[email protected]144114942012-12-04 07:23:23187void ModuleSystem::HandleException(const v8::TryCatch& try_catch) {
[email protected]68e63ea12013-06-05 05:00:54188 exception_handler_->HandleUncaughtException(try_catch);
[email protected]1c6189f2012-05-18 06:45:52189}
190
[email protected]4f1633f2013-03-09 14:26:24191v8::Handle<v8::Value> ModuleSystem::Require(const std::string& module_name) {
[email protected]95c6b3012013-12-02 14:30:31192 v8::EscapableHandleScope handle_scope(GetIsolate());
193 return handle_scope.Escape(RequireForJsInner(
[email protected]9c47471e2013-11-28 14:41:21194 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str())));
[email protected]ecde1912012-03-16 06:25:31195}
196
[email protected]d8c5fbb2013-06-14 11:35:25197void ModuleSystem::RequireForJs(
[email protected]f55c90ee62014-04-12 00:50:03198 const v8::FunctionCallbackInfo<v8::Value>& args) {
[email protected]ecde1912012-03-16 06:25:31199 v8::Handle<v8::String> module_name = args[0]->ToString();
[email protected]d8c5fbb2013-06-14 11:35:25200 args.GetReturnValue().Set(RequireForJsInner(module_name));
[email protected]ecde1912012-03-16 06:25:31201}
202
[email protected]95c6b3012013-12-02 14:30:31203v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
[email protected]ecde1912012-03-16 06:25:31204 v8::Handle<v8::String> module_name) {
[email protected]95c6b3012013-12-02 14:30:31205 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]9a598442013-06-04 16:39:12206 v8::Context::Scope context_scope(context()->v8_context());
[email protected]95ee77da2013-03-19 21:11:11207
[email protected]9a598442013-06-04 16:39:12208 v8::Handle<v8::Object> global(context()->v8_context()->Global());
[email protected]079532242013-03-12 06:01:10209
210 // The module system might have been deleted. This can happen if a different
211 // context keeps a reference to us, but our frame is destroyed (e.g.
212 // background page keeps reference to chrome object in a closed popup).
[email protected]9c47471e2013-11-28 14:41:21213 v8::Handle<v8::Value> modules_value = global->GetHiddenValue(
214 v8::String::NewFromUtf8(GetIsolate(), kModulesField));
[email protected]d2663612013-03-17 09:25:56215 if (modules_value.IsEmpty() || modules_value->IsUndefined()) {
[email protected]95c6b3012013-12-02 14:30:31216 Warn(GetIsolate(), "Extension view no longer exists");
217 return v8::Undefined(GetIsolate());
[email protected]d2663612013-03-17 09:25:56218 }
[email protected]079532242013-03-12 06:01:10219
220 v8::Handle<v8::Object> modules(v8::Handle<v8::Object>::Cast(modules_value));
[email protected]95c6b3012013-12-02 14:30:31221 v8::Local<v8::Value> exports(modules->Get(module_name));
[email protected]ecde1912012-03-16 06:25:31222 if (!exports->IsUndefined())
[email protected]95c6b3012013-12-02 14:30:31223 return handle_scope.Escape(exports);
[email protected]7c95c1a82012-04-17 02:11:33224
[email protected]d9f51dad2014-07-09 05:39:38225 exports = LoadModule(*v8::String::Utf8Value(module_name));
[email protected]ecde1912012-03-16 06:25:31226 modules->Set(module_name, exports);
[email protected]95c6b3012013-12-02 14:30:31227 return handle_scope.Escape(exports);
[email protected]58e10452012-02-22 03:34:45228}
229
[email protected]4f1633f2013-03-09 14:26:24230v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
231 const std::string& module_name,
232 const std::string& method_name) {
[email protected]f80685c32014-07-26 19:48:04233 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]68e63ea12013-06-05 05:00:54234 v8::Handle<v8::Value> no_args;
[email protected]f80685c32014-07-26 19:48:04235 return handle_scope.Escape(
236 CallModuleMethod(module_name, method_name, 0, &no_args));
[email protected]a714e462013-01-26 06:33:10237}
238
239v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
240 const std::string& module_name,
241 const std::string& method_name,
242 std::vector<v8::Handle<v8::Value> >* args) {
[email protected]68e63ea12013-06-05 05:00:54243 return CallModuleMethod(
244 module_name, method_name, args->size(), vector_as_array(args));
245}
246
247v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
248 const std::string& module_name,
249 const std::string& method_name,
250 int argc,
251 v8::Handle<v8::Value> argv[]) {
[email protected]f55c90ee62014-04-12 00:50:03252 TRACE_EVENT2("v8",
253 "v8.callModuleMethod",
254 "module_name",
255 module_name,
256 "method_name",
257 method_name);
[email protected]68e63ea12013-06-05 05:00:54258
[email protected]95c6b3012013-12-02 14:30:31259 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]68e63ea12013-06-05 05:00:54260 v8::Context::Scope context_scope(context()->v8_context());
261
262 v8::Local<v8::Value> module;
263 {
264 NativesEnabledScope natives_enabled(this);
[email protected]9c47471e2013-11-28 14:41:21265 module = RequireForJsInner(
266 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
[email protected]68e63ea12013-06-05 05:00:54267 }
268
[email protected]95ee77da2013-03-19 21:11:11269 if (module.IsEmpty() || !module->IsObject()) {
[email protected]662c48b2013-07-12 03:50:52270 Fatal(context_,
[email protected]ad6aa8f92013-06-22 15:34:16271 "Failed to get module " + module_name + " to call " + method_name);
[email protected]95c6b3012013-12-02 14:30:31272 return handle_scope.Escape(
273 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
[email protected]95ee77da2013-03-19 21:11:11274 }
275
[email protected]f55c90ee62014-04-12 00:50:03276 v8::Local<v8::Value> value = v8::Handle<v8::Object>::Cast(module)->Get(
277 v8::String::NewFromUtf8(GetIsolate(), method_name.c_str()));
[email protected]95ee77da2013-03-19 21:11:11278 if (value.IsEmpty() || !value->IsFunction()) {
[email protected]662c48b2013-07-12 03:50:52279 Fatal(context_, module_name + "." + method_name + " is not a function");
[email protected]95c6b3012013-12-02 14:30:31280 return handle_scope.Escape(
281 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
[email protected]95ee77da2013-03-19 21:11:11282 }
283
[email protected]68e63ea12013-06-05 05:00:54284 v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
[email protected]a714e462013-01-26 06:33:10285 v8::Local<v8::Value> result;
[email protected]2bcbf712012-09-05 06:58:49286 {
[email protected]2bcbf712012-09-05 06:58:49287 v8::TryCatch try_catch;
288 try_catch.SetCaptureMessage(true);
[email protected]68e63ea12013-06-05 05:00:54289 result = context_->CallFunction(func, argc, argv);
[email protected]2bcbf712012-09-05 06:58:49290 if (try_catch.HasCaught())
[email protected]144114942012-12-04 07:23:23291 HandleException(try_catch);
[email protected]2bcbf712012-09-05 06:58:49292 }
[email protected]95c6b3012013-12-02 14:30:31293 return handle_scope.Escape(result);
[email protected]2bcbf712012-09-05 06:58:49294}
295
[email protected]f55c90ee62014-04-12 00:50:03296void ModuleSystem::RegisterNativeHandler(
297 const std::string& name,
[email protected]58e10452012-02-22 03:34:45298 scoped_ptr<NativeHandler> native_handler) {
299 native_handler_map_[name] =
300 linked_ptr<NativeHandler>(native_handler.release());
301}
302
[email protected]95ee77da2013-03-19 21:11:11303void ModuleSystem::OverrideNativeHandlerForTest(const std::string& name) {
[email protected]11844fa2012-05-10 00:35:59304 overridden_native_handlers_.insert(name);
305}
306
[email protected]ecde1912012-03-16 06:25:31307void ModuleSystem::RunString(const std::string& code, const std::string& name) {
[email protected]dc3d06e2013-09-06 12:21:03308 v8::HandleScope handle_scope(GetIsolate());
[email protected]9c47471e2013-11-28 14:41:21309 RunString(v8::String::NewFromUtf8(GetIsolate(), code.c_str()),
310 v8::String::NewFromUtf8(GetIsolate(), name.c_str()));
[email protected]58e10452012-02-22 03:34:45311}
312
[email protected]cc0457712012-03-21 03:56:38313// static
[email protected]4e008e172013-06-13 20:15:48314void ModuleSystem::NativeLazyFieldGetter(
[email protected]4f1633f2013-03-09 14:26:24315 v8::Local<v8::String> property,
[email protected]4e008e172013-06-13 20:15:48316 const v8::PropertyCallbackInfo<v8::Value>& info) {
[email protected]f55c90ee62014-04-12 00:50:03317 LazyFieldGetterInner(property, info, &ModuleSystem::RequireNativeFromString);
[email protected]4e008e172013-06-13 20:15:48318}
319
320// static
321void ModuleSystem::LazyFieldGetter(
322 v8::Local<v8::String> property,
323 const v8::PropertyCallbackInfo<v8::Value>& info) {
324 LazyFieldGetterInner(property, info, &ModuleSystem::Require);
325}
326
327// static
328void ModuleSystem::LazyFieldGetterInner(
329 v8::Local<v8::String> property,
330 const v8::PropertyCallbackInfo<v8::Value>& info,
[email protected]4f1633f2013-03-09 14:26:24331 RequireFunction require_function) {
[email protected]561ddce2012-03-22 01:18:55332 CHECK(!info.Data().IsEmpty());
333 CHECK(info.Data()->IsObject());
[email protected]dc3d06e2013-09-06 12:21:03334 v8::HandleScope handle_scope(info.GetIsolate());
[email protected]561ddce2012-03-22 01:18:55335 v8::Handle<v8::Object> parameters = v8::Handle<v8::Object>::Cast(info.Data());
[email protected]9a598442013-06-04 16:39:12336 // This context should be the same as context()->v8_context().
[email protected]4f1633f2013-03-09 14:26:24337 v8::Handle<v8::Context> context = parameters->CreationContext();
338 v8::Handle<v8::Object> global(context->Global());
[email protected]9c47471e2013-11-28 14:41:21339 v8::Handle<v8::Value> module_system_value = global->GetHiddenValue(
340 v8::String::NewFromUtf8(info.GetIsolate(), kModuleSystem));
[email protected]95ee77da2013-03-19 21:11:11341 if (module_system_value.IsEmpty() || !module_system_value->IsExternal()) {
[email protected]bad9a5f2012-04-13 19:16:54342 // ModuleSystem has been deleted.
[email protected]95ee77da2013-03-19 21:11:11343 // TODO(kalman): See comment in header file.
[email protected]95c6b3012013-12-02 14:30:31344 Warn(info.GetIsolate(),
345 "Module system has been deleted, does extension view exist?");
[email protected]4e008e172013-06-13 20:15:48346 return;
[email protected]bad9a5f2012-04-13 19:16:54347 }
[email protected]95ee77da2013-03-19 21:11:11348
[email protected]561ddce2012-03-22 01:18:55349 ModuleSystem* module_system = static_cast<ModuleSystem*>(
350 v8::Handle<v8::External>::Cast(module_system_value)->Value());
[email protected]cc0457712012-03-21 03:56:38351
[email protected]f55c90ee62014-04-12 00:50:03352 std::string name =
353 *v8::String::Utf8Value(
354 parameters->Get(v8::String::NewFromUtf8(info.GetIsolate(),
355 kModuleName))->ToString());
[email protected]4f1633f2013-03-09 14:26:24356
357 // Switch to our v8 context because we need functions created while running
358 // the require()d module to belong to our context, not the current one.
359 v8::Context::Scope context_scope(context);
360 NativesEnabledScope natives_enabled_scope(module_system);
361
362 v8::TryCatch try_catch;
[email protected]95ee77da2013-03-19 21:11:11363 v8::Handle<v8::Value> module_value = (module_system->*require_function)(name);
[email protected]4f1633f2013-03-09 14:26:24364 if (try_catch.HasCaught()) {
365 module_system->HandleException(try_catch);
[email protected]4e008e172013-06-13 20:15:48366 return;
[email protected]95ee77da2013-03-19 21:11:11367 }
368 if (module_value.IsEmpty() || !module_value->IsObject()) {
369 // require_function will have already logged this, we don't need to.
[email protected]4e008e172013-06-13 20:15:48370 return;
[email protected]b6aad81c2012-03-27 08:45:15371 }
[email protected]4f1633f2013-03-09 14:26:24372
[email protected]95ee77da2013-03-19 21:11:11373 v8::Handle<v8::Object> module = v8::Handle<v8::Object>::Cast(module_value);
[email protected]561ddce2012-03-22 01:18:55374 v8::Handle<v8::String> field =
[email protected]9c47471e2013-11-28 14:41:21375 parameters->Get(v8::String::NewFromUtf8(info.GetIsolate(), kModuleField))
376 ->ToString();
[email protected]561ddce2012-03-22 01:18:55377
[email protected]95ee77da2013-03-19 21:11:11378 if (!module->Has(field)) {
[email protected]d7cd1b02013-09-10 00:22:16379 std::string field_str = *v8::String::Utf8Value(field);
[email protected]662c48b2013-07-12 03:50:52380 Fatal(module_system->context_,
381 "Lazy require of " + name + "." + field_str + " did not set the " +
382 field_str + " field");
[email protected]4e008e172013-06-13 20:15:48383 return;
[email protected]95ee77da2013-03-19 21:11:11384 }
[email protected]4f1633f2013-03-09 14:26:24385
386 v8::Local<v8::Value> new_field = module->Get(field);
[email protected]95ee77da2013-03-19 21:11:11387 if (try_catch.HasCaught()) {
388 module_system->HandleException(try_catch);
[email protected]4e008e172013-06-13 20:15:48389 return;
[email protected]95ee77da2013-03-19 21:11:11390 }
391
392 // Ok for it to be undefined, among other things it's how bindings signify
393 // that the extension doesn't have permission to use them.
394 CHECK(!new_field.IsEmpty());
395
[email protected]4f1633f2013-03-09 14:26:24396 // Delete the getter and set this field to |new_field| so the same object is
397 // returned every time a certain API is accessed.
[email protected]80b0c8c2014-04-22 15:00:43398 v8::Handle<v8::Value> val = info.This();
399 if (val->IsObject()) {
400 v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(val);
401 object->Delete(property);
402 object->Set(property, new_field);
403 } else {
404 NOTREACHED();
405 }
[email protected]4e008e172013-06-13 20:15:48406 info.GetReturnValue().Set(new_field);
[email protected]561ddce2012-03-22 01:18:55407}
408
409void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object,
410 const std::string& field,
411 const std::string& module_name,
412 const std::string& module_field) {
[email protected]f55c90ee62014-04-12 00:50:03413 SetLazyField(
414 object, field, module_name, module_field, &ModuleSystem::LazyFieldGetter);
[email protected]4f1633f2013-03-09 14:26:24415}
416
417void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object,
418 const std::string& field,
419 const std::string& module_name,
420 const std::string& module_field,
[email protected]4e008e172013-06-13 20:15:48421 v8::AccessorGetterCallback getter) {
[email protected]dc3d06e2013-09-06 12:21:03422 v8::HandleScope handle_scope(GetIsolate());
[email protected]505ffde2013-12-19 15:47:13423 v8::Handle<v8::Object> parameters = v8::Object::New(GetIsolate());
[email protected]9c47471e2013-11-28 14:41:21424 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleName),
425 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
426 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleField),
427 v8::String::NewFromUtf8(GetIsolate(), module_field.c_str()));
428 object->SetAccessor(v8::String::NewFromUtf8(GetIsolate(), field.c_str()),
[email protected]4f1633f2013-03-09 14:26:24429 getter,
[email protected]561ddce2012-03-22 01:18:55430 NULL,
431 parameters);
[email protected]cc0457712012-03-21 03:56:38432}
[email protected]ecde1912012-03-16 06:25:31433
[email protected]4f1633f2013-03-09 14:26:24434void ModuleSystem::SetNativeLazyField(v8::Handle<v8::Object> object,
435 const std::string& field,
436 const std::string& module_name,
437 const std::string& module_field) {
[email protected]f55c90ee62014-04-12 00:50:03438 SetLazyField(object,
439 field,
440 module_name,
441 module_field,
442 &ModuleSystem::NativeLazyFieldGetter);
[email protected]4f1633f2013-03-09 14:26:24443}
444
[email protected]ecde1912012-03-16 06:25:31445v8::Handle<v8::Value> ModuleSystem::RunString(v8::Handle<v8::String> code,
446 v8::Handle<v8::String> name) {
[email protected]95c6b3012013-12-02 14:30:31447 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]68e63ea12013-06-05 05:00:54448 v8::Context::Scope context_scope(context()->v8_context());
[email protected]95ee77da2013-03-19 21:11:11449
[email protected]d7cd1b02013-09-10 00:22:16450 // Prepend extensions:: to |name| so that internal code can be differentiated
451 // from external code in stack traces. This has no effect on behaviour.
[email protected]f55c90ee62014-04-12 00:50:03452 std::string internal_name =
453 base::StringPrintf("extensions::%s", *v8::String::Utf8Value(name));
[email protected]d7cd1b02013-09-10 00:22:16454
[email protected]a1221aea2013-11-07 01:31:30455 blink::WebScopedMicrotaskSuppression suppression;
[email protected]7c95c1a82012-04-17 02:11:33456 v8::TryCatch try_catch;
[email protected]56a4bf832012-07-13 04:26:54457 try_catch.SetCaptureMessage(true);
[email protected]9c47471e2013-11-28 14:41:21458 v8::Handle<v8::Script> script(
[email protected]74af28ea2014-02-27 18:53:29459 v8::Script::Compile(code,
460 v8::String::NewFromUtf8(GetIsolate(),
461 internal_name.c_str(),
462 v8::String::kNormalString,
463 internal_name.size())));
[email protected]7c95c1a82012-04-17 02:11:33464 if (try_catch.HasCaught()) {
[email protected]144114942012-12-04 07:23:23465 HandleException(try_catch);
[email protected]95c6b3012013-12-02 14:30:31466 return v8::Undefined(GetIsolate());
[email protected]7c95c1a82012-04-17 02:11:33467 }
468
[email protected]95c6b3012013-12-02 14:30:31469 v8::Local<v8::Value> result = script->Run();
[email protected]95ee77da2013-03-19 21:11:11470 if (try_catch.HasCaught()) {
[email protected]144114942012-12-04 07:23:23471 HandleException(try_catch);
[email protected]95c6b3012013-12-02 14:30:31472 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11473 }
[email protected]7c95c1a82012-04-17 02:11:33474
[email protected]95c6b3012013-12-02 14:30:31475 return handle_scope.Escape(result);
[email protected]9e03ce22012-03-13 08:50:05476}
477
[email protected]d2663612013-03-17 09:25:56478v8::Handle<v8::Value> ModuleSystem::GetSource(const std::string& module_name) {
[email protected]95c6b3012013-12-02 14:30:31479 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]ecde1912012-03-16 06:25:31480 if (!source_map_->Contains(module_name))
[email protected]95c6b3012013-12-02 14:30:31481 return v8::Undefined(GetIsolate());
482 return handle_scope.Escape(
483 v8::Local<v8::Value>(source_map_->GetSource(GetIsolate(), module_name)));
[email protected]58e10452012-02-22 03:34:45484}
485
[email protected]d8c5fbb2013-06-14 11:35:25486void ModuleSystem::RequireNative(
487 const v8::FunctionCallbackInfo<v8::Value>& args) {
[email protected]58e10452012-02-22 03:34:45488 CHECK_EQ(1, args.Length());
[email protected]d7cd1b02013-09-10 00:22:16489 std::string native_name = *v8::String::Utf8Value(args[0]->ToString());
[email protected]d8c5fbb2013-06-14 11:35:25490 args.GetReturnValue().Set(RequireNativeFromString(native_name));
[email protected]4f1633f2013-03-09 14:26:24491}
492
493v8::Handle<v8::Value> ModuleSystem::RequireNativeFromString(
494 const std::string& native_name) {
[email protected]95ee77da2013-03-19 21:11:11495 if (natives_enabled_ == 0) {
496 // HACK: if in test throw exception so that we can test the natives-disabled
497 // logic; however, under normal circumstances, this is programmer error so
498 // we could crash.
[email protected]9c47471e2013-11-28 14:41:21499 if (exception_handler_) {
[email protected]95c6b3012013-12-02 14:30:31500 return GetIsolate()->ThrowException(
[email protected]9c47471e2013-11-28 14:41:21501 v8::String::NewFromUtf8(GetIsolate(), "Natives disabled"));
502 }
[email protected]662c48b2013-07-12 03:50:52503 Fatal(context_, "Natives disabled for requireNative(" + native_name + ")");
[email protected]95c6b3012013-12-02 14:30:31504 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11505 }
506
[email protected]9c47471e2013-11-28 14:41:21507 if (overridden_native_handlers_.count(native_name) > 0u) {
508 return RequireForJsInner(
509 v8::String::NewFromUtf8(GetIsolate(), native_name.c_str()));
510 }
[email protected]95ee77da2013-03-19 21:11:11511
[email protected]58e10452012-02-22 03:34:45512 NativeHandlerMap::iterator i = native_handler_map_.find(native_name);
[email protected]95ee77da2013-03-19 21:11:11513 if (i == native_handler_map_.end()) {
[email protected]662c48b2013-07-12 03:50:52514 Fatal(context_,
[email protected]ad6aa8f92013-06-22 15:34:16515 "Couldn't find native for requireNative(" + native_name + ")");
[email protected]95c6b3012013-12-02 14:30:31516 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11517 }
[email protected]58e10452012-02-22 03:34:45518 return i->second->NewInstance();
519}
[email protected]ecde1912012-03-16 06:25:31520
[email protected]d9f51dad2014-07-09 05:39:38521void ModuleSystem::RequireAsync(
522 const v8::FunctionCallbackInfo<v8::Value>& args) {
523 CHECK_EQ(1, args.Length());
524 std::string module_name = *v8::String::Utf8Value(args[0]->ToString());
525 v8::Handle<v8::Promise::Resolver> resolver(
526 v8::Promise::Resolver::New(GetIsolate()));
527 args.GetReturnValue().Set(resolver->GetPromise());
528 scoped_ptr<v8::UniquePersistent<v8::Promise::Resolver> > persistent_resolver(
529 new v8::UniquePersistent<v8::Promise::Resolver>(GetIsolate(), resolver));
530 gin::ModuleRegistry* module_registry =
531 gin::ModuleRegistry::From(context_->v8_context());
532 if (!module_registry) {
533 Warn(GetIsolate(), "Extension view no longer exists");
534 resolver->Reject(v8::Exception::Error(v8::String::NewFromUtf8(
535 GetIsolate(), "Extension view no longer exists")));
536 return;
537 }
538 module_registry->LoadModule(GetIsolate(),
539 module_name,
540 base::Bind(&ModuleSystem::OnModuleLoaded,
541 weak_factory_.GetWeakPtr(),
542 base::Passed(&persistent_resolver)));
543 if (module_registry->available_modules().count(module_name) == 0)
544 LoadModule(module_name);
545}
546
[email protected]ecde1912012-03-16 06:25:31547v8::Handle<v8::String> ModuleSystem::WrapSource(v8::Handle<v8::String> source) {
[email protected]95c6b3012013-12-02 14:30:31548 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]295890bd2013-06-15 10:52:45549 // Keep in order with the arguments in RequireForJsInner.
[email protected]2a356872014-02-21 23:18:52550 v8::Handle<v8::String> left = v8::String::NewFromUtf8(
551 GetIsolate(),
[email protected]d9f51dad2014-07-09 05:39:38552 "(function(define, require, requireNative, requireAsync, exports, "
[email protected]2a356872014-02-21 23:18:52553 "console, privates,"
[email protected]0d775c72014-08-22 13:06:26554 "$Array, $Function, $JSON, $Object, $RegExp, $String, $Error) {"
[email protected]2a356872014-02-21 23:18:52555 "'use strict';");
[email protected]9c47471e2013-11-28 14:41:21556 v8::Handle<v8::String> right = v8::String::NewFromUtf8(GetIsolate(), "\n})");
[email protected]95c6b3012013-12-02 14:30:31557 return handle_scope.Escape(v8::Local<v8::String>(
558 v8::String::Concat(left, v8::String::Concat(source, right))));
[email protected]ecde1912012-03-16 06:25:31559}
560
[email protected]ca557292013-12-11 08:44:27561void ModuleSystem::Private(const v8::FunctionCallbackInfo<v8::Value>& args) {
562 CHECK_EQ(1, args.Length());
563 CHECK(args[0]->IsObject());
564 v8::Local<v8::Object> obj = args[0].As<v8::Object>();
565 v8::Local<v8::String> privates_key =
566 v8::String::NewFromUtf8(GetIsolate(), "privates");
567 v8::Local<v8::Value> privates = obj->GetHiddenValue(privates_key);
568 if (privates.IsEmpty()) {
[email protected]505ffde2013-12-19 15:47:13569 privates = v8::Object::New(args.GetIsolate());
[email protected]ca557292013-12-11 08:44:27570 obj->SetHiddenValue(privates_key, privates);
571 }
572 args.GetReturnValue().Set(privates);
573}
574
[email protected]d9f51dad2014-07-09 05:39:38575v8::Handle<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
576 v8::EscapableHandleScope handle_scope(GetIsolate());
577 v8::Context::Scope context_scope(context()->v8_context());
578
579 v8::Handle<v8::Value> source(GetSource(module_name));
580 if (source.IsEmpty() || source->IsUndefined()) {
581 Fatal(context_, "No source for require(" + module_name + ")");
582 return v8::Undefined(GetIsolate());
583 }
584 v8::Handle<v8::String> wrapped_source(
585 WrapSource(v8::Handle<v8::String>::Cast(source)));
586 // Modules are wrapped in (function(){...}) so they always return functions.
587 v8::Handle<v8::Value> func_as_value =
588 RunString(wrapped_source,
589 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
590 if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
591 Fatal(context_, "Bad source for require(" + module_name + ")");
592 return v8::Undefined(GetIsolate());
593 }
594
595 v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(func_as_value);
596
597 v8::Handle<v8::Object> define_object = v8::Object::New(GetIsolate());
598 gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
599
600 v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
601 v8::Handle<v8::Object> natives(NewInstance());
602 CHECK(!natives.IsEmpty()); // this can happen if v8 has issues
603
604 // These must match the argument order in WrapSource.
605 v8::Handle<v8::Value> args[] = {
606 // AMD.
607 define_object->Get(v8::String::NewFromUtf8(GetIsolate(), "define")),
608 // CommonJS.
609 natives->Get(v8::String::NewFromUtf8(
610 GetIsolate(), "require", v8::String::kInternalizedString)),
611 natives->Get(v8::String::NewFromUtf8(
612 GetIsolate(), "requireNative", v8::String::kInternalizedString)),
613 natives->Get(v8::String::NewFromUtf8(
614 GetIsolate(), "requireAsync", v8::String::kInternalizedString)),
615 exports,
616 // Libraries that we magically expose to every module.
617 console::AsV8Object(),
618 natives->Get(v8::String::NewFromUtf8(
619 GetIsolate(), "privates", v8::String::kInternalizedString)),
620 // Each safe builtin. Keep in order with the arguments in WrapSource.
621 context_->safe_builtins()->GetArray(),
622 context_->safe_builtins()->GetFunction(),
623 context_->safe_builtins()->GetJSON(),
624 context_->safe_builtins()->GetObjekt(),
625 context_->safe_builtins()->GetRegExp(),
626 context_->safe_builtins()->GetString(),
[email protected]0d775c72014-08-22 13:06:26627 context_->safe_builtins()->GetError(),
[email protected]d9f51dad2014-07-09 05:39:38628 };
629 {
630 v8::TryCatch try_catch;
631 try_catch.SetCaptureMessage(true);
632 context_->CallFunction(func, arraysize(args), args);
633 if (try_catch.HasCaught()) {
634 HandleException(try_catch);
635 return v8::Undefined(GetIsolate());
636 }
637 }
638 return handle_scope.Escape(exports);
639}
640
641void ModuleSystem::OnDidAddPendingModule(
642 const std::string& id,
643 const std::vector<std::string>& dependencies) {
644 if (!source_map_->Contains(id))
645 return;
646
647 gin::ModuleRegistry* registry =
648 gin::ModuleRegistry::From(context_->v8_context());
649 DCHECK(registry);
650 for (std::vector<std::string>::const_iterator it = dependencies.begin();
651 it != dependencies.end();
652 ++it) {
653 if (registry->available_modules().count(*it) == 0)
654 LoadModule(*it);
655 }
656 registry->AttemptToLoadMoreModules(GetIsolate());
657}
658
659void ModuleSystem::OnModuleLoaded(
660 scoped_ptr<v8::UniquePersistent<v8::Promise::Resolver> > resolver,
661 v8::Handle<v8::Value> value) {
662 if (!is_valid())
663 return;
664 v8::HandleScope handle_scope(GetIsolate());
665 v8::Handle<v8::Promise::Resolver> resolver_local(
666 v8::Local<v8::Promise::Resolver>::New(GetIsolate(), *resolver));
667 resolver_local->Resolve(value);
668}
669
[email protected]4e008e172013-06-13 20:15:48670} // namespace extensions