• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "node_wasm_web_api.h"
2 
3 #include "memory_tracker-inl.h"
4 #include "node_errors.h"
5 #include "node_external_reference.h"
6 
7 namespace node {
8 namespace wasm_web_api {
9 
10 using v8::ArrayBuffer;
11 using v8::ArrayBufferView;
12 using v8::Context;
13 using v8::Function;
14 using v8::FunctionCallbackInfo;
15 using v8::FunctionTemplate;
16 using v8::Isolate;
17 using v8::Local;
18 using v8::MaybeLocal;
19 using v8::Object;
20 using v8::Value;
21 using v8::WasmStreaming;
22 
Initialize(Environment * env)23 Local<Function> WasmStreamingObject::Initialize(Environment* env) {
24   Local<Function> templ = env->wasm_streaming_object_constructor();
25   if (!templ.IsEmpty()) {
26     return templ;
27   }
28 
29   Isolate* isolate = env->isolate();
30   Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New);
31   t->Inherit(BaseObject::GetConstructorTemplate(env));
32   t->InstanceTemplate()->SetInternalFieldCount(
33       WasmStreamingObject::kInternalFieldCount);
34 
35   SetProtoMethod(isolate, t, "setURL", SetURL);
36   SetProtoMethod(isolate, t, "push", Push);
37   SetProtoMethod(isolate, t, "finish", Finish);
38   SetProtoMethod(isolate, t, "abort", Abort);
39 
40   auto function = t->GetFunction(env->context()).ToLocalChecked();
41   env->set_wasm_streaming_object_constructor(function);
42   return function;
43 }
44 
RegisterExternalReferences(ExternalReferenceRegistry * registry)45 void WasmStreamingObject::RegisterExternalReferences(
46     ExternalReferenceRegistry* registry) {
47   registry->Register(New);
48   registry->Register(Push);
49   registry->Register(Finish);
50   registry->Register(Abort);
51 }
52 
MemoryInfo(MemoryTracker * tracker) const53 void WasmStreamingObject::MemoryInfo(MemoryTracker* tracker) const {
54   // v8::WasmStreaming is opaque. We assume that the size of the WebAssembly
55   // module that is being compiled is roughly what V8 allocates (as in, off by
56   // only a small factor).
57   tracker->TrackFieldWithSize("streaming", wasm_size_);
58 }
59 
Create(Environment * env,std::shared_ptr<WasmStreaming> streaming)60 MaybeLocal<Object> WasmStreamingObject::Create(
61     Environment* env, std::shared_ptr<WasmStreaming> streaming) {
62   Local<Function> ctor = Initialize(env);
63   Local<Object> obj;
64   if (!ctor->NewInstance(env->context(), 0, nullptr).ToLocal(&obj)) {
65     return MaybeLocal<Object>();
66   }
67 
68   CHECK(streaming);
69 
70   WasmStreamingObject* ptr = Unwrap<WasmStreamingObject>(obj);
71   CHECK_NOT_NULL(ptr);
72   ptr->streaming_ = streaming;
73   ptr->wasm_size_ = 0;
74   return obj;
75 }
76 
New(const FunctionCallbackInfo<Value> & args)77 void WasmStreamingObject::New(const FunctionCallbackInfo<Value>& args) {
78   CHECK(args.IsConstructCall());
79   Environment* env = Environment::GetCurrent(args);
80   new WasmStreamingObject(env, args.This());
81 }
82 
SetURL(const FunctionCallbackInfo<Value> & args)83 void WasmStreamingObject::SetURL(const FunctionCallbackInfo<Value>& args) {
84   WasmStreamingObject* obj;
85   ASSIGN_OR_RETURN_UNWRAP(&obj, args.Holder());
86   CHECK(obj->streaming_);
87 
88   CHECK_EQ(args.Length(), 1);
89   CHECK(args[0]->IsString());
90   Utf8Value url(Environment::GetCurrent(args)->isolate(), args[0]);
91   obj->streaming_->SetUrl(url.out(), url.length());
92 }
93 
Push(const FunctionCallbackInfo<Value> & args)94 void WasmStreamingObject::Push(const FunctionCallbackInfo<Value>& args) {
95   WasmStreamingObject* obj;
96   ASSIGN_OR_RETURN_UNWRAP(&obj, args.Holder());
97   CHECK(obj->streaming_);
98 
99   CHECK_EQ(args.Length(), 1);
100   Local<Value> chunk = args[0];
101 
102   // The start of the memory section backing the ArrayBuffer(View), the offset
103   // of the ArrayBuffer(View) within the memory section, and its size in bytes.
104   const void* bytes;
105   size_t offset;
106   size_t size;
107 
108   if (LIKELY(chunk->IsArrayBufferView())) {
109     Local<ArrayBufferView> view = chunk.As<ArrayBufferView>();
110     bytes = view->Buffer()->Data();
111     offset = view->ByteOffset();
112     size = view->ByteLength();
113   } else if (LIKELY(chunk->IsArrayBuffer())) {
114     Local<ArrayBuffer> buffer = chunk.As<ArrayBuffer>();
115     bytes = buffer->Data();
116     offset = 0;
117     size = buffer->ByteLength();
118   } else {
119     return node::THROW_ERR_INVALID_ARG_TYPE(
120         Environment::GetCurrent(args),
121         "chunk must be an ArrayBufferView or an ArrayBuffer");
122   }
123 
124   // Forward the data to V8. Internally, V8 will make a copy.
125   obj->streaming_->OnBytesReceived(static_cast<const uint8_t*>(bytes) + offset,
126                                    size);
127   obj->wasm_size_ += size;
128 }
129 
Finish(const FunctionCallbackInfo<Value> & args)130 void WasmStreamingObject::Finish(const FunctionCallbackInfo<Value>& args) {
131   WasmStreamingObject* obj;
132   ASSIGN_OR_RETURN_UNWRAP(&obj, args.Holder());
133   CHECK(obj->streaming_);
134 
135   CHECK_EQ(args.Length(), 0);
136   obj->streaming_->Finish();
137 }
138 
Abort(const FunctionCallbackInfo<Value> & args)139 void WasmStreamingObject::Abort(const FunctionCallbackInfo<Value>& args) {
140   WasmStreamingObject* obj;
141   ASSIGN_OR_RETURN_UNWRAP(&obj, args.Holder());
142   CHECK(obj->streaming_);
143 
144   CHECK_EQ(args.Length(), 1);
145   obj->streaming_->Abort(args[0]);
146 }
147 
StartStreamingCompilation(const FunctionCallbackInfo<Value> & info)148 void StartStreamingCompilation(const FunctionCallbackInfo<Value>& info) {
149   // V8 passes an instance of v8::WasmStreaming to this callback, which we can
150   // use to pass the WebAssembly module bytes to V8 as we receive them.
151   // Unfortunately, our fetch() implementation is a JavaScript dependency, so it
152   // is difficult to implement the required logic here. Instead, we create a
153   // a WasmStreamingObject that encapsulates v8::WasmStreaming and that we can
154   // pass to the JavaScript implementation. The JavaScript implementation can
155   // then push() bytes from the Response and eventually either finish() or
156   // abort() the operation.
157 
158   // Create the wrapper object.
159   std::shared_ptr<WasmStreaming> streaming =
160       WasmStreaming::Unpack(info.GetIsolate(), info.Data());
161   Environment* env = Environment::GetCurrent(info);
162   Local<Object> obj;
163   if (!WasmStreamingObject::Create(env, streaming).ToLocal(&obj)) {
164     // A JavaScript exception is pending. Let V8 deal with it.
165     return;
166   }
167 
168   // V8 always passes one argument to this callback.
169   CHECK_EQ(info.Length(), 1);
170 
171   // Prepare the JavaScript implementation for invocation. We will pass the
172   // WasmStreamingObject as the first argument, followed by the argument that we
173   // received from V8, i.e., the first argument passed to compileStreaming (or
174   // instantiateStreaming).
175   Local<Function> impl = env->wasm_streaming_compilation_impl();
176   CHECK(!impl.IsEmpty());
177   Local<Value> args[] = {obj, info[0]};
178 
179   // Hand control to the JavaScript implementation. It should never throw an
180   // error, but if it does, we leave it to the calling V8 code to handle that
181   // gracefully. Otherwise, we assert that the JavaScript function does not
182   // return anything.
183   MaybeLocal<Value> maybe_ret =
184       impl->Call(env->context(), info.This(), 2, args);
185   Local<Value> ret;
186   CHECK_IMPLIES(maybe_ret.ToLocal(&ret), ret->IsUndefined());
187 }
188 
189 // Called once by JavaScript during initialization.
SetImplementation(const FunctionCallbackInfo<Value> & info)190 void SetImplementation(const FunctionCallbackInfo<Value>& info) {
191   Environment* env = Environment::GetCurrent(info);
192   env->set_wasm_streaming_compilation_impl(info[0].As<Function>());
193 }
194 
Initialize(Local<Object> target,Local<Value>,Local<Context> context,void *)195 void Initialize(Local<Object> target,
196                 Local<Value>,
197                 Local<Context> context,
198                 void*) {
199   SetMethod(context, target, "setImplementation", SetImplementation);
200 }
201 
RegisterExternalReferences(ExternalReferenceRegistry * registry)202 void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
203   registry->Register(SetImplementation);
204   registry->Register(StartStreamingCompilation);
205   WasmStreamingObject::RegisterExternalReferences(registry);
206 }
207 
208 }  // namespace wasm_web_api
209 }  // namespace node
210 
211 NODE_BINDING_CONTEXT_AWARE_INTERNAL(wasm_web_api,
212                                     node::wasm_web_api::Initialize)
213 NODE_BINDING_EXTERNAL_REFERENCE(wasm_web_api,
214                                 node::wasm_web_api::RegisterExternalReferences)
215