Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(323)

Side by Side Diff: extensions/renderer/module_system.cc

Issue 1185443004: extensions: Use V8 Maybe APIs in ModuleSystem (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "extensions/renderer/module_system.h" 5 #include "extensions/renderer/module_system.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/command_line.h" 8 #include "base/command_line.h"
9 #include "base/logging.h" 9 #include "base/logging.h"
10 #include "base/stl_util.h" 10 #include "base/stl_util.h"
11 #include "base/strings/string_util.h" 11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h" 12 #include "base/strings/stringprintf.h"
13 #include "base/trace_event/trace_event.h" 13 #include "base/trace_event/trace_event.h"
14 #include "content/public/renderer/render_frame.h" 14 #include "content/public/renderer/render_frame.h"
15 #include "content/public/renderer/render_view.h" 15 #include "content/public/renderer/render_view.h"
16 #include "extensions/common/extension.h" 16 #include "extensions/common/extension.h"
17 #include "extensions/common/extensions_client.h" 17 #include "extensions/common/extensions_client.h"
18 #include "extensions/renderer/console.h" 18 #include "extensions/renderer/console.h"
19 #include "extensions/renderer/safe_builtins.h" 19 #include "extensions/renderer/safe_builtins.h"
20 #include "extensions/renderer/script_context.h" 20 #include "extensions/renderer/script_context.h"
21 #include "extensions/renderer/v8_helpers.h"
21 #include "gin/modules/module_registry.h" 22 #include "gin/modules/module_registry.h"
22 #include "third_party/WebKit/public/web/WebFrame.h" 23 #include "third_party/WebKit/public/web/WebFrame.h"
23 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" 24 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
24 25
25 namespace extensions { 26 namespace extensions {
26 27
28 using namespace v8_helpers;
29
27 namespace { 30 namespace {
28 31
29 const char* kModuleSystem = "module_system"; 32 const char* kModuleSystem = "module_system";
30 const char* kModuleName = "module_name"; 33 const char* kModuleName = "module_name";
31 const char* kModuleField = "module_field"; 34 const char* kModuleField = "module_field";
32 const char* kModulesField = "modules"; 35 const char* kModulesField = "modules";
33 36
34 // Logs an error for the calling context in preparation for potentially 37 // Logs an error for the calling context in preparation for potentially
35 // crashing the renderer, with some added metadata about the context: 38 // crashing the renderer, with some added metadata about the context:
36 // - Its type (blessed, unblessed, etc). 39 // - Its type (blessed, unblessed, etc).
(...skipping 25 matching lines...) Expand all
62 } 65 }
63 66
64 void Warn(v8::Isolate* isolate, const std::string& message) { 67 void Warn(v8::Isolate* isolate, const std::string& message) {
65 console::Warn(isolate->GetCallingContext(), message); 68 console::Warn(isolate->GetCallingContext(), message);
66 } 69 }
67 70
68 // Default exception handler which logs the exception. 71 // Default exception handler which logs the exception.
69 class DefaultExceptionHandler : public ModuleSystem::ExceptionHandler { 72 class DefaultExceptionHandler : public ModuleSystem::ExceptionHandler {
70 public: 73 public:
71 explicit DefaultExceptionHandler(ScriptContext* context) 74 explicit DefaultExceptionHandler(ScriptContext* context)
72 : context_(context) {} 75 : ModuleSystem::ExceptionHandler(context) {}
73 76
74 // Fatally dumps the debug info from |try_catch| to the console. 77 // Fatally dumps the debug info from |try_catch| to the console.
75 // Make sure this is never used for exceptions that originate in external 78 // Make sure this is never used for exceptions that originate in external
76 // code! 79 // code!
77 void HandleUncaughtException(const v8::TryCatch& try_catch) override { 80 void HandleUncaughtException(const v8::TryCatch& try_catch) override {
78 v8::HandleScope handle_scope(context_->isolate()); 81 v8::HandleScope handle_scope(context_->isolate());
79 std::string stack_trace = "<stack trace unavailable>"; 82 std::string stack_trace = "<stack trace unavailable>";
80 if (!try_catch.StackTrace().IsEmpty()) { 83 v8::Local<v8::Value> v8_stack_trace;
81 v8::String::Utf8Value stack_value(try_catch.StackTrace()); 84 if (try_catch.StackTrace(context_->v8_context()).ToLocal(&v8_stack_trace)) {
85 v8::String::Utf8Value stack_value(v8_stack_trace);
82 if (*stack_value) 86 if (*stack_value)
83 stack_trace.assign(*stack_value, stack_value.length()); 87 stack_trace.assign(*stack_value, stack_value.length());
84 else 88 else
85 stack_trace = "<could not convert stack trace to string>"; 89 stack_trace = "<could not convert stack trace to string>";
86 } 90 }
87 Fatal(context_, CreateExceptionString(try_catch) + "{" + stack_trace + "}"); 91 Fatal(context_,
92 CreateExceptionString(try_catch) + "{" + stack_trace + "}");
not at google - send to devlin 2015/06/16 20:52:24 Is this formatting change necessary? Either way, r
bashi 2015/06/17 01:40:45 Reverted.
88 } 93 }
89 94
90 private: 95 private:
91 ScriptContext* context_; 96 ScriptContext* context_;
92 }; 97 };
93 98
94 } // namespace 99 } // namespace
95 100
96 std::string ModuleSystem::ExceptionHandler::CreateExceptionString( 101 std::string ModuleSystem::ExceptionHandler::CreateExceptionString(
97 const v8::TryCatch& try_catch) { 102 const v8::TryCatch& try_catch) {
98 v8::Local<v8::Message> message(try_catch.Message()); 103 v8::Local<v8::Message> message(try_catch.Message());
99 if (message.IsEmpty()) { 104 if (message.IsEmpty()) {
100 return "try_catch has no message"; 105 return "try_catch has no message";
101 } 106 }
102 107
103 std::string resource_name = "<unknown resource>"; 108 std::string resource_name = "<unknown resource>";
104 if (!message->GetScriptOrigin().ResourceName().IsEmpty()) { 109 if (!message->GetScriptOrigin().ResourceName().IsEmpty()) {
105 v8::String::Utf8Value resource_name_v8( 110 v8::String::Utf8Value resource_name_v8(
106 message->GetScriptOrigin().ResourceName()); 111 message->GetScriptOrigin().ResourceName());
107 resource_name.assign(*resource_name_v8, resource_name_v8.length()); 112 resource_name.assign(*resource_name_v8, resource_name_v8.length());
108 } 113 }
109 114
110 std::string error_message = "<no error message>"; 115 std::string error_message = "<no error message>";
111 if (!message->Get().IsEmpty()) { 116 if (!message->Get().IsEmpty()) {
112 v8::String::Utf8Value error_message_v8(message->Get()); 117 v8::String::Utf8Value error_message_v8(message->Get());
113 error_message.assign(*error_message_v8, error_message_v8.length()); 118 error_message.assign(*error_message_v8, error_message_v8.length());
114 } 119 }
115 120
121 auto maybe = message->GetLineNumber(context_->v8_context());
122 int line_number = maybe.IsJust() ? maybe.FromJust() : 0;
116 return base::StringPrintf("%s:%d: %s", 123 return base::StringPrintf("%s:%d: %s",
117 resource_name.c_str(), 124 resource_name.c_str(),
118 message->GetLineNumber(), 125 line_number,
119 error_message.c_str()); 126 error_message.c_str());
120 } 127 }
121 128
122 ModuleSystem::ModuleSystem(ScriptContext* context, SourceMap* source_map) 129 ModuleSystem::ModuleSystem(ScriptContext* context, SourceMap* source_map)
123 : ObjectBackedNativeHandler(context), 130 : ObjectBackedNativeHandler(context),
124 context_(context), 131 context_(context),
125 source_map_(source_map), 132 source_map_(source_map),
126 natives_enabled_(0), 133 natives_enabled_(0),
127 exception_handler_(new DefaultExceptionHandler(context)), 134 exception_handler_(new DefaultExceptionHandler(context)),
128 weak_factory_(this) { 135 weak_factory_(this) {
129 RouteFunction( 136 RouteFunction(
130 "require", 137 "require",
131 base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this))); 138 base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this)));
132 RouteFunction( 139 RouteFunction(
133 "requireNative", 140 "requireNative",
134 base::Bind(&ModuleSystem::RequireNative, base::Unretained(this))); 141 base::Bind(&ModuleSystem::RequireNative, base::Unretained(this)));
135 RouteFunction( 142 RouteFunction(
136 "requireAsync", 143 "requireAsync",
137 base::Bind(&ModuleSystem::RequireAsync, base::Unretained(this))); 144 base::Bind(&ModuleSystem::RequireAsync, base::Unretained(this)));
138 RouteFunction("privates", 145 RouteFunction("privates",
139 base::Bind(&ModuleSystem::Private, base::Unretained(this))); 146 base::Bind(&ModuleSystem::Private, base::Unretained(this)));
140 147
141 v8::Local<v8::Object> global(context->v8_context()->Global()); 148 v8::Local<v8::Object> global(context->v8_context()->Global());
142 v8::Isolate* isolate = context->isolate(); 149 v8::Isolate* isolate = context->isolate();
143 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModulesField), 150 global->SetHiddenValue(ToV8StringUnsafe(isolate, kModulesField),
144 v8::Object::New(isolate)); 151 v8::Object::New(isolate));
145 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModuleSystem), 152 global->SetHiddenValue(ToV8StringUnsafe(isolate, kModuleSystem),
146 v8::External::New(isolate, this)); 153 v8::External::New(isolate, this));
147 154
148 gin::ModuleRegistry::From(context->v8_context())->AddObserver(this); 155 gin::ModuleRegistry::From(context->v8_context())->AddObserver(this);
149 if (context_->GetRenderFrame()) { 156 if (context_->GetRenderFrame()) {
150 context_->GetRenderFrame()->EnsureMojoBuiltinsAreAvailable( 157 context_->GetRenderFrame()->EnsureMojoBuiltinsAreAvailable(
151 context->isolate(), context->v8_context()); 158 context->isolate(), context->v8_context());
152 } 159 }
153 } 160 }
154 161
155 ModuleSystem::~ModuleSystem() { 162 ModuleSystem::~ModuleSystem() {
156 } 163 }
157 164
158 void ModuleSystem::Invalidate() { 165 void ModuleSystem::Invalidate() {
159 // Clear the module system properties from the global context. It's polite, 166 // Clear the module system properties from the global context. It's polite,
160 // and we use this as a signal in lazy handlers that we no longer exist. 167 // and we use this as a signal in lazy handlers that we no longer exist.
161 { 168 {
162 v8::HandleScope scope(GetIsolate()); 169 v8::HandleScope scope(GetIsolate());
163 v8::Local<v8::Object> global = context()->v8_context()->Global(); 170 v8::Local<v8::Object> global = context()->v8_context()->Global();
164 global->DeleteHiddenValue( 171 global->DeleteHiddenValue(ToV8StringUnsafe(GetIsolate(), kModulesField));
165 v8::String::NewFromUtf8(GetIsolate(), kModulesField)); 172 global->DeleteHiddenValue(ToV8StringUnsafe(GetIsolate(), kModuleSystem));
166 global->DeleteHiddenValue(
167 v8::String::NewFromUtf8(GetIsolate(), kModuleSystem));
168 } 173 }
169 174
170 // Invalidate all active and clobbered NativeHandlers we own. 175 // Invalidate all active and clobbered NativeHandlers we own.
171 for (const auto& handler : native_handler_map_) 176 for (const auto& handler : native_handler_map_)
172 handler.second->Invalidate(); 177 handler.second->Invalidate();
173 for (const auto& clobbered_handler : clobbered_native_handlers_) 178 for (const auto& clobbered_handler : clobbered_native_handlers_)
174 clobbered_handler->Invalidate(); 179 clobbered_handler->Invalidate();
175 180
176 ObjectBackedNativeHandler::Invalidate(); 181 ObjectBackedNativeHandler::Invalidate();
177 } 182 }
178 183
179 ModuleSystem::NativesEnabledScope::NativesEnabledScope( 184 ModuleSystem::NativesEnabledScope::NativesEnabledScope(
180 ModuleSystem* module_system) 185 ModuleSystem* module_system)
181 : module_system_(module_system) { 186 : module_system_(module_system) {
182 module_system_->natives_enabled_++; 187 module_system_->natives_enabled_++;
183 } 188 }
184 189
185 ModuleSystem::NativesEnabledScope::~NativesEnabledScope() { 190 ModuleSystem::NativesEnabledScope::~NativesEnabledScope() {
186 module_system_->natives_enabled_--; 191 module_system_->natives_enabled_--;
187 CHECK_GE(module_system_->natives_enabled_, 0); 192 CHECK_GE(module_system_->natives_enabled_, 0);
188 } 193 }
189 194
190 void ModuleSystem::HandleException(const v8::TryCatch& try_catch) { 195 void ModuleSystem::HandleException(const v8::TryCatch& try_catch) {
191 exception_handler_->HandleUncaughtException(try_catch); 196 exception_handler_->HandleUncaughtException(try_catch);
192 } 197 }
193 198
194 v8::Local<v8::Value> ModuleSystem::Require(const std::string& module_name) { 199 v8::Local<v8::Value> ModuleSystem::Require(const std::string& module_name) {
200 if (module_name.size() >= v8::String::kMaxLength)
201 return v8::Undefined(GetIsolate());
195 v8::EscapableHandleScope handle_scope(GetIsolate()); 202 v8::EscapableHandleScope handle_scope(GetIsolate());
196 return handle_scope.Escape(RequireForJsInner( 203 return handle_scope.Escape(RequireForJsInner(
197 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()))); 204 ToV8StringUnsafe(GetIsolate(), module_name.c_str())));
198 } 205 }
199 206
200 void ModuleSystem::RequireForJs( 207 void ModuleSystem::RequireForJs(
201 const v8::FunctionCallbackInfo<v8::Value>& args) { 208 const v8::FunctionCallbackInfo<v8::Value>& args) {
202 v8::Local<v8::String> module_name = args[0]->ToString(args.GetIsolate()); 209 if (!args[0]->IsString()) {
210 NOTREACHED() << "require() called with a non-string argument";
211 return;
212 }
213 v8::Local<v8::String> module_name = args[0].As<v8::String>();
203 args.GetReturnValue().Set(RequireForJsInner(module_name)); 214 args.GetReturnValue().Set(RequireForJsInner(module_name));
204 } 215 }
205 216
206 v8::Local<v8::Value> ModuleSystem::RequireForJsInner( 217 v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
207 v8::Local<v8::String> module_name) { 218 v8::Local<v8::String> module_name) {
208 v8::EscapableHandleScope handle_scope(GetIsolate()); 219 v8::EscapableHandleScope handle_scope(GetIsolate());
209 v8::Context::Scope context_scope(context()->v8_context()); 220 v8::Local<v8::Context> v8_context = context()->v8_context();
221 v8::Context::Scope context_scope(v8_context);
210 222
211 v8::Local<v8::Object> global(context()->v8_context()->Global()); 223 v8::Local<v8::Object> global(context()->v8_context()->Global());
212 224
213 // The module system might have been deleted. This can happen if a different 225 // The module system might have been deleted. This can happen if a different
214 // context keeps a reference to us, but our frame is destroyed (e.g. 226 // context keeps a reference to us, but our frame is destroyed (e.g.
215 // background page keeps reference to chrome object in a closed popup). 227 // background page keeps reference to chrome object in a closed popup).
216 v8::Local<v8::Value> modules_value = global->GetHiddenValue( 228 v8::Local<v8::Value> modules_value = global->GetHiddenValue(
217 v8::String::NewFromUtf8(GetIsolate(), kModulesField)); 229 ToV8StringUnsafe(GetIsolate(), kModulesField));
218 if (modules_value.IsEmpty() || modules_value->IsUndefined()) { 230 if (modules_value.IsEmpty() || modules_value->IsUndefined()) {
219 Warn(GetIsolate(), "Extension view no longer exists"); 231 Warn(GetIsolate(), "Extension view no longer exists");
220 return v8::Undefined(GetIsolate()); 232 return v8::Undefined(GetIsolate());
221 } 233 }
222 234
223 v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); 235 v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value));
224 v8::Local<v8::Value> exports(modules->Get(module_name)); 236 v8::Local<v8::Value> exports;
225 if (!exports->IsUndefined()) 237 if (!modules->Get(v8_context, module_name).ToLocal(&exports) ||
238 !exports->IsUndefined())
226 return handle_scope.Escape(exports); 239 return handle_scope.Escape(exports);
227 240
228 exports = LoadModule(*v8::String::Utf8Value(module_name)); 241 exports = LoadModule(*v8::String::Utf8Value(module_name));
229 modules->Set(module_name, exports); 242 SetProperty(v8_context, modules, module_name, exports);
230 return handle_scope.Escape(exports); 243 return handle_scope.Escape(exports);
231 } 244 }
232 245
233 v8::Local<v8::Value> ModuleSystem::CallModuleMethod( 246 v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
234 const std::string& module_name, 247 const std::string& module_name,
235 const std::string& method_name) { 248 const std::string& method_name) {
236 v8::EscapableHandleScope handle_scope(GetIsolate()); 249 v8::EscapableHandleScope handle_scope(GetIsolate());
237 v8::Local<v8::Value> no_args; 250 v8::Local<v8::Value> no_args;
238 return handle_scope.Escape( 251 return handle_scope.Escape(
239 CallModuleMethod(module_name, method_name, 0, &no_args)); 252 CallModuleMethod(module_name, method_name, 0, &no_args));
(...skipping 13 matching lines...) Expand all
253 int argc, 266 int argc,
254 v8::Local<v8::Value> argv[]) { 267 v8::Local<v8::Value> argv[]) {
255 TRACE_EVENT2("v8", 268 TRACE_EVENT2("v8",
256 "v8.callModuleMethod", 269 "v8.callModuleMethod",
257 "module_name", 270 "module_name",
258 module_name, 271 module_name,
259 "method_name", 272 "method_name",
260 method_name); 273 method_name);
261 274
262 v8::EscapableHandleScope handle_scope(GetIsolate()); 275 v8::EscapableHandleScope handle_scope(GetIsolate());
263 v8::Context::Scope context_scope(context()->v8_context()); 276 v8::Local<v8::Context> v8_context = context()->v8_context();
277 v8::Context::Scope context_scope(v8_context);
278
279 v8::Local<v8::String> v8_module_name;
280 v8::Local<v8::String> v8_method_name;
281 if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name) ||
282 !ToV8String(GetIsolate(), method_name.c_str(), &v8_method_name)) {
283 return handle_scope.Escape(
284 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
not at google - send to devlin 2015/06/16 20:52:24 It actually looks like Handle and Local are the sa
bashi 2015/06/17 01:40:45 Done.
285 }
264 286
265 v8::Local<v8::Value> module; 287 v8::Local<v8::Value> module;
266 { 288 {
267 NativesEnabledScope natives_enabled(this); 289 NativesEnabledScope natives_enabled(this);
268 module = RequireForJsInner( 290 module = RequireForJsInner(v8_module_name);
269 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
270 } 291 }
271 292
272 if (module.IsEmpty() || !module->IsObject()) { 293 if (module.IsEmpty() || !module->IsObject()) {
273 Fatal(context_, 294 Fatal(context_,
274 "Failed to get module " + module_name + " to call " + method_name); 295 "Failed to get module " + module_name + " to call " + method_name);
275 return handle_scope.Escape( 296 return handle_scope.Escape(
276 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate()))); 297 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
277 } 298 }
278 299
279 v8::Local<v8::Value> value = v8::Local<v8::Object>::Cast(module)->Get( 300 v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(module);
280 v8::String::NewFromUtf8(GetIsolate(), method_name.c_str())); 301 v8::Local<v8::Value> value;
281 if (value.IsEmpty() || !value->IsFunction()) { 302 if (!object->Get(v8_context, v8_method_name).ToLocal(&value) ||
303 !value->IsFunction()) {
282 Fatal(context_, module_name + "." + method_name + " is not a function"); 304 Fatal(context_, module_name + "." + method_name + " is not a function");
283 return handle_scope.Escape( 305 return handle_scope.Escape(
284 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate()))); 306 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
285 } 307 }
286 308
287 v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(value); 309 v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(value);
288 v8::Local<v8::Value> result; 310 v8::Local<v8::Value> result;
289 { 311 {
290 v8::TryCatch try_catch; 312 v8::TryCatch try_catch(GetIsolate());
291 try_catch.SetCaptureMessage(true); 313 try_catch.SetCaptureMessage(true);
292 result = context_->CallFunction(func, argc, argv); 314 result = context_->CallFunction(func, argc, argv);
293 if (try_catch.HasCaught()) 315 if (try_catch.HasCaught()) {
294 HandleException(try_catch); 316 HandleException(try_catch);
317 result = v8::Local<v8::Primitive>(v8::Undefined(GetIsolate()));
318 }
295 } 319 }
296 return handle_scope.Escape(result); 320 return handle_scope.Escape(result);
297 } 321 }
298 322
299 void ModuleSystem::RegisterNativeHandler( 323 void ModuleSystem::RegisterNativeHandler(
300 const std::string& name, 324 const std::string& name,
301 scoped_ptr<NativeHandler> native_handler) { 325 scoped_ptr<NativeHandler> native_handler) {
302 ClobberExistingNativeHandler(name); 326 ClobberExistingNativeHandler(name);
303 native_handler_map_[name] = 327 native_handler_map_[name] =
304 linked_ptr<NativeHandler>(native_handler.release()); 328 linked_ptr<NativeHandler>(native_handler.release());
305 } 329 }
306 330
307 void ModuleSystem::OverrideNativeHandlerForTest(const std::string& name) { 331 void ModuleSystem::OverrideNativeHandlerForTest(const std::string& name) {
308 ClobberExistingNativeHandler(name); 332 ClobberExistingNativeHandler(name);
309 overridden_native_handlers_.insert(name); 333 overridden_native_handlers_.insert(name);
310 } 334 }
311 335
312 void ModuleSystem::RunString(const std::string& code, const std::string& name) { 336 void ModuleSystem::RunString(const std::string& code, const std::string& name) {
313 v8::HandleScope handle_scope(GetIsolate()); 337 v8::HandleScope handle_scope(GetIsolate());
314 RunString(v8::String::NewFromUtf8(GetIsolate(), code.c_str()), 338 v8::Local<v8::String> v8_code;
315 v8::String::NewFromUtf8(GetIsolate(), name.c_str())); 339 v8::Local<v8::String> v8_name;
340 if (!ToV8String(GetIsolate(), code.c_str(), &v8_code) ||
341 !ToV8String(GetIsolate(), name.c_str(), &v8_name)) {
342 Warn(GetIsolate(), "Too long code or name.");
343 return;
344 }
345 RunString(v8_code, v8_name);
316 } 346 }
317 347
318 // static 348 // static
319 void ModuleSystem::NativeLazyFieldGetter( 349 void ModuleSystem::NativeLazyFieldGetter(
320 v8::Local<v8::String> property, 350 v8::Local<v8::Name> property,
321 const v8::PropertyCallbackInfo<v8::Value>& info) { 351 const v8::PropertyCallbackInfo<v8::Value>& info) {
322 LazyFieldGetterInner(property, info, &ModuleSystem::RequireNativeFromString); 352 LazyFieldGetterInner(property.As<v8::String>(), info,
353 &ModuleSystem::RequireNativeFromString);
323 } 354 }
324 355
325 // static 356 // static
326 void ModuleSystem::LazyFieldGetter( 357 void ModuleSystem::LazyFieldGetter(
327 v8::Local<v8::String> property, 358 v8::Local<v8::Name> property,
328 const v8::PropertyCallbackInfo<v8::Value>& info) { 359 const v8::PropertyCallbackInfo<v8::Value>& info) {
329 LazyFieldGetterInner(property, info, &ModuleSystem::Require); 360 LazyFieldGetterInner(property.As<v8::String>(), info, &ModuleSystem::Require);
330 } 361 }
331 362
332 // static 363 // static
333 void ModuleSystem::LazyFieldGetterInner( 364 void ModuleSystem::LazyFieldGetterInner(
334 v8::Local<v8::String> property, 365 v8::Local<v8::String> property,
335 const v8::PropertyCallbackInfo<v8::Value>& info, 366 const v8::PropertyCallbackInfo<v8::Value>& info,
336 RequireFunction require_function) { 367 RequireFunction require_function) {
337 CHECK(!info.Data().IsEmpty()); 368 CHECK(!info.Data().IsEmpty());
338 CHECK(info.Data()->IsObject()); 369 CHECK(info.Data()->IsObject());
339 v8::HandleScope handle_scope(info.GetIsolate()); 370 v8::HandleScope handle_scope(info.GetIsolate());
340 v8::Local<v8::Object> parameters = v8::Local<v8::Object>::Cast(info.Data()); 371 v8::Local<v8::Object> parameters = v8::Local<v8::Object>::Cast(info.Data());
341 // This context should be the same as context()->v8_context(). 372 // This context should be the same as context()->v8_context().
342 v8::Local<v8::Context> context = parameters->CreationContext(); 373 v8::Local<v8::Context> context = parameters->CreationContext();
343 v8::Local<v8::Object> global(context->Global()); 374 v8::Local<v8::Object> global(context->Global());
344 v8::Local<v8::Value> module_system_value = global->GetHiddenValue( 375 v8::Local<v8::Value> module_system_value = global->GetHiddenValue(
345 v8::String::NewFromUtf8(info.GetIsolate(), kModuleSystem)); 376 ToV8StringUnsafe(info.GetIsolate(), kModuleSystem));
346 if (module_system_value.IsEmpty() || !module_system_value->IsExternal()) { 377 if (module_system_value.IsEmpty() || !module_system_value->IsExternal()) {
347 // ModuleSystem has been deleted. 378 // ModuleSystem has been deleted.
348 // TODO(kalman): See comment in header file. 379 // TODO(kalman): See comment in header file.
349 Warn(info.GetIsolate(), 380 Warn(info.GetIsolate(),
350 "Module system has been deleted, does extension view exist?"); 381 "Module system has been deleted, does extension view exist?");
351 return; 382 return;
352 } 383 }
353 384
354 ModuleSystem* module_system = static_cast<ModuleSystem*>( 385 ModuleSystem* module_system = static_cast<ModuleSystem*>(
355 v8::Local<v8::External>::Cast(module_system_value)->Value()); 386 v8::Local<v8::External>::Cast(module_system_value)->Value());
356 387
357 std::string name = *v8::String::Utf8Value(parameters->Get( 388 v8::Local<v8::String> v8_k_module_name =
358 v8::String::NewFromUtf8(info.GetIsolate(), kModuleName))); 389 ToV8StringUnsafe(info.GetIsolate(), kModuleName);
390 v8::Local<v8::Value> v8_module_name;
391 if (!parameters->Get(context, v8_k_module_name).ToLocal(&v8_module_name)) {
not at google - send to devlin 2015/06/16 20:52:24 What do you think about adding a "GetProperty" met
bashi 2015/06/17 01:40:45 Done.
392 Warn(info.GetIsolate(), "Cannot find module.");
393 return;
394 }
395 std::string name = *v8::String::Utf8Value(v8_module_name);
359 396
360 // Switch to our v8 context because we need functions created while running 397 // Switch to our v8 context because we need functions created while running
361 // the require()d module to belong to our context, not the current one. 398 // the require()d module to belong to our context, not the current one.
362 v8::Context::Scope context_scope(context); 399 v8::Context::Scope context_scope(context);
363 NativesEnabledScope natives_enabled_scope(module_system); 400 NativesEnabledScope natives_enabled_scope(module_system);
364 401
365 v8::TryCatch try_catch; 402 v8::TryCatch try_catch(info.GetIsolate());
366 v8::Local<v8::Value> module_value = (module_system->*require_function)(name); 403 v8::Local<v8::Value> module_value = (module_system->*require_function)(name);
367 if (try_catch.HasCaught()) { 404 if (try_catch.HasCaught()) {
368 module_system->HandleException(try_catch); 405 module_system->HandleException(try_catch);
369 return; 406 return;
370 } 407 }
371 if (module_value.IsEmpty() || !module_value->IsObject()) { 408 if (module_value.IsEmpty() || !module_value->IsObject()) {
372 // require_function will have already logged this, we don't need to. 409 // require_function will have already logged this, we don't need to.
373 return; 410 return;
374 } 411 }
375 412
376 v8::Local<v8::Object> module = v8::Local<v8::Object>::Cast(module_value); 413 v8::Local<v8::Object> module = v8::Local<v8::Object>::Cast(module_value);
377 v8::Local<v8::String> field = 414 v8::Local<v8::Value> field_value;
378 parameters->Get(v8::String::NewFromUtf8(info.GetIsolate(), kModuleField)) 415 if (!parameters->Get(context,
379 ->ToString(info.GetIsolate()); 416 ToV8StringUnsafe(info.GetIsolate(), kModuleField))
417 .ToLocal(&field_value)) {
418 module_system->HandleException(try_catch);
419 return;
420 }
421 v8::Local<v8::String> field;
422 if (!field_value->ToString(context).ToLocal(&field)) {
423 module_system->HandleException(try_catch);
424 return;
425 }
380 426
381 if (!module->Has(field)) { 427 if (!CheckV8Call(module->Has(context, field))) {
382 std::string field_str = *v8::String::Utf8Value(field); 428 std::string field_str = *v8::String::Utf8Value(field);
383 Fatal(module_system->context_, 429 Fatal(module_system->context_,
384 "Lazy require of " + name + "." + field_str + " did not set the " + 430 "Lazy require of " + name + "." + field_str + " did not set the " +
385 field_str + " field"); 431 field_str + " field");
386 return; 432 return;
387 } 433 }
388 434
389 v8::Local<v8::Value> new_field = module->Get(field); 435 v8::Local<v8::Value> new_field;
390 if (try_catch.HasCaught()) { 436 if (!module->Get(context, field).ToLocal(&new_field)) {
391 module_system->HandleException(try_catch); 437 module_system->HandleException(try_catch);
392 return; 438 return;
393 } 439 }
394 440
395 // Ok for it to be undefined, among other things it's how bindings signify 441 // Ok for it to be undefined, among other things it's how bindings signify
396 // that the extension doesn't have permission to use them. 442 // that the extension doesn't have permission to use them.
397 CHECK(!new_field.IsEmpty()); 443 CHECK(!new_field.IsEmpty());
398 444
399 // Delete the getter and set this field to |new_field| so the same object is 445 // Delete the getter and set this field to |new_field| so the same object is
400 // returned every time a certain API is accessed. 446 // returned every time a certain API is accessed.
401 v8::Local<v8::Value> val = info.This(); 447 v8::Local<v8::Value> val = info.This();
402 if (val->IsObject()) { 448 if (val->IsObject()) {
403 v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(val); 449 v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(val);
404 object->Delete(property); 450 object->Delete(context, property);
405 object->Set(property, new_field); 451 SetProperty(context, object, property, new_field);
406 } else { 452 } else {
407 NOTREACHED(); 453 NOTREACHED();
408 } 454 }
409 info.GetReturnValue().Set(new_field); 455 info.GetReturnValue().Set(new_field);
410 } 456 }
411 457
412 void ModuleSystem::SetLazyField(v8::Local<v8::Object> object, 458 void ModuleSystem::SetLazyField(v8::Local<v8::Object> object,
413 const std::string& field, 459 const std::string& field,
414 const std::string& module_name, 460 const std::string& module_name,
415 const std::string& module_field) { 461 const std::string& module_field) {
416 SetLazyField( 462 SetLazyField(
417 object, field, module_name, module_field, &ModuleSystem::LazyFieldGetter); 463 object, field, module_name, module_field, &ModuleSystem::LazyFieldGetter);
418 } 464 }
419 465
420 void ModuleSystem::SetLazyField(v8::Local<v8::Object> object, 466 void ModuleSystem::SetLazyField(v8::Local<v8::Object> object,
421 const std::string& field, 467 const std::string& field,
422 const std::string& module_name, 468 const std::string& module_name,
423 const std::string& module_field, 469 const std::string& module_field,
424 v8::AccessorGetterCallback getter) { 470 v8::AccessorNameGetterCallback getter) {
471 CHECK(field.size() < v8::String::kMaxLength);
472 CHECK(module_name.size() < v8::String::kMaxLength);
473 CHECK(module_field.size() < v8::String::kMaxLength);
425 v8::HandleScope handle_scope(GetIsolate()); 474 v8::HandleScope handle_scope(GetIsolate());
426 v8::Local<v8::Object> parameters = v8::Object::New(GetIsolate()); 475 v8::Local<v8::Object> parameters = v8::Object::New(GetIsolate());
427 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleName), 476 v8::Local<v8::Context> context = context_->v8_context();
428 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str())); 477 SetProperty(context, parameters, ToV8StringUnsafe(GetIsolate(), kModuleName),
429 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleField), 478 ToV8StringUnsafe(GetIsolate(), module_name.c_str()));
430 v8::String::NewFromUtf8(GetIsolate(), module_field.c_str())); 479 SetProperty(context, parameters, ToV8StringUnsafe(GetIsolate(), kModuleField),
431 object->SetAccessor(v8::String::NewFromUtf8(GetIsolate(), field.c_str()), 480 ToV8StringUnsafe(GetIsolate(), module_field.c_str()));
432 getter, 481 auto maybe = object->SetAccessor(
433 NULL, 482 context, ToV8StringUnsafe(GetIsolate(), field.c_str()), getter, NULL,
434 parameters); 483 parameters);
484 CHECK(CheckV8Call(maybe));
435 } 485 }
436 486
437 void ModuleSystem::SetNativeLazyField(v8::Local<v8::Object> object, 487 void ModuleSystem::SetNativeLazyField(v8::Local<v8::Object> object,
438 const std::string& field, 488 const std::string& field,
439 const std::string& module_name, 489 const std::string& module_name,
440 const std::string& module_field) { 490 const std::string& module_field) {
441 SetLazyField(object, 491 SetLazyField(object,
442 field, 492 field,
443 module_name, 493 module_name,
444 module_field, 494 module_field,
445 &ModuleSystem::NativeLazyFieldGetter); 495 &ModuleSystem::NativeLazyFieldGetter);
446 } 496 }
447 497
448 v8::Local<v8::Value> ModuleSystem::RunString(v8::Local<v8::String> code, 498 v8::Local<v8::Value> ModuleSystem::RunString(v8::Local<v8::String> code,
449 v8::Local<v8::String> name) { 499 v8::Local<v8::String> name) {
450 v8::EscapableHandleScope handle_scope(GetIsolate()); 500 v8::EscapableHandleScope handle_scope(GetIsolate());
451 v8::Context::Scope context_scope(context()->v8_context()); 501 v8::Local<v8::Context> v8_context = context()->v8_context();
502 v8::Context::Scope context_scope(v8_context);
452 503
453 // Prepend extensions:: to |name| so that internal code can be differentiated 504 // Prepend extensions:: to |name| so that internal code can be differentiated
454 // from external code in stack traces. This has no effect on behaviour. 505 // from external code in stack traces. This has no effect on behaviour.
455 std::string internal_name = 506 std::string internal_name =
456 base::StringPrintf("extensions::%s", *v8::String::Utf8Value(name)); 507 base::StringPrintf("extensions::%s", *v8::String::Utf8Value(name));
457 508
509 if (internal_name.size() >= v8::String::kMaxLength) {
510 NOTREACHED() << "internal_name is too long.";
511 return v8::Undefined(GetIsolate());
512 }
513
458 blink::WebScopedMicrotaskSuppression suppression; 514 blink::WebScopedMicrotaskSuppression suppression;
459 v8::TryCatch try_catch; 515 v8::TryCatch try_catch(GetIsolate());
460 try_catch.SetCaptureMessage(true); 516 try_catch.SetCaptureMessage(true);
461 v8::Local<v8::Script> script(v8::Script::Compile( 517 v8::ScriptOrigin origin(
462 code, v8::String::NewFromUtf8(GetIsolate(), internal_name.c_str(), 518 ToV8StringUnsafe(GetIsolate(), internal_name.c_str()));
463 v8::String::kNormalString, 519 v8::Local<v8::Script> script;
464 internal_name.size()))); 520 if (!v8::Script::Compile(v8_context, code, &origin).ToLocal(&script)) {
465 if (try_catch.HasCaught()) {
466 HandleException(try_catch); 521 HandleException(try_catch);
467 return v8::Undefined(GetIsolate()); 522 return v8::Undefined(GetIsolate());
468 } 523 }
469 524
470 v8::Local<v8::Value> result = script->Run(); 525 v8::Local<v8::Value> result;
471 if (try_catch.HasCaught()) { 526 if (!script->Run(v8_context).ToLocal(&result)) {
472 HandleException(try_catch); 527 HandleException(try_catch);
473 return v8::Undefined(GetIsolate()); 528 return v8::Undefined(GetIsolate());
474 } 529 }
475 530
476 return handle_scope.Escape(result); 531 return handle_scope.Escape(result);
477 } 532 }
478 533
479 v8::Local<v8::Value> ModuleSystem::GetSource(const std::string& module_name) { 534 v8::Local<v8::Value> ModuleSystem::GetSource(const std::string& module_name) {
480 v8::EscapableHandleScope handle_scope(GetIsolate()); 535 v8::EscapableHandleScope handle_scope(GetIsolate());
481 if (!source_map_->Contains(module_name)) 536 if (!source_map_->Contains(module_name))
(...skipping 10 matching lines...) Expand all
492 } 547 }
493 548
494 v8::Local<v8::Value> ModuleSystem::RequireNativeFromString( 549 v8::Local<v8::Value> ModuleSystem::RequireNativeFromString(
495 const std::string& native_name) { 550 const std::string& native_name) {
496 if (natives_enabled_ == 0) { 551 if (natives_enabled_ == 0) {
497 // HACK: if in test throw exception so that we can test the natives-disabled 552 // HACK: if in test throw exception so that we can test the natives-disabled
498 // logic; however, under normal circumstances, this is programmer error so 553 // logic; however, under normal circumstances, this is programmer error so
499 // we could crash. 554 // we could crash.
500 if (exception_handler_) { 555 if (exception_handler_) {
501 return GetIsolate()->ThrowException( 556 return GetIsolate()->ThrowException(
502 v8::String::NewFromUtf8(GetIsolate(), "Natives disabled")); 557 ToV8StringUnsafe(GetIsolate(), "Natives disabled"));
503 } 558 }
504 Fatal(context_, "Natives disabled for requireNative(" + native_name + ")"); 559 Fatal(context_, "Natives disabled for requireNative(" + native_name + ")");
505 return v8::Undefined(GetIsolate()); 560 return v8::Undefined(GetIsolate());
506 } 561 }
507 562
508 if (overridden_native_handlers_.count(native_name) > 0u) { 563 if (overridden_native_handlers_.count(native_name) > 0u) {
509 return RequireForJsInner( 564 return RequireForJsInner(
510 v8::String::NewFromUtf8(GetIsolate(), native_name.c_str())); 565 ToV8StringUnsafe(GetIsolate(), native_name.c_str()));
511 } 566 }
512 567
513 NativeHandlerMap::iterator i = native_handler_map_.find(native_name); 568 NativeHandlerMap::iterator i = native_handler_map_.find(native_name);
514 if (i == native_handler_map_.end()) { 569 if (i == native_handler_map_.end()) {
515 Fatal(context_, 570 Fatal(context_,
516 "Couldn't find native for requireNative(" + native_name + ")"); 571 "Couldn't find native for requireNative(" + native_name + ")");
517 return v8::Undefined(GetIsolate()); 572 return v8::Undefined(GetIsolate());
518 } 573 }
519 return i->second->NewInstance(); 574 return i->second->NewInstance();
520 } 575 }
521 576
522 void ModuleSystem::RequireAsync( 577 void ModuleSystem::RequireAsync(
523 const v8::FunctionCallbackInfo<v8::Value>& args) { 578 const v8::FunctionCallbackInfo<v8::Value>& args) {
524 CHECK_EQ(1, args.Length()); 579 CHECK_EQ(1, args.Length());
525 std::string module_name = *v8::String::Utf8Value(args[0]); 580 std::string module_name = *v8::String::Utf8Value(args[0]);
581 v8::Local<v8::Context> v8_context = context_->v8_context();
526 v8::Local<v8::Promise::Resolver> resolver( 582 v8::Local<v8::Promise::Resolver> resolver(
527 v8::Promise::Resolver::New(GetIsolate())); 583 v8::Promise::Resolver::New(v8_context).ToLocalChecked());
528 args.GetReturnValue().Set(resolver->GetPromise()); 584 args.GetReturnValue().Set(resolver->GetPromise());
529 scoped_ptr<v8::Global<v8::Promise::Resolver>> global_resolver( 585 scoped_ptr<v8::Global<v8::Promise::Resolver>> global_resolver(
530 new v8::Global<v8::Promise::Resolver>(GetIsolate(), resolver)); 586 new v8::Global<v8::Promise::Resolver>(GetIsolate(), resolver));
531 gin::ModuleRegistry* module_registry = 587 gin::ModuleRegistry* module_registry =
532 gin::ModuleRegistry::From(context_->v8_context()); 588 gin::ModuleRegistry::From(v8_context);
533 if (!module_registry) { 589 if (!module_registry) {
534 Warn(GetIsolate(), "Extension view no longer exists"); 590 Warn(GetIsolate(), "Extension view no longer exists");
535 resolver->Reject(v8::Exception::Error(v8::String::NewFromUtf8( 591 resolver->Reject(v8_context, v8::Exception::Error(ToV8StringUnsafe(
536 GetIsolate(), "Extension view no longer exists"))); 592 GetIsolate(), "Extension view no longer exists")));
537 return; 593 return;
538 } 594 }
539 module_registry->LoadModule( 595 module_registry->LoadModule(
540 GetIsolate(), module_name, 596 GetIsolate(), module_name,
541 base::Bind(&ModuleSystem::OnModuleLoaded, weak_factory_.GetWeakPtr(), 597 base::Bind(&ModuleSystem::OnModuleLoaded, weak_factory_.GetWeakPtr(),
542 base::Passed(&global_resolver))); 598 base::Passed(&global_resolver)));
543 if (module_registry->available_modules().count(module_name) == 0) 599 if (module_registry->available_modules().count(module_name) == 0)
544 LoadModule(module_name); 600 LoadModule(module_name);
545 } 601 }
546 602
547 v8::Local<v8::String> ModuleSystem::WrapSource(v8::Local<v8::String> source) { 603 v8::Local<v8::String> ModuleSystem::WrapSource(v8::Local<v8::String> source) {
548 v8::EscapableHandleScope handle_scope(GetIsolate()); 604 v8::EscapableHandleScope handle_scope(GetIsolate());
549 // Keep in order with the arguments in RequireForJsInner. 605 // Keep in order with the arguments in RequireForJsInner.
550 v8::Local<v8::String> left = v8::String::NewFromUtf8( 606 v8::Local<v8::String> left = ToV8StringUnsafe(
551 GetIsolate(), 607 GetIsolate(),
552 "(function(define, require, requireNative, requireAsync, exports, " 608 "(function(define, require, requireNative, requireAsync, exports, "
553 "console, privates," 609 "console, privates,"
554 "$Array, $Function, $JSON, $Object, $RegExp, $String, $Error) {" 610 "$Array, $Function, $JSON, $Object, $RegExp, $String, $Error) {"
555 "'use strict';"); 611 "'use strict';");
556 v8::Local<v8::String> right = v8::String::NewFromUtf8(GetIsolate(), "\n})"); 612 v8::Local<v8::String> right = ToV8StringUnsafe(GetIsolate(), "\n})");
557 return handle_scope.Escape(v8::Local<v8::String>( 613 return handle_scope.Escape(v8::Local<v8::String>(
558 v8::String::Concat(left, v8::String::Concat(source, right)))); 614 v8::String::Concat(left, v8::String::Concat(source, right))));
559 } 615 }
560 616
561 void ModuleSystem::Private(const v8::FunctionCallbackInfo<v8::Value>& args) { 617 void ModuleSystem::Private(const v8::FunctionCallbackInfo<v8::Value>& args) {
562 CHECK_EQ(1, args.Length()); 618 CHECK_EQ(1, args.Length());
563 if (!args[0]->IsObject() || args[0]->IsNull()) { 619 if (!args[0]->IsObject() || args[0]->IsNull()) {
564 GetIsolate()->ThrowException( 620 GetIsolate()->ThrowException(
565 v8::Exception::TypeError(v8::String::NewFromUtf8(GetIsolate(), 621 v8::Exception::TypeError(ToV8StringUnsafe(GetIsolate(),
566 args[0]->IsUndefined() 622 args[0]->IsUndefined()
567 ? "Method called without a valid receiver (this). " 623 ? "Method called without a valid receiver (this). "
568 "Did you forget to call .bind()?" 624 "Did you forget to call .bind()?"
569 : "Invalid invocation: receiver is not an object!"))); 625 : "Invalid invocation: receiver is not an object!")));
570 return; 626 return;
571 } 627 }
572 v8::Local<v8::Object> obj = args[0].As<v8::Object>(); 628 v8::Local<v8::Object> obj = args[0].As<v8::Object>();
573 v8::Local<v8::String> privates_key = 629 v8::Local<v8::String> privates_key =
574 v8::String::NewFromUtf8(GetIsolate(), "privates"); 630 ToV8StringUnsafe(GetIsolate(), "privates");
575 v8::Local<v8::Value> privates = obj->GetHiddenValue(privates_key); 631 v8::Local<v8::Value> privates = obj->GetHiddenValue(privates_key);
576 if (privates.IsEmpty()) { 632 if (privates.IsEmpty()) {
577 privates = v8::Object::New(args.GetIsolate()); 633 privates = v8::Object::New(args.GetIsolate());
578 if (privates.IsEmpty()) { 634 if (privates.IsEmpty()) {
579 GetIsolate()->ThrowException( 635 GetIsolate()->ThrowException(
580 v8::String::NewFromUtf8(GetIsolate(), "Failed to create privates")); 636 ToV8StringUnsafe(GetIsolate(), "Failed to create privates"));
581 return; 637 return;
582 } 638 }
583 obj->SetHiddenValue(privates_key, privates); 639 obj->SetHiddenValue(privates_key, privates);
584 } 640 }
585 args.GetReturnValue().Set(privates); 641 args.GetReturnValue().Set(privates);
586 } 642 }
587 643
588 v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) { 644 v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
589 v8::EscapableHandleScope handle_scope(GetIsolate()); 645 v8::EscapableHandleScope handle_scope(GetIsolate());
590 v8::Context::Scope context_scope(context()->v8_context()); 646 v8::Local<v8::Context> v8_context = context()->v8_context();
647 v8::Context::Scope context_scope(v8_context);
591 648
592 v8::Local<v8::Value> source(GetSource(module_name)); 649 v8::Local<v8::Value> source(GetSource(module_name));
593 if (source.IsEmpty() || source->IsUndefined()) { 650 if (source.IsEmpty() || source->IsUndefined()) {
594 Fatal(context_, "No source for require(" + module_name + ")"); 651 Fatal(context_, "No source for require(" + module_name + ")");
595 return v8::Undefined(GetIsolate()); 652 return v8::Undefined(GetIsolate());
596 } 653 }
597 v8::Local<v8::String> wrapped_source( 654 v8::Local<v8::String> wrapped_source(
598 WrapSource(v8::Local<v8::String>::Cast(source))); 655 WrapSource(v8::Local<v8::String>::Cast(source)));
656 v8::Local<v8::String> v8_module_name;
657 if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
658 NOTREACHED() << "module_name is too long";
659 return v8::Undefined(GetIsolate());
660 }
599 // Modules are wrapped in (function(){...}) so they always return functions. 661 // Modules are wrapped in (function(){...}) so they always return functions.
600 v8::Local<v8::Value> func_as_value = 662 v8::Local<v8::Value> func_as_value =
601 RunString(wrapped_source, 663 RunString(wrapped_source, v8_module_name);
602 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
603 if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) { 664 if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
604 Fatal(context_, "Bad source for require(" + module_name + ")"); 665 Fatal(context_, "Bad source for require(" + module_name + ")");
605 return v8::Undefined(GetIsolate()); 666 return v8::Undefined(GetIsolate());
606 } 667 }
607 668
608 v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value); 669 v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
609 670
610 v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate()); 671 v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
611 gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object); 672 gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
612 673
613 v8::Local<v8::Value> exports = v8::Object::New(GetIsolate()); 674 v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
614 v8::Local<v8::Object> natives(NewInstance()); 675 v8::Local<v8::Object> natives(NewInstance());
615 CHECK(!natives.IsEmpty()); // this can happen if v8 has issues 676 CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
616 677
617 // These must match the argument order in WrapSource. 678 // These must match the argument order in WrapSource.
618 v8::Local<v8::Value> args[] = { 679 v8::Local<v8::Value> args[] = {
619 // AMD. 680 // AMD.
620 define_object->Get(v8::String::NewFromUtf8(GetIsolate(), "define")), 681 UnsafeGet(v8_context, define_object,
682 ToV8StringUnsafe(GetIsolate(), "define")),
621 // CommonJS. 683 // CommonJS.
622 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "require", 684 UnsafeGet(v8_context, natives,
623 v8::String::kInternalizedString)), 685 ToV8StringUnsafe(GetIsolate(), "require",
624 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "requireNative", 686 v8::NewStringType::kInternalized)),
625 v8::String::kInternalizedString)), 687 UnsafeGet(v8_context, natives,
626 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "requireAsync", 688 ToV8StringUnsafe(GetIsolate(), "requireNative",
627 v8::String::kInternalizedString)), 689 v8::NewStringType::kInternalized)),
690 UnsafeGet(v8_context, natives,
691 ToV8StringUnsafe(GetIsolate(), "requireAsync",
692 v8::NewStringType::kInternalized)),
628 exports, 693 exports,
629 // Libraries that we magically expose to every module. 694 // Libraries that we magically expose to every module.
630 console::AsV8Object(GetIsolate()), 695 console::AsV8Object(GetIsolate()),
631 natives->Get(v8::String::NewFromUtf8(GetIsolate(), "privates", 696 UnsafeGet(v8_context, natives,
632 v8::String::kInternalizedString)), 697 ToV8StringUnsafe(GetIsolate(), "privates",
698 v8::NewStringType::kInternalized)),
633 // Each safe builtin. Keep in order with the arguments in WrapSource. 699 // Each safe builtin. Keep in order with the arguments in WrapSource.
634 context_->safe_builtins()->GetArray(), 700 context_->safe_builtins()->GetArray(),
635 context_->safe_builtins()->GetFunction(), 701 context_->safe_builtins()->GetFunction(),
636 context_->safe_builtins()->GetJSON(), 702 context_->safe_builtins()->GetJSON(),
637 context_->safe_builtins()->GetObjekt(), 703 context_->safe_builtins()->GetObjekt(),
638 context_->safe_builtins()->GetRegExp(), 704 context_->safe_builtins()->GetRegExp(),
639 context_->safe_builtins()->GetString(), 705 context_->safe_builtins()->GetString(),
640 context_->safe_builtins()->GetError(), 706 context_->safe_builtins()->GetError(),
641 }; 707 };
642 { 708 {
643 v8::TryCatch try_catch; 709 v8::TryCatch try_catch(GetIsolate());
644 try_catch.SetCaptureMessage(true); 710 try_catch.SetCaptureMessage(true);
645 context_->CallFunction(func, arraysize(args), args); 711 context_->CallFunction(func, arraysize(args), args);
646 if (try_catch.HasCaught()) { 712 if (try_catch.HasCaught()) {
647 HandleException(try_catch); 713 HandleException(try_catch);
648 return v8::Undefined(GetIsolate()); 714 return v8::Undefined(GetIsolate());
649 } 715 }
650 } 716 }
651 return handle_scope.Escape(exports); 717 return handle_scope.Escape(exports);
652 } 718 }
653 719
(...skipping 19 matching lines...) Expand all
673 } 739 }
674 740
675 void ModuleSystem::OnModuleLoaded( 741 void ModuleSystem::OnModuleLoaded(
676 scoped_ptr<v8::Global<v8::Promise::Resolver>> resolver, 742 scoped_ptr<v8::Global<v8::Promise::Resolver>> resolver,
677 v8::Local<v8::Value> value) { 743 v8::Local<v8::Value> value) {
678 if (!is_valid()) 744 if (!is_valid())
679 return; 745 return;
680 v8::HandleScope handle_scope(GetIsolate()); 746 v8::HandleScope handle_scope(GetIsolate());
681 v8::Local<v8::Promise::Resolver> resolver_local( 747 v8::Local<v8::Promise::Resolver> resolver_local(
682 v8::Local<v8::Promise::Resolver>::New(GetIsolate(), *resolver)); 748 v8::Local<v8::Promise::Resolver>::New(GetIsolate(), *resolver));
683 resolver_local->Resolve(value); 749 resolver_local->Resolve(context()->v8_context(), value);
684 } 750 }
685 751
686 void ModuleSystem::ClobberExistingNativeHandler(const std::string& name) { 752 void ModuleSystem::ClobberExistingNativeHandler(const std::string& name) {
687 NativeHandlerMap::iterator existing_handler = native_handler_map_.find(name); 753 NativeHandlerMap::iterator existing_handler = native_handler_map_.find(name);
688 if (existing_handler != native_handler_map_.end()) { 754 if (existing_handler != native_handler_map_.end()) {
689 clobbered_native_handlers_.push_back(existing_handler->second); 755 clobbered_native_handlers_.push_back(existing_handler->second);
690 native_handler_map_.erase(existing_handler); 756 native_handler_map_.erase(existing_handler);
691 } 757 }
692 } 758 }
693 759
694 } // namespace extensions 760 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698