GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_blob.cc Lines: 240 279 86.0 %
Date: 2022-08-28 04:20:35 Branches: 78 136 57.4 %

Line Branch Exec Source
1
#include "node_blob.h"
2
#include "async_wrap-inl.h"
3
#include "base_object-inl.h"
4
#include "env-inl.h"
5
#include "memory_tracker-inl.h"
6
#include "node_errors.h"
7
#include "node_external_reference.h"
8
#include "threadpoolwork-inl.h"
9
#include "v8.h"
10
11
#include <algorithm>
12
13
namespace node {
14
15
using v8::Array;
16
using v8::ArrayBuffer;
17
using v8::ArrayBufferView;
18
using v8::BackingStore;
19
using v8::Context;
20
using v8::EscapableHandleScope;
21
using v8::Function;
22
using v8::FunctionCallbackInfo;
23
using v8::FunctionTemplate;
24
using v8::HandleScope;
25
using v8::Isolate;
26
using v8::Local;
27
using v8::MaybeLocal;
28
using v8::Number;
29
using v8::Object;
30
using v8::String;
31
using v8::Uint32;
32
using v8::Undefined;
33
using v8::Value;
34
35
775
void Blob::Initialize(
36
    Local<Object> target,
37
    Local<Value> unused,
38
    Local<Context> context,
39
    void* priv) {
40
775
  Environment* env = Environment::GetCurrent(context);
41
42
  BlobBindingData* const binding_data =
43
775
      env->AddBindingData<BlobBindingData>(context, target);
44
775
  if (binding_data == nullptr) return;
45
46
775
  SetMethod(context, target, "createBlob", New);
47
775
  SetMethod(context, target, "storeDataObject", StoreDataObject);
48
775
  SetMethod(context, target, "getDataObject", GetDataObject);
49
775
  SetMethod(context, target, "revokeDataObject", RevokeDataObject);
50
775
  FixedSizeBlobCopyJob::Initialize(env, target);
51
}
52
53
174
Local<FunctionTemplate> Blob::GetConstructorTemplate(Environment* env) {
54
174
  Local<FunctionTemplate> tmpl = env->blob_constructor_template();
55
174
  if (tmpl.IsEmpty()) {
56
10
    Isolate* isolate = env->isolate();
57
10
    tmpl = NewFunctionTemplate(isolate, nullptr);
58
20
    tmpl->InstanceTemplate()->SetInternalFieldCount(
59
        BaseObject::kInternalFieldCount);
60
10
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
61
10
    tmpl->SetClassName(
62
        FIXED_ONE_BYTE_STRING(env->isolate(), "Blob"));
63
10
    SetProtoMethod(isolate, tmpl, "toArrayBuffer", ToArrayBuffer);
64
10
    SetProtoMethod(isolate, tmpl, "slice", ToSlice);
65
10
    env->set_blob_constructor_template(tmpl);
66
  }
67
174
  return tmpl;
68
}
69
70
56
bool Blob::HasInstance(Environment* env, v8::Local<v8::Value> object) {
71
112
  return GetConstructorTemplate(env)->HasInstance(object);
72
}
73
74
118
BaseObjectPtr<Blob> Blob::Create(
75
    Environment* env,
76
    const std::vector<BlobEntry> store,
77
    size_t length) {
78
79
236
  HandleScope scope(env->isolate());
80
81
  Local<Function> ctor;
82
354
  if (!GetConstructorTemplate(env)->GetFunction(env->context()).ToLocal(&ctor))
83
    return BaseObjectPtr<Blob>();
84
85
  Local<Object> obj;
86
236
  if (!ctor->NewInstance(env->context()).ToLocal(&obj))
87
    return BaseObjectPtr<Blob>();
88
89
118
  return MakeBaseObject<Blob>(env, obj, store, length);
90
}
91
92
104
void Blob::New(const FunctionCallbackInfo<Value>& args) {
93
104
  Environment* env = Environment::GetCurrent(args);
94
104
  CHECK(args[0]->IsArray());  // sources
95
104
  CHECK(args[1]->IsUint32());  // length
96
97
104
  std::vector<BlobEntry> entries;
98
99
208
  size_t length = args[1].As<Uint32>()->Value();
100
104
  size_t len = 0;
101
104
  Local<Array> ary = args[0].As<Array>();
102
496
  for (size_t n = 0; n < ary->Length(); n++) {
103
    Local<Value> entry;
104
288
    if (!ary->Get(env->context(), n).ToLocal(&entry))
105
      return;
106

144
    CHECK(entry->IsArrayBufferView() || Blob::HasInstance(env, entry));
107
144
    if (entry->IsArrayBufferView()) {
108
140
      Local<ArrayBufferView> view = entry.As<ArrayBufferView>();
109
140
      CHECK_EQ(view->ByteOffset(), 0);
110
280
      std::shared_ptr<BackingStore> store = view->Buffer()->GetBackingStore();
111
140
      size_t byte_length = view->ByteLength();
112
280
      view->Buffer()->Detach();  // The Blob will own the backing store now.
113
140
      entries.emplace_back(BlobEntry{std::move(store), byte_length, 0});
114
140
      len += byte_length;
115
    } else {
116
      Blob* blob;
117
4
      ASSIGN_OR_RETURN_UNWRAP(&blob, entry);
118
4
      auto source = blob->entries();
119
4
      entries.insert(entries.end(), source.begin(), source.end());
120
4
      len += blob->length();
121
    }
122
  }
123
104
  CHECK_EQ(length, len);
124
125
208
  BaseObjectPtr<Blob> blob = Create(env, entries, length);
126
104
  if (blob)
127
208
    args.GetReturnValue().Set(blob->object());
128
}
129
130
void Blob::ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
131
  Environment* env = Environment::GetCurrent(args);
132
  Blob* blob;
133
  ASSIGN_OR_RETURN_UNWRAP(&blob, args.Holder());
134
  Local<Value> ret;
135
  if (blob->GetArrayBuffer(env).ToLocal(&ret))
136
    args.GetReturnValue().Set(ret);
137
}
138
139
13
void Blob::ToSlice(const FunctionCallbackInfo<Value>& args) {
140
13
  Environment* env = Environment::GetCurrent(args);
141
  Blob* blob;
142
13
  ASSIGN_OR_RETURN_UNWRAP(&blob, args.Holder());
143
13
  CHECK(args[0]->IsUint32());
144
13
  CHECK(args[1]->IsUint32());
145
26
  size_t start = args[0].As<Uint32>()->Value();
146
26
  size_t end = args[1].As<Uint32>()->Value();
147
26
  BaseObjectPtr<Blob> slice = blob->Slice(env, start, end);
148
13
  if (slice)
149
26
    args.GetReturnValue().Set(slice->object());
150
}
151
152
void Blob::MemoryInfo(MemoryTracker* tracker) const {
153
  tracker->TrackFieldWithSize("store", length_);
154
}
155
156
MaybeLocal<Value> Blob::GetArrayBuffer(Environment* env) {
157
  EscapableHandleScope scope(env->isolate());
158
  size_t len = length();
159
  std::shared_ptr<BackingStore> store =
160
      ArrayBuffer::NewBackingStore(env->isolate(), len);
161
  if (len > 0) {
162
    unsigned char* dest = static_cast<unsigned char*>(store->Data());
163
    size_t total = 0;
164
    for (const auto& entry : entries()) {
165
      unsigned char* src = static_cast<unsigned char*>(entry.store->Data());
166
      src += entry.offset;
167
      memcpy(dest, src, entry.length);
168
      dest += entry.length;
169
      total += entry.length;
170
      CHECK_LE(total, len);
171
    }
172
  }
173
174
  return scope.Escape(ArrayBuffer::New(env->isolate(), store));
175
}
176
177
13
BaseObjectPtr<Blob> Blob::Slice(Environment* env, size_t start, size_t end) {
178
13
  CHECK_LE(start, length());
179
13
  CHECK_LE(end, length());
180
13
  CHECK_LE(start, end);
181
182
26
  std::vector<BlobEntry> slices;
183
13
  size_t total = end - start;
184
13
  size_t remaining = total;
185
186
13
  if (total == 0) return Create(env, slices, 0);
187
188
23
  for (const auto& entry : entries()) {
189
14
    if (start + entry.offset > entry.store->ByteLength()) {
190
      start -= entry.length;
191
      continue;
192
    }
193
194
14
    size_t offset = entry.offset + start;
195
14
    size_t len = std::min(remaining, entry.store->ByteLength() - offset);
196
14
    slices.emplace_back(BlobEntry{entry.store, len, offset});
197
198
14
    remaining -= len;
199
14
    start = 0;
200
201
14
    if (remaining == 0)
202
9
      break;
203
  }
204
205
9
  return Create(env, slices, total);
206
}
207
208
118
Blob::Blob(
209
    Environment* env,
210
    v8::Local<v8::Object> obj,
211
    const std::vector<BlobEntry>& store,
212
118
    size_t length)
213
    : BaseObject(env, obj),
214
      store_(store),
215
118
      length_(length) {
216
118
  MakeWeak();
217
118
}
218
219
BaseObjectPtr<BaseObject>
220
1
Blob::BlobTransferData::Deserialize(
221
    Environment* env,
222
    Local<Context> context,
223
    std::unique_ptr<worker::TransferData> self) {
224
2
  if (context != env->context()) {
225
    THROW_ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE(env);
226
    return {};
227
  }
228
1
  return Blob::Create(env, store_, length_);
229
}
230
231
1
BaseObject::TransferMode Blob::GetTransferMode() const {
232
1
  return BaseObject::TransferMode::kCloneable;
233
}
234
235
1
std::unique_ptr<worker::TransferData> Blob::CloneForMessaging() const {
236
1
  return std::make_unique<BlobTransferData>(store_, length_);
237
}
238
239
2
void Blob::StoreDataObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
240
2
  Environment* env = Environment::GetCurrent(args);
241
  BlobBindingData* binding_data =
242
2
      Environment::GetBindingData<BlobBindingData>(args);
243
244
4
  CHECK(args[0]->IsString());  // ID key
245
2
  CHECK(Blob::HasInstance(env, args[1]));  // Blob
246
2
  CHECK(args[2]->IsUint32());  // Length
247
4
  CHECK(args[3]->IsString());  // Type
248
249
2
  Utf8Value key(env->isolate(), args[0]);
250
  Blob* blob;
251
2
  ASSIGN_OR_RETURN_UNWRAP(&blob, args[1]);
252
253
4
  size_t length = args[2].As<Uint32>()->Value();
254
2
  Utf8Value type(env->isolate(), args[3]);
255
256
2
  binding_data->store_data_object(
257
4
      std::string(*key, key.length()),
258
4
      BlobBindingData::StoredDataObject(
259
4
        BaseObjectPtr<Blob>(blob),
260
        length,
261
4
        std::string(*type, type.length())));
262
}
263
264
2
void Blob::RevokeDataObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
265
  BlobBindingData* binding_data =
266
2
      Environment::GetBindingData<BlobBindingData>(args);
267
268
2
  Environment* env = Environment::GetCurrent(args);
269
4
  CHECK(args[0]->IsString());  // ID key
270
271
2
  Utf8Value key(env->isolate(), args[0]);
272
273
2
  binding_data->revoke_data_object(std::string(*key, key.length()));
274
2
}
275
276
2
void Blob::GetDataObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
277
  BlobBindingData* binding_data =
278
2
      Environment::GetBindingData<BlobBindingData>(args);
279
280
2
  Environment* env = Environment::GetCurrent(args);
281
4
  CHECK(args[0]->IsString());
282
283
2
  Utf8Value key(env->isolate(), args[0]);
284
285
  BlobBindingData::StoredDataObject stored =
286
4
      binding_data->get_data_object(std::string(*key, key.length()));
287
2
  if (stored.blob) {
288
    Local<Value> type;
289
1
    if (!String::NewFromUtf8(
290
            env->isolate(),
291
            stored.type.c_str(),
292
            v8::NewStringType::kNormal,
293
2
            static_cast<int>(stored.type.length())).ToLocal(&type)) {
294
      return;
295
    }
296
297
    Local<Value> values[] = {
298
1
      stored.blob->object(),
299
1
      Uint32::NewFromUnsigned(env->isolate(), stored.length),
300
      type
301
3
    };
302
303
2
    args.GetReturnValue().Set(
304
        Array::New(
305
            env->isolate(),
306
            values,
307
            arraysize(values)));
308
  }
309
}
310
311
50
FixedSizeBlobCopyJob::FixedSizeBlobCopyJob(
312
    Environment* env,
313
    Local<Object> object,
314
    Blob* blob,
315
50
    FixedSizeBlobCopyJob::Mode mode)
316
    : AsyncWrap(env, object, AsyncWrap::PROVIDER_FIXEDSIZEBLOBCOPY),
317
      ThreadPoolWork(env),
318
50
      mode_(mode) {
319
50
  if (mode == FixedSizeBlobCopyJob::Mode::SYNC) MakeWeak();
320
50
  source_ = blob->entries();
321
50
  length_ = blob->length();
322
50
}
323
324
2
void FixedSizeBlobCopyJob::AfterThreadPoolWork(int status) {
325
2
  Environment* env = AsyncWrap::env();
326
2
  CHECK_EQ(mode_, Mode::ASYNC);
327

2
  CHECK(status == 0 || status == UV_ECANCELED);
328
4
  std::unique_ptr<FixedSizeBlobCopyJob> ptr(this);
329
4
  HandleScope handle_scope(env->isolate());
330
2
  Context::Scope context_scope(env->context());
331
6
  Local<Value> args[2];
332
333
2
  if (status == UV_ECANCELED) {
334
    args[0] = Number::New(env->isolate(), status),
335
    args[1] = Undefined(env->isolate());
336
  } else {
337
2
    args[0] = Undefined(env->isolate());
338
4
    args[1] = ArrayBuffer::New(env->isolate(), destination_);
339
  }
340
341
2
  ptr->MakeCallback(env->ondone_string(), arraysize(args), args);
342
2
}
343
344
50
void FixedSizeBlobCopyJob::DoThreadPoolWork() {
345
50
  unsigned char* dest = static_cast<unsigned char*>(destination_->Data());
346
50
  if (length_ > 0) {
347
44
    size_t total = 0;
348
111
    for (const auto& entry : source_) {
349
67
      unsigned char* src = static_cast<unsigned char*>(entry.store->Data());
350
67
      src += entry.offset;
351
67
      memcpy(dest, src, entry.length);
352
67
      dest += entry.length;
353
67
      total += entry.length;
354
67
      CHECK_LE(total, length_);
355
    }
356
  }
357
50
}
358
359
void FixedSizeBlobCopyJob::MemoryInfo(MemoryTracker* tracker) const {
360
  tracker->TrackFieldWithSize("source", length_);
361
  tracker->TrackFieldWithSize(
362
      "destination",
363
      destination_ ? destination_->ByteLength() : 0);
364
}
365
366
775
void FixedSizeBlobCopyJob::Initialize(Environment* env, Local<Object> target) {
367
775
  Isolate* isolate = env->isolate();
368
775
  v8::Local<v8::FunctionTemplate> job = NewFunctionTemplate(isolate, New);
369
775
  job->Inherit(AsyncWrap::GetConstructorTemplate(env));
370
1550
  job->InstanceTemplate()->SetInternalFieldCount(
371
      AsyncWrap::kInternalFieldCount);
372
775
  SetProtoMethod(isolate, job, "run", Run);
373
775
  SetConstructorFunction(env->context(), target, "FixedSizeBlobCopyJob", job);
374
775
}
375
376
50
void FixedSizeBlobCopyJob::New(const FunctionCallbackInfo<Value>& args) {
377
  static constexpr size_t kMaxSyncLength = 4096;
378
  static constexpr size_t kMaxEntryCount = 4;
379
380
50
  Environment* env = Environment::GetCurrent(args);
381
50
  CHECK(args.IsConstructCall());
382
50
  CHECK(args[0]->IsObject());
383
50
  CHECK(Blob::HasInstance(env, args[0]));
384
385
  Blob* blob;
386
50
  ASSIGN_OR_RETURN_UNWRAP(&blob, args[0]);
387
388
  // This is a fairly arbitrary heuristic. We want to avoid deferring to
389
  // the threadpool if the amount of data being copied is small and there
390
  // aren't that many entries to copy.
391
  FixedSizeBlobCopyJob::Mode mode =
392
49
      (blob->length() < kMaxSyncLength &&
393
149
       blob->entries().size() < kMaxEntryCount) ?
394
          FixedSizeBlobCopyJob::Mode::SYNC :
395
50
          FixedSizeBlobCopyJob::Mode::ASYNC;
396
397
50
  new FixedSizeBlobCopyJob(env, args.This(), blob, mode);
398
}
399
400
50
void FixedSizeBlobCopyJob::Run(const FunctionCallbackInfo<Value>& args) {
401
50
  Environment* env = Environment::GetCurrent(args);
402
  FixedSizeBlobCopyJob* job;
403
52
  ASSIGN_OR_RETURN_UNWRAP(&job, args.Holder());
404
50
  job->destination_ =
405
50
      ArrayBuffer::NewBackingStore(env->isolate(), job->length_);
406
50
  if (job->mode() == FixedSizeBlobCopyJob::Mode::ASYNC)
407
2
    return job->ScheduleWork();
408
409
48
  job->DoThreadPoolWork();
410
96
  args.GetReturnValue().Set(
411
48
      ArrayBuffer::New(env->isolate(), job->destination_));
412
}
413
414
5378
void FixedSizeBlobCopyJob::RegisterExternalReferences(
415
    ExternalReferenceRegistry* registry) {
416
5378
  registry->Register(New);
417
5378
  registry->Register(Run);
418
5378
}
419
420
void BlobBindingData::StoredDataObject::MemoryInfo(
421
    MemoryTracker* tracker) const {
422
  tracker->TrackField("blob", blob);
423
  tracker->TrackFieldWithSize("type", type.length());
424
}
425
426
2
BlobBindingData::StoredDataObject::StoredDataObject(
427
    const BaseObjectPtr<Blob>& blob_,
428
    size_t length_,
429
2
    const std::string& type_)
430
    : blob(blob_),
431
      length(length_),
432
2
      type(type_) {}
433
434
6146
BlobBindingData::BlobBindingData(Environment* env, Local<Object> wrap)
435
6146
    : SnapshotableObject(env, wrap, type_int) {
436
6146
  MakeWeak();
437
6146
}
438
439
24
void BlobBindingData::MemoryInfo(MemoryTracker* tracker) const {
440
24
  tracker->TrackField("data_objects", data_objects_);
441
24
}
442
443
2
void BlobBindingData::store_data_object(
444
    const std::string& uuid,
445
    const BlobBindingData::StoredDataObject& object) {
446
2
  data_objects_[uuid] = object;
447
2
}
448
449
2
void BlobBindingData::revoke_data_object(const std::string& uuid) {
450
2
  if (data_objects_.find(uuid) == data_objects_.end()) {
451
1
    return;
452
  }
453
1
  data_objects_.erase(uuid);
454
1
  CHECK_EQ(data_objects_.find(uuid), data_objects_.end());
455
}
456
457
2
BlobBindingData::StoredDataObject BlobBindingData::get_data_object(
458
    const std::string& uuid) {
459
2
  auto entry = data_objects_.find(uuid);
460
2
  if (entry == data_objects_.end())
461
1
    return BlobBindingData::StoredDataObject {};
462
1
  return entry->second;
463
}
464
465
5371
void BlobBindingData::Deserialize(Local<Context> context,
466
                                  Local<Object> holder,
467
                                  int index,
468
                                  InternalFieldInfoBase* info) {
469
  DCHECK_EQ(index, BaseObject::kEmbedderType);
470
10742
  HandleScope scope(context->GetIsolate());
471
5371
  Environment* env = Environment::GetCurrent(context);
472
  BlobBindingData* binding =
473
5371
      env->AddBindingData<BlobBindingData>(context, holder);
474
5371
  CHECK_NOT_NULL(binding);
475
5371
}
476
477
6
bool BlobBindingData::PrepareForSerialization(Local<Context> context,
478
                                              v8::SnapshotCreator* creator) {
479
  // Stored blob objects are not actually persisted.
480
  // Return true because we need to maintain the reference to the binding from
481
  // JS land.
482
6
  return true;
483
}
484
485
6
InternalFieldInfoBase* BlobBindingData::Serialize(int index) {
486
  DCHECK_EQ(index, BaseObject::kEmbedderType);
487
  InternalFieldInfo* info =
488
6
      InternalFieldInfoBase::New<InternalFieldInfo>(type());
489
6
  return info;
490
}
491
492
5378
void Blob::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
493
5378
  registry->Register(Blob::New);
494
5378
  registry->Register(Blob::ToArrayBuffer);
495
5378
  registry->Register(Blob::ToSlice);
496
5378
  registry->Register(Blob::StoreDataObject);
497
5378
  registry->Register(Blob::GetDataObject);
498
5378
  registry->Register(Blob::RevokeDataObject);
499
500
5378
  FixedSizeBlobCopyJob::RegisterExternalReferences(registry);
501
5378
}
502
503
}  // namespace node
504
505
5450
NODE_MODULE_CONTEXT_AWARE_INTERNAL(blob, node::Blob::Initialize)
506
5378
NODE_MODULE_EXTERNAL_REFERENCE(blob, node::Blob::RegisterExternalReferences)