blob: b1ea01807a242d5081f01598421b159bcd3ae991 [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"
kalmanb0c1c502015-04-15 00:25:069#include "base/logging.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"
primiano7182d7b2015-01-30 18:02:0313#include "base/trace_event/trace_event.h"
sammcfb8875c2014-10-28 11:51:0414#include "content/public/renderer/render_frame.h"
[email protected]4f1633f2013-03-09 14:26:2415#include "content/public/renderer/render_view.h"
thestigb012bc3d2014-09-18 22:57:1316#include "extensions/common/extension.h"
[email protected]f55c90ee62014-04-12 00:50:0317#include "extensions/common/extensions_client.h"
18#include "extensions/renderer/console.h"
19#include "extensions/renderer/safe_builtins.h"
20#include "extensions/renderer/script_context.h"
[email protected]d9f51dad2014-07-09 05:39:3821#include "gin/modules/module_registry.h"
[email protected]2255a9332013-06-17 05:12:3122#include "third_party/WebKit/public/web/WebFrame.h"
23#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
[email protected]58e10452012-02-22 03:34:4524
[email protected]95ee77da2013-03-19 21:11:1125namespace extensions {
26
[email protected]58e10452012-02-22 03:34:4527namespace {
28
[email protected]561ddce2012-03-22 01:18:5529const char* kModuleSystem = "module_system";
30const char* kModuleName = "module_name";
31const char* kModuleField = "module_field";
[email protected]bad9a5f2012-04-13 19:16:5432const char* kModulesField = "modules";
[email protected]cc0457712012-03-21 03:56:3833
kalmanec0e3aa2015-04-28 21:50:3234// Logs an error for the calling context in preparation for potentially
35// crashing the renderer, with some added metadata about the context:
[email protected]662c48b2013-07-12 03:50:5236// - Its type (blessed, unblessed, etc).
37// - Whether it's valid.
38// - The extension ID, if one exists.
kalmanec0e3aa2015-04-28 21:50:3239// Crashing won't happen in stable/beta releases, but is encouraged to happen
40// in the less stable released to catch errors early.
[email protected]f55c90ee62014-04-12 00:50:0341void Fatal(ScriptContext* context, const std::string& message) {
[email protected]662c48b2013-07-12 03:50:5242 // Prepend some context metadata.
43 std::string full_message = "(";
44 if (!context->is_valid())
45 full_message += "Invalid ";
46 full_message += context->GetContextTypeDescription();
47 full_message += " context";
48 if (context->extension()) {
49 full_message += " for ";
50 full_message += context->extension()->id();
51 }
52 full_message += ") ";
53 full_message += message;
54
[email protected]f55c90ee62014-04-12 00:50:0355 if (ExtensionsClient::Get()->ShouldSuppressFatalErrors())
[email protected]95c6b3012013-12-02 14:30:3156 console::Error(context->isolate()->GetCallingContext(), full_message);
[email protected]f55c90ee62014-04-12 00:50:0357 else
58 console::Fatal(context->isolate()->GetCallingContext(), full_message);
[email protected]ad6aa8f92013-06-22 15:34:1659}
60
[email protected]95c6b3012013-12-02 14:30:3161void Warn(v8::Isolate* isolate, const std::string& message) {
62 console::Warn(isolate->GetCallingContext(), message);
[email protected]ad6aa8f92013-06-22 15:34:1663}
64
[email protected]68e63ea12013-06-05 05:00:5465// Default exception handler which logs the exception.
66class DefaultExceptionHandler : public ModuleSystem::ExceptionHandler {
67 public:
[email protected]f55c90ee62014-04-12 00:50:0368 explicit DefaultExceptionHandler(ScriptContext* context)
[email protected]662c48b2013-07-12 03:50:5269 : context_(context) {}
[email protected]ad6aa8f92013-06-22 15:34:1670
[email protected]68e63ea12013-06-05 05:00:5471 // Fatally dumps the debug info from |try_catch| to the console.
72 // Make sure this is never used for exceptions that originate in external
73 // code!
dcheng9168b2f2014-10-21 12:38:2474 void HandleUncaughtException(const v8::TryCatch& try_catch) override {
[email protected]dc3d06e2013-09-06 12:21:0375 v8::HandleScope handle_scope(context_->isolate());
[email protected]68e63ea12013-06-05 05:00:5476 std::string stack_trace = "<stack trace unavailable>";
77 if (!try_catch.StackTrace().IsEmpty()) {
78 v8::String::Utf8Value stack_value(try_catch.StackTrace());
79 if (*stack_value)
80 stack_trace.assign(*stack_value, stack_value.length());
81 else
82 stack_trace = "<could not convert stack trace to string>";
83 }
[email protected]662c48b2013-07-12 03:50:5284 Fatal(context_, CreateExceptionString(try_catch) + "{" + stack_trace + "}");
[email protected]68e63ea12013-06-05 05:00:5485 }
[email protected]ad6aa8f92013-06-22 15:34:1686
87 private:
[email protected]f55c90ee62014-04-12 00:50:0388 ScriptContext* context_;
[email protected]68e63ea12013-06-05 05:00:5489};
90
[email protected]f55c90ee62014-04-12 00:50:0391} // namespace
[email protected]68e63ea12013-06-05 05:00:5492
93std::string ModuleSystem::ExceptionHandler::CreateExceptionString(
94 const v8::TryCatch& try_catch) {
tfarinaf85316f2015-04-29 17:03:4095 v8::Local<v8::Message> message(try_catch.Message());
[email protected]95ee77da2013-03-19 21:11:1196 if (message.IsEmpty()) {
97 return "try_catch has no message";
98 }
[email protected]58e10452012-02-22 03:34:4599
[email protected]95ee77da2013-03-19 21:11:11100 std::string resource_name = "<unknown resource>";
[email protected]bce20ba2014-06-27 18:18:45101 if (!message->GetScriptOrigin().ResourceName().IsEmpty()) {
[email protected]95ee77da2013-03-19 21:11:11102 v8::String::Utf8Value resource_name_v8(
dcarneya261b772014-11-20 17:55:07103 message->GetScriptOrigin().ResourceName());
[email protected]95ee77da2013-03-19 21:11:11104 resource_name.assign(*resource_name_v8, resource_name_v8.length());
105 }
106
107 std::string error_message = "<no error message>";
108 if (!message->Get().IsEmpty()) {
109 v8::String::Utf8Value error_message_v8(message->Get());
110 error_message.assign(*error_message_v8, error_message_v8.length());
111 }
112
113 return base::StringPrintf("%s:%d: %s",
114 resource_name.c_str(),
115 message->GetLineNumber(),
116 error_message.c_str());
117}
118
[email protected]f55c90ee62014-04-12 00:50:03119ModuleSystem::ModuleSystem(ScriptContext* context, SourceMap* source_map)
[email protected]4f1633f2013-03-09 14:26:24120 : ObjectBackedNativeHandler(context),
[email protected]68e63ea12013-06-05 05:00:54121 context_(context),
[email protected]bad9a5f2012-04-13 19:16:54122 source_map_(source_map),
[email protected]68e63ea12013-06-05 05:00:54123 natives_enabled_(0),
[email protected]d9f51dad2014-07-09 05:39:38124 exception_handler_(new DefaultExceptionHandler(context)),
125 weak_factory_(this) {
[email protected]f55c90ee62014-04-12 00:50:03126 RouteFunction(
127 "require",
[email protected]ecde1912012-03-16 06:25:31128 base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this)));
[email protected]f55c90ee62014-04-12 00:50:03129 RouteFunction(
130 "requireNative",
[email protected]4f1633f2013-03-09 14:26:24131 base::Bind(&ModuleSystem::RequireNative, base::Unretained(this)));
[email protected]d9f51dad2014-07-09 05:39:38132 RouteFunction(
133 "requireAsync",
134 base::Bind(&ModuleSystem::RequireAsync, base::Unretained(this)));
[email protected]ca557292013-12-11 08:44:27135 RouteFunction("privates",
[email protected]f55c90ee62014-04-12 00:50:03136 base::Bind(&ModuleSystem::Private, base::Unretained(this)));
[email protected]ecde1912012-03-16 06:25:31137
tfarinaf85316f2015-04-29 17:03:40138 v8::Local<v8::Object> global(context->v8_context()->Global());
[email protected]505ffde2013-12-19 15:47:13139 v8::Isolate* isolate = context->isolate();
[email protected]f55c90ee62014-04-12 00:50:03140 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModulesField),
141 v8::Object::New(isolate));
142 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModuleSystem),
143 v8::External::New(isolate, this));
[email protected]d9f51dad2014-07-09 05:39:38144
145 gin::ModuleRegistry::From(context->v8_context())->AddObserver(this);
sammcfb8875c2014-10-28 11:51:04146 if (context_->GetRenderFrame()) {
147 context_->GetRenderFrame()->EnsureMojoBuiltinsAreAvailable(
148 context->isolate(), context->v8_context());
149 }
[email protected]58e10452012-02-22 03:34:45150}
151
kalmanb0c1c502015-04-15 00:25:06152ModuleSystem::~ModuleSystem() {
153}
[email protected]4f1633f2013-03-09 14:26:24154
155void ModuleSystem::Invalidate() {
[email protected]079532242013-03-12 06:01:10156 // Clear the module system properties from the global context. It's polite,
157 // and we use this as a signal in lazy handlers that we no longer exist.
158 {
[email protected]dc3d06e2013-09-06 12:21:03159 v8::HandleScope scope(GetIsolate());
tfarinaf85316f2015-04-29 17:03:40160 v8::Local<v8::Object> global = context()->v8_context()->Global();
[email protected]9c47471e2013-11-28 14:41:21161 global->DeleteHiddenValue(
162 v8::String::NewFromUtf8(GetIsolate(), kModulesField));
163 global->DeleteHiddenValue(
164 v8::String::NewFromUtf8(GetIsolate(), kModuleSystem));
[email protected]079532242013-03-12 06:01:10165 }
166
kalmanb0c1c502015-04-15 00:25:06167 // Invalidate all active and clobbered NativeHandlers we own.
168 for (const auto& handler : native_handler_map_)
169 handler.second->Invalidate();
170 for (const auto& clobbered_handler : clobbered_native_handlers_)
171 clobbered_handler->Invalidate();
[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
tfarinaf85316f2015-04-29 17:03:40191v8::Local<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) {
tfarinaf85316f2015-04-29 17:03:40199 v8::Local<v8::String> module_name = args[0]->ToString(args.GetIsolate());
[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(
tfarinaf85316f2015-04-29 17:03:40204 v8::Local<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
tfarinaf85316f2015-04-29 17:03:40208 v8::Local<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).
tfarinaf85316f2015-04-29 17:03:40213 v8::Local<v8::Value> modules_value = global->GetHiddenValue(
[email protected]9c47471e2013-11-28 14:41:21214 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
tfarinaf85316f2015-04-29 17:03:40220 v8::Local<v8::Object> modules(v8::Local<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());
tfarinaf85316f2015-04-29 17:03:40234 v8::Local<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,
tfarinaf85316f2015-04-29 17:03:40242 std::vector<v8::Local<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,
tfarinaf85316f2015-04-29 17:03:40251 v8::Local<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
tfarinaf85316f2015-04-29 17:03:40276 v8::Local<v8::Value> value = v8::Local<v8::Object>::Cast(module)->Get(
[email protected]f55c90ee62014-04-12 00:50:03277 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
tfarinaf85316f2015-04-29 17:03:40284 v8::Local<v8::Function> func = v8::Local<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) {
kalmanb0c1c502015-04-15 00:25:06299 ClobberExistingNativeHandler(name);
[email protected]58e10452012-02-22 03:34:45300 native_handler_map_[name] =
301 linked_ptr<NativeHandler>(native_handler.release());
302}
303
[email protected]95ee77da2013-03-19 21:11:11304void ModuleSystem::OverrideNativeHandlerForTest(const std::string& name) {
kalmanb0c1c502015-04-15 00:25:06305 ClobberExistingNativeHandler(name);
[email protected]11844fa2012-05-10 00:35:59306 overridden_native_handlers_.insert(name);
307}
308
[email protected]ecde1912012-03-16 06:25:31309void ModuleSystem::RunString(const std::string& code, const std::string& name) {
[email protected]dc3d06e2013-09-06 12:21:03310 v8::HandleScope handle_scope(GetIsolate());
[email protected]9c47471e2013-11-28 14:41:21311 RunString(v8::String::NewFromUtf8(GetIsolate(), code.c_str()),
312 v8::String::NewFromUtf8(GetIsolate(), name.c_str()));
[email protected]58e10452012-02-22 03:34:45313}
314
[email protected]cc0457712012-03-21 03:56:38315// static
[email protected]4e008e172013-06-13 20:15:48316void ModuleSystem::NativeLazyFieldGetter(
[email protected]4f1633f2013-03-09 14:26:24317 v8::Local<v8::String> property,
[email protected]4e008e172013-06-13 20:15:48318 const v8::PropertyCallbackInfo<v8::Value>& info) {
[email protected]f55c90ee62014-04-12 00:50:03319 LazyFieldGetterInner(property, info, &ModuleSystem::RequireNativeFromString);
[email protected]4e008e172013-06-13 20:15:48320}
321
322// static
323void ModuleSystem::LazyFieldGetter(
324 v8::Local<v8::String> property,
325 const v8::PropertyCallbackInfo<v8::Value>& info) {
326 LazyFieldGetterInner(property, info, &ModuleSystem::Require);
327}
328
329// static
330void ModuleSystem::LazyFieldGetterInner(
331 v8::Local<v8::String> property,
332 const v8::PropertyCallbackInfo<v8::Value>& info,
[email protected]4f1633f2013-03-09 14:26:24333 RequireFunction require_function) {
[email protected]561ddce2012-03-22 01:18:55334 CHECK(!info.Data().IsEmpty());
335 CHECK(info.Data()->IsObject());
[email protected]dc3d06e2013-09-06 12:21:03336 v8::HandleScope handle_scope(info.GetIsolate());
tfarinaf85316f2015-04-29 17:03:40337 v8::Local<v8::Object> parameters = v8::Local<v8::Object>::Cast(info.Data());
[email protected]9a598442013-06-04 16:39:12338 // This context should be the same as context()->v8_context().
tfarinaf85316f2015-04-29 17:03:40339 v8::Local<v8::Context> context = parameters->CreationContext();
340 v8::Local<v8::Object> global(context->Global());
341 v8::Local<v8::Value> module_system_value = global->GetHiddenValue(
[email protected]9c47471e2013-11-28 14:41:21342 v8::String::NewFromUtf8(info.GetIsolate(), kModuleSystem));
[email protected]95ee77da2013-03-19 21:11:11343 if (module_system_value.IsEmpty() || !module_system_value->IsExternal()) {
[email protected]bad9a5f2012-04-13 19:16:54344 // ModuleSystem has been deleted.
[email protected]95ee77da2013-03-19 21:11:11345 // TODO(kalman): See comment in header file.
[email protected]95c6b3012013-12-02 14:30:31346 Warn(info.GetIsolate(),
347 "Module system has been deleted, does extension view exist?");
[email protected]4e008e172013-06-13 20:15:48348 return;
[email protected]bad9a5f2012-04-13 19:16:54349 }
[email protected]95ee77da2013-03-19 21:11:11350
[email protected]561ddce2012-03-22 01:18:55351 ModuleSystem* module_system = static_cast<ModuleSystem*>(
tfarinaf85316f2015-04-29 17:03:40352 v8::Local<v8::External>::Cast(module_system_value)->Value());
[email protected]cc0457712012-03-21 03:56:38353
dcarneya261b772014-11-20 17:55:07354 std::string name = *v8::String::Utf8Value(parameters->Get(
355 v8::String::NewFromUtf8(info.GetIsolate(), kModuleName)));
[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;
tfarinaf85316f2015-04-29 17:03:40363 v8::Local<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
tfarinaf85316f2015-04-29 17:03:40373 v8::Local<v8::Object> module = v8::Local<v8::Object>::Cast(module_value);
374 v8::Local<v8::String> field =
[email protected]9c47471e2013-11-28 14:41:21375 parameters->Get(v8::String::NewFromUtf8(info.GetIsolate(), kModuleField))
dcarneya261b772014-11-20 17:55:07376 ->ToString(info.GetIsolate());
[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.
tfarinaf85316f2015-04-29 17:03:40398 v8::Local<v8::Value> val = info.This();
[email protected]80b0c8c2014-04-22 15:00:43399 if (val->IsObject()) {
tfarinaf85316f2015-04-29 17:03:40400 v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(val);
[email protected]80b0c8c2014-04-22 15:00:43401 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
tfarinaf85316f2015-04-29 17:03:40409void ModuleSystem::SetLazyField(v8::Local<v8::Object> object,
[email protected]561ddce2012-03-22 01:18:55410 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
tfarinaf85316f2015-04-29 17:03:40417void ModuleSystem::SetLazyField(v8::Local<v8::Object> object,
[email protected]4f1633f2013-03-09 14:26:24418 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());
tfarinaf85316f2015-04-29 17:03:40423 v8::Local<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
tfarinaf85316f2015-04-29 17:03:40434void ModuleSystem::SetNativeLazyField(v8::Local<v8::Object> object,
[email protected]4f1633f2013-03-09 14:26:24435 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
tfarinaf85316f2015-04-29 17:03:40445v8::Local<v8::Value> ModuleSystem::RunString(v8::Local<v8::String> code,
446 v8::Local<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);
tfarinaf85316f2015-04-29 17:03:40458 v8::Local<v8::Script> script(v8::Script::Compile(
459 code, v8::String::NewFromUtf8(GetIsolate(), internal_name.c_str(),
460 v8::String::kNormalString,
461 internal_name.size())));
[email protected]7c95c1a82012-04-17 02:11:33462 if (try_catch.HasCaught()) {
[email protected]144114942012-12-04 07:23:23463 HandleException(try_catch);
[email protected]95c6b3012013-12-02 14:30:31464 return v8::Undefined(GetIsolate());
[email protected]7c95c1a82012-04-17 02:11:33465 }
466
[email protected]95c6b3012013-12-02 14:30:31467 v8::Local<v8::Value> result = script->Run();
[email protected]95ee77da2013-03-19 21:11:11468 if (try_catch.HasCaught()) {
[email protected]144114942012-12-04 07:23:23469 HandleException(try_catch);
[email protected]95c6b3012013-12-02 14:30:31470 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11471 }
[email protected]7c95c1a82012-04-17 02:11:33472
[email protected]95c6b3012013-12-02 14:30:31473 return handle_scope.Escape(result);
[email protected]9e03ce22012-03-13 08:50:05474}
475
tfarinaf85316f2015-04-29 17:03:40476v8::Local<v8::Value> ModuleSystem::GetSource(const std::string& module_name) {
[email protected]95c6b3012013-12-02 14:30:31477 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]ecde1912012-03-16 06:25:31478 if (!source_map_->Contains(module_name))
[email protected]95c6b3012013-12-02 14:30:31479 return v8::Undefined(GetIsolate());
480 return handle_scope.Escape(
481 v8::Local<v8::Value>(source_map_->GetSource(GetIsolate(), module_name)));
[email protected]58e10452012-02-22 03:34:45482}
483
[email protected]d8c5fbb2013-06-14 11:35:25484void ModuleSystem::RequireNative(
485 const v8::FunctionCallbackInfo<v8::Value>& args) {
[email protected]58e10452012-02-22 03:34:45486 CHECK_EQ(1, args.Length());
dcarneya261b772014-11-20 17:55:07487 std::string native_name = *v8::String::Utf8Value(args[0]);
[email protected]d8c5fbb2013-06-14 11:35:25488 args.GetReturnValue().Set(RequireNativeFromString(native_name));
[email protected]4f1633f2013-03-09 14:26:24489}
490
tfarinaf85316f2015-04-29 17:03:40491v8::Local<v8::Value> ModuleSystem::RequireNativeFromString(
[email protected]4f1633f2013-03-09 14:26:24492 const std::string& native_name) {
[email protected]95ee77da2013-03-19 21:11:11493 if (natives_enabled_ == 0) {
494 // HACK: if in test throw exception so that we can test the natives-disabled
495 // logic; however, under normal circumstances, this is programmer error so
496 // we could crash.
[email protected]9c47471e2013-11-28 14:41:21497 if (exception_handler_) {
[email protected]95c6b3012013-12-02 14:30:31498 return GetIsolate()->ThrowException(
[email protected]9c47471e2013-11-28 14:41:21499 v8::String::NewFromUtf8(GetIsolate(), "Natives disabled"));
500 }
[email protected]662c48b2013-07-12 03:50:52501 Fatal(context_, "Natives disabled for requireNative(" + native_name + ")");
[email protected]95c6b3012013-12-02 14:30:31502 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11503 }
504
[email protected]9c47471e2013-11-28 14:41:21505 if (overridden_native_handlers_.count(native_name) > 0u) {
506 return RequireForJsInner(
507 v8::String::NewFromUtf8(GetIsolate(), native_name.c_str()));
508 }
[email protected]95ee77da2013-03-19 21:11:11509
[email protected]58e10452012-02-22 03:34:45510 NativeHandlerMap::iterator i = native_handler_map_.find(native_name);
[email protected]95ee77da2013-03-19 21:11:11511 if (i == native_handler_map_.end()) {
[email protected]662c48b2013-07-12 03:50:52512 Fatal(context_,
[email protected]ad6aa8f92013-06-22 15:34:16513 "Couldn't find native for requireNative(" + native_name + ")");
[email protected]95c6b3012013-12-02 14:30:31514 return v8::Undefined(GetIsolate());
[email protected]95ee77da2013-03-19 21:11:11515 }
[email protected]58e10452012-02-22 03:34:45516 return i->second->NewInstance();
517}
[email protected]ecde1912012-03-16 06:25:31518
[email protected]d9f51dad2014-07-09 05:39:38519void ModuleSystem::RequireAsync(
520 const v8::FunctionCallbackInfo<v8::Value>& args) {
521 CHECK_EQ(1, args.Length());
dcarneya261b772014-11-20 17:55:07522 std::string module_name = *v8::String::Utf8Value(args[0]);
tfarinaf85316f2015-04-29 17:03:40523 v8::Local<v8::Promise::Resolver> resolver(
[email protected]d9f51dad2014-07-09 05:39:38524 v8::Promise::Resolver::New(GetIsolate()));
525 args.GetReturnValue().Set(resolver->GetPromise());
kalman83292b82015-03-12 16:40:25526 scoped_ptr<v8::Global<v8::Promise::Resolver>> global_resolver(
527 new v8::Global<v8::Promise::Resolver>(GetIsolate(), resolver));
[email protected]d9f51dad2014-07-09 05:39:38528 gin::ModuleRegistry* module_registry =
529 gin::ModuleRegistry::From(context_->v8_context());
530 if (!module_registry) {
531 Warn(GetIsolate(), "Extension view no longer exists");
532 resolver->Reject(v8::Exception::Error(v8::String::NewFromUtf8(
533 GetIsolate(), "Extension view no longer exists")));
534 return;
535 }
kalman83292b82015-03-12 16:40:25536 module_registry->LoadModule(
537 GetIsolate(), module_name,
538 base::Bind(&ModuleSystem::OnModuleLoaded, weak_factory_.GetWeakPtr(),
539 base::Passed(&global_resolver)));
[email protected]d9f51dad2014-07-09 05:39:38540 if (module_registry->available_modules().count(module_name) == 0)
541 LoadModule(module_name);
542}
543
tfarinaf85316f2015-04-29 17:03:40544v8::Local<v8::String> ModuleSystem::WrapSource(v8::Local<v8::String> source) {
[email protected]95c6b3012013-12-02 14:30:31545 v8::EscapableHandleScope handle_scope(GetIsolate());
[email protected]295890bd2013-06-15 10:52:45546 // Keep in order with the arguments in RequireForJsInner.
tfarinaf85316f2015-04-29 17:03:40547 v8::Local<v8::String> left = v8::String::NewFromUtf8(
[email protected]2a356872014-02-21 23:18:52548 GetIsolate(),
[email protected]d9f51dad2014-07-09 05:39:38549 "(function(define, require, requireNative, requireAsync, exports, "
[email protected]2a356872014-02-21 23:18:52550 "console, privates,"
[email protected]0d775c72014-08-22 13:06:26551 "$Array, $Function, $JSON, $Object, $RegExp, $String, $Error) {"
[email protected]2a356872014-02-21 23:18:52552 "'use strict';");
tfarinaf85316f2015-04-29 17:03:40553 v8::Local<v8::String> right = v8::String::NewFromUtf8(GetIsolate(), "\n})");
[email protected]95c6b3012013-12-02 14:30:31554 return handle_scope.Escape(v8::Local<v8::String>(
555 v8::String::Concat(left, v8::String::Concat(source, right))));
[email protected]ecde1912012-03-16 06:25:31556}
557
[email protected]ca557292013-12-11 08:44:27558void ModuleSystem::Private(const v8::FunctionCallbackInfo<v8::Value>& args) {
559 CHECK_EQ(1, args.Length());
rob5c641ed2014-12-09 00:24:57560 if (!args[0]->IsObject() || args[0]->IsNull()) {
561 GetIsolate()->ThrowException(
562 v8::Exception::TypeError(v8::String::NewFromUtf8(GetIsolate(),
563 args[0]->IsUndefined()
564 ? "Method called without a valid receiver (this). "
565 "Did you forget to call .bind()?"
566 : "Invalid invocation: receiver is not an object!")));
567 return;
568 }
[email protected]ca557292013-12-11 08:44:27569 v8::Local<v8::Object> obj = args[0].As<v8::Object>();
570 v8::Local<v8::String> privates_key =
571 v8::String::NewFromUtf8(GetIsolate(), "privates");
572 v8::Local<v8::Value> privates = obj->GetHiddenValue(privates_key);
573 if (privates.IsEmpty()) {
[email protected]505ffde2013-12-19 15:47:13574 privates = v8::Object::New(args.GetIsolate());
kalmanad8ddd02014-10-15 00:20:06575 if (privates.IsEmpty()) {
576 GetIsolate()->ThrowException(
577 v8::String::NewFromUtf8(GetIsolate(), "Failed to create privates"));
578 return;
579 }
[email protected]ca557292013-12-11 08:44:27580 obj->SetHiddenValue(privates_key, privates);
581 }
582 args.GetReturnValue().Set(privates);
583}
584
tfarinaf85316f2015-04-29 17:03:40585v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
[email protected]d9f51dad2014-07-09 05:39:38586 v8::EscapableHandleScope handle_scope(GetIsolate());
587 v8::Context::Scope context_scope(context()->v8_context());
588
tfarinaf85316f2015-04-29 17:03:40589 v8::Local<v8::Value> source(GetSource(module_name));
[email protected]d9f51dad2014-07-09 05:39:38590 if (source.IsEmpty() || source->IsUndefined()) {
591 Fatal(context_, "No source for require(" + module_name + ")");
592 return v8::Undefined(GetIsolate());
593 }
tfarinaf85316f2015-04-29 17:03:40594 v8::Local<v8::String> wrapped_source(
595 WrapSource(v8::Local<v8::String>::Cast(source)));
[email protected]d9f51dad2014-07-09 05:39:38596 // Modules are wrapped in (function(){...}) so they always return functions.
tfarinaf85316f2015-04-29 17:03:40597 v8::Local<v8::Value> func_as_value =
[email protected]d9f51dad2014-07-09 05:39:38598 RunString(wrapped_source,
599 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
600 if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
601 Fatal(context_, "Bad source for require(" + module_name + ")");
602 return v8::Undefined(GetIsolate());
603 }
604
tfarinaf85316f2015-04-29 17:03:40605 v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
[email protected]d9f51dad2014-07-09 05:39:38606
tfarinaf85316f2015-04-29 17:03:40607 v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
[email protected]d9f51dad2014-07-09 05:39:38608 gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
609
610 v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
tfarinaf85316f2015-04-29 17:03:40611 v8::Local<v8::Object> natives(NewInstance());
[email protected]d9f51dad2014-07-09 05:39:38612 CHECK(!natives.IsEmpty()); // this can happen if v8 has issues
613
614 // These must match the argument order in WrapSource.
tfarinaf85316f2015-04-29 17:03:40615 v8::Local<v8::Value> args[] = {
[email protected]d9f51dad2014-07-09 05:39:38616 // AMD.
617 define_object->Get(v8::String::NewFromUtf8(GetIsolate(), "define")),
618 // CommonJS.
tfarinaf85316f2015-04-29 17:03:40619 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "require",
620 v8::String::kInternalizedString)),
621 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "requireNative",
622 v8::String::kInternalizedString)),
623 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "requireAsync",
624 v8::String::kInternalizedString)),
[email protected]d9f51dad2014-07-09 05:39:38625 exports,
626 // Libraries that we magically expose to every module.
kalmanfb6f10ac2014-11-06 23:55:35627 console::AsV8Object(GetIsolate()),
tfarinaf85316f2015-04-29 17:03:40628 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "privates",
629 v8::String::kInternalizedString)),
[email protected]d9f51dad2014-07-09 05:39:38630 // Each safe builtin. Keep in order with the arguments in WrapSource.
631 context_->safe_builtins()->GetArray(),
632 context_->safe_builtins()->GetFunction(),
633 context_->safe_builtins()->GetJSON(),
634 context_->safe_builtins()->GetObjekt(),
635 context_->safe_builtins()->GetRegExp(),
636 context_->safe_builtins()->GetString(),
[email protected]0d775c72014-08-22 13:06:26637 context_->safe_builtins()->GetError(),
[email protected]d9f51dad2014-07-09 05:39:38638 };
639 {
640 v8::TryCatch try_catch;
641 try_catch.SetCaptureMessage(true);
642 context_->CallFunction(func, arraysize(args), args);
643 if (try_catch.HasCaught()) {
644 HandleException(try_catch);
645 return v8::Undefined(GetIsolate());
646 }
647 }
648 return handle_scope.Escape(exports);
649}
650
651void ModuleSystem::OnDidAddPendingModule(
652 const std::string& id,
653 const std::vector<std::string>& dependencies) {
sammc2cc226562015-01-14 01:25:06654 bool module_system_managed = source_map_->Contains(id);
[email protected]d9f51dad2014-07-09 05:39:38655
656 gin::ModuleRegistry* registry =
657 gin::ModuleRegistry::From(context_->v8_context());
658 DCHECK(registry);
sammc2cc226562015-01-14 01:25:06659 for (const auto& dependency : dependencies) {
660 // If a dependency is not available, and either the module or this
661 // dependency is managed by ModuleSystem, attempt to load it. Other
662 // gin::ModuleRegistry users (WebUI and users of the mojoPrivate API) are
663 // responsible for loading their module dependencies when required.
664 if (registry->available_modules().count(dependency) == 0 &&
665 (module_system_managed || source_map_->Contains(dependency))) {
666 LoadModule(dependency);
667 }
[email protected]d9f51dad2014-07-09 05:39:38668 }
669 registry->AttemptToLoadMoreModules(GetIsolate());
670}
671
672void ModuleSystem::OnModuleLoaded(
kalman83292b82015-03-12 16:40:25673 scoped_ptr<v8::Global<v8::Promise::Resolver>> resolver,
tfarinaf85316f2015-04-29 17:03:40674 v8::Local<v8::Value> value) {
[email protected]d9f51dad2014-07-09 05:39:38675 if (!is_valid())
676 return;
677 v8::HandleScope handle_scope(GetIsolate());
tfarinaf85316f2015-04-29 17:03:40678 v8::Local<v8::Promise::Resolver> resolver_local(
[email protected]d9f51dad2014-07-09 05:39:38679 v8::Local<v8::Promise::Resolver>::New(GetIsolate(), *resolver));
680 resolver_local->Resolve(value);
681}
682
kalmanb0c1c502015-04-15 00:25:06683void ModuleSystem::ClobberExistingNativeHandler(const std::string& name) {
684 NativeHandlerMap::iterator existing_handler = native_handler_map_.find(name);
685 if (existing_handler != native_handler_map_.end()) {
686 clobbered_native_handlers_.push_back(existing_handler->second);
687 native_handler_map_.erase(existing_handler);
688 }
689}
690
[email protected]4e008e172013-06-13 20:15:48691} // namespace extensions