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
3 // found in the LICENSE file.
5 #ifndef EXTENSIONS_RENDERER_MODULE_SYSTEM_H_
6 #define EXTENSIONS_RENDERER_MODULE_SYSTEM_H_
13 #include "base/compiler_specific.h"
14 #include "base/memory/linked_ptr.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "extensions/renderer/native_handler.h"
17 #include "extensions/renderer/object_backed_native_handler.h"
18 #include "gin/modules/module_registry_observer.h"
19 #include "v8/include/v8.h"
21 namespace extensions
{
25 // A module system for JS similar to node.js' require() function.
26 // Each module has three variables in the global scope:
27 // - exports, an object returned to dependencies who require() this
29 // - require, a function that takes a module name as an argument and returns
30 // that module's exports object.
31 // - requireNative, a function that takes the name of a registered
32 // NativeHandler and returns an object that contains the functions the
33 // NativeHandler defines.
35 // Each module in a ModuleSystem is executed at most once and its exports
38 // Note that a ModuleSystem must be used only in conjunction with a single
40 // TODO(koz): Rename this to JavaScriptModuleSystem.
41 class ModuleSystem
: public ObjectBackedNativeHandler
,
42 public gin::ModuleRegistryObserver
{
46 virtual ~SourceMap() {}
47 virtual v8::Local
<v8::Value
> GetSource(v8::Isolate
* isolate
,
48 const std::string
& name
) = 0;
49 virtual bool Contains(const std::string
& name
) = 0;
52 class ExceptionHandler
{
54 explicit ExceptionHandler(ScriptContext
* context
) : context_(context
) {}
55 virtual ~ExceptionHandler() {}
56 virtual void HandleUncaughtException(const v8::TryCatch
& try_catch
) = 0;
59 // Formats |try_catch| as a nice string.
60 std::string
CreateExceptionString(const v8::TryCatch
& try_catch
);
61 // A script context associated with this handler. Owned by the module
63 ScriptContext
* context_
;
66 // Enables native bindings for the duration of its lifetime.
67 class NativesEnabledScope
{
69 explicit NativesEnabledScope(ModuleSystem
* module_system
);
70 ~NativesEnabledScope();
73 ModuleSystem
* module_system_
;
74 DISALLOW_COPY_AND_ASSIGN(NativesEnabledScope
);
77 // |source_map| is a weak pointer.
78 ModuleSystem(ScriptContext
* context
, SourceMap
* source_map
);
79 ~ModuleSystem() override
;
81 // Require the specified module. This is the equivalent of calling
82 // require('module_name') from the loaded JS files.
83 v8::MaybeLocal
<v8::Object
> Require(const std::string
& module_name
);
84 void Require(const v8::FunctionCallbackInfo
<v8::Value
>& args
);
86 // Run |code| in the current context with the name |name| used for stack
88 v8::Local
<v8::Value
> RunString(v8::Local
<v8::String
> code
,
89 v8::Local
<v8::String
> name
);
91 // Calls the specified method exported by the specified module. This is
92 // equivalent to calling require('module_name').method_name() from JS.
93 v8::Local
<v8::Value
> CallModuleMethod(const std::string
& module_name
,
94 const std::string
& method_name
);
95 v8::Local
<v8::Value
> CallModuleMethod(
96 const std::string
& module_name
,
97 const std::string
& method_name
,
98 std::vector
<v8::Local
<v8::Value
>>* args
);
99 v8::Local
<v8::Value
> CallModuleMethod(const std::string
& module_name
,
100 const std::string
& method_name
,
102 v8::Local
<v8::Value
> argv
[]);
104 // Register |native_handler| as a potential target for requireNative(), so
105 // calls to requireNative(|name|) from JS will return a new object created by
107 void RegisterNativeHandler(const std::string
& name
,
108 scoped_ptr
<NativeHandler
> native_handler
);
110 // Causes requireNative(|name|) to look for its module in |source_map_|
111 // instead of using a registered native handler. This can be used in unit
112 // tests to mock out native modules.
113 void OverrideNativeHandlerForTest(const std::string
& name
);
115 // Executes |code| in the current context with |name| as the filename.
116 void RunString(const std::string
& code
, const std::string
& name
);
118 // Make |object|.|field| lazily evaluate to the result of
119 // require(|module_name|)[|module_field|].
121 // TODO(kalman): All targets for this method are ObjectBackedNativeHandlers,
122 // move this logic into those classes (in fact, the chrome
123 // object is the only client, only that needs to implement it).
124 void SetLazyField(v8::Local
<v8::Object
> object
,
125 const std::string
& field
,
126 const std::string
& module_name
,
127 const std::string
& module_field
);
129 void SetLazyField(v8::Local
<v8::Object
> object
,
130 const std::string
& field
,
131 const std::string
& module_name
,
132 const std::string
& module_field
,
133 v8::AccessorNameGetterCallback getter
);
135 // Make |object|.|field| lazily evaluate to the result of
136 // requireNative(|module_name|)[|module_field|].
137 // TODO(kalman): Same as above.
138 void SetNativeLazyField(v8::Local
<v8::Object
> object
,
139 const std::string
& field
,
140 const std::string
& module_name
,
141 const std::string
& module_field
);
143 // Passes exceptions to |handler| rather than console::Fatal.
144 void SetExceptionHandlerForTest(scoped_ptr
<ExceptionHandler
> handler
) {
145 exception_handler_
= handler
.Pass();
149 friend class ModuleSystemTestEnvironment
;
150 friend class ScriptContext
;
151 void Invalidate() override
;
154 typedef std::map
<std::string
, linked_ptr
<NativeHandler
> > NativeHandlerMap
;
156 // Retrieves the lazily defined field specified by |property|.
157 static void LazyFieldGetter(v8::Local
<v8::Name
> property
,
158 const v8::PropertyCallbackInfo
<v8::Value
>& info
);
159 // Retrieves the lazily defined field specified by |property| on a native
161 static void NativeLazyFieldGetter(
162 v8::Local
<v8::Name
> property
,
163 const v8::PropertyCallbackInfo
<v8::Value
>& info
);
165 // Called when an exception is thrown but not caught.
166 void HandleException(const v8::TryCatch
& try_catch
);
168 void RequireForJs(const v8::FunctionCallbackInfo
<v8::Value
>& args
);
169 v8::Local
<v8::Value
> RequireForJsInner(v8::Local
<v8::String
> module_name
);
171 typedef v8::MaybeLocal
<v8::Object
>(ModuleSystem::*RequireFunction
)(
173 // Base implementation of a LazyFieldGetter which uses |require_fn| to require
175 static void LazyFieldGetterInner(
176 v8::Local
<v8::String
> property
,
177 const v8::PropertyCallbackInfo
<v8::Value
>& info
,
178 RequireFunction require_function
);
180 // Return the named source file stored in the source map.
181 // |args[0]| - the name of a source file in source_map_.
182 v8::Local
<v8::Value
> GetSource(const std::string
& module_name
);
184 // Return an object that contains the native methods defined by the named
186 // |args[0]| - the name of a native handler object.
187 v8::MaybeLocal
<v8::Object
> RequireNativeFromString(
188 const std::string
& native_name
);
189 void RequireNative(const v8::FunctionCallbackInfo
<v8::Value
>& args
);
191 // Return a promise for a requested module.
192 // |args[0]| - the name of a module.
193 void RequireAsync(const v8::FunctionCallbackInfo
<v8::Value
>& args
);
195 // Wraps |source| in a (function(define, require, requireNative, ...) {...}).
196 v8::Local
<v8::String
> WrapSource(v8::Local
<v8::String
> source
);
198 // NativeHandler implementation which returns the private area of an Object.
199 void Private(const v8::FunctionCallbackInfo
<v8::Value
>& args
);
201 // Loads and runs a Javascript module.
202 v8::Local
<v8::Value
> LoadModule(const std::string
& module_name
);
204 // Invoked when a module is loaded in response to a requireAsync call.
205 // Resolves |resolver| with |value|.
206 void OnModuleLoaded(scoped_ptr
<v8::Global
<v8::Promise::Resolver
>> resolver
,
207 v8::Local
<v8::Value
> value
);
209 // gin::ModuleRegistryObserver overrides.
210 void OnDidAddPendingModule(
211 const std::string
& id
,
212 const std::vector
<std::string
>& dependencies
) override
;
214 // Marks any existing NativeHandler named |name| as clobbered.
215 // See |clobbered_native_handlers_|.
216 void ClobberExistingNativeHandler(const std::string
& name
);
218 ScriptContext
* context_
;
220 // A map from module names to the JS source for that module. GetSource()
221 // performs a lookup on this map.
222 SourceMap
* source_map_
;
224 // A map from native handler names to native handlers.
225 NativeHandlerMap native_handler_map_
;
227 // When 0, natives are disabled, otherwise indicates how many callers have
228 // pinned natives as enabled.
229 int natives_enabled_
;
231 // Called when an exception is thrown but not caught in JS. Overridable by
233 scoped_ptr
<ExceptionHandler
> exception_handler_
;
235 // A set of native handlers that should actually be require()d as non-native
236 // handlers. This is used for tests to mock out native handlers in JS.
237 std::set
<std::string
> overridden_native_handlers_
;
239 // A list of NativeHandlers that have been clobbered, either due to
240 // registering a NativeHandler when one was already registered with the same
241 // name, or due to OverrideNativeHandlerForTest. This is needed so that they
242 // can be later Invalidated. It should only happen in tests.
243 std::vector
<linked_ptr
<NativeHandler
>> clobbered_native_handlers_
;
245 base::WeakPtrFactory
<ModuleSystem
> weak_factory_
;
247 DISALLOW_COPY_AND_ASSIGN(ModuleSystem
);
250 } // namespace extensions
252 #endif // EXTENSIONS_RENDERER_MODULE_SYSTEM_H_