GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_blob.cc Lines: 238 277 85.9 %
Date: 2022-05-23 04:15:47 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::Local;
26
using v8::MaybeLocal;
27
using v8::Number;
28
using v8::Object;
29
using v8::String;
30
using v8::Uint32;
31
using v8::Undefined;
32
using v8::Value;
33
34
847
void Blob::Initialize(
35
    Local<Object> target,
36
    Local<Value> unused,
37
    Local<Context> context,
38
    void* priv) {
39
847
  Environment* env = Environment::GetCurrent(context);
40
41
  BlobBindingData* const binding_data =
42
847
      env->AddBindingData<BlobBindingData>(context, target);
43
847
  if (binding_data == nullptr) return;
44
45
847
  env->SetMethod(target, "createBlob", New);
46
847
  env->SetMethod(target, "storeDataObject", StoreDataObject);
47
847
  env->SetMethod(target, "getDataObject", GetDataObject);
48
847
  env->SetMethod(target, "revokeDataObject", RevokeDataObject);
49
847
  FixedSizeBlobCopyJob::Initialize(env, target);
50
}
51
52
273
Local<FunctionTemplate> Blob::GetConstructorTemplate(Environment* env) {
53
273
  Local<FunctionTemplate> tmpl = env->blob_constructor_template();
54
273
  if (tmpl.IsEmpty()) {
55
14
    tmpl = FunctionTemplate::New(env->isolate());
56
28
    tmpl->InstanceTemplate()->SetInternalFieldCount(
57
        BaseObject::kInternalFieldCount);
58
14
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
59
14
    tmpl->SetClassName(
60
        FIXED_ONE_BYTE_STRING(env->isolate(), "Blob"));
61
14
    env->SetProtoMethod(tmpl, "toArrayBuffer", ToArrayBuffer);
62
14
    env->SetProtoMethod(tmpl, "slice", ToSlice);
63
14
    env->set_blob_constructor_template(tmpl);
64
  }
65
273
  return tmpl;
66
}
67
68
128
bool Blob::HasInstance(Environment* env, v8::Local<v8::Value> object) {
69
256
  return GetConstructorTemplate(env)->HasInstance(object);
70
}
71
72
145
BaseObjectPtr<Blob> Blob::Create(
73
    Environment* env,
74
    const std::vector<BlobEntry> store,
75
    size_t length) {
76
77
290
  HandleScope scope(env->isolate());
78
79
  Local<Function> ctor;
80
435
  if (!GetConstructorTemplate(env)->GetFunction(env->context()).ToLocal(&ctor))
81
    return BaseObjectPtr<Blob>();
82
83
  Local<Object> obj;
84
290
  if (!ctor->NewInstance(env->context()).ToLocal(&obj))
85
    return BaseObjectPtr<Blob>();
86
87
145
  return MakeBaseObject<Blob>(env, obj, store, length);
88
}
89
90
131
void Blob::New(const FunctionCallbackInfo<Value>& args) {
91
131
  Environment* env = Environment::GetCurrent(args);
92
131
  CHECK(args[0]->IsArray());  // sources
93
131
  CHECK(args[1]->IsUint32());  // length
94
95
131
  std::vector<BlobEntry> entries;
96
97
262
  size_t length = args[1].As<Uint32>()->Value();
98
131
  size_t len = 0;
99
131
  Local<Array> ary = args[0].As<Array>();
100
558
  for (size_t n = 0; n < ary->Length(); n++) {
101
    Local<Value> entry;
102
296
    if (!ary->Get(env->context(), n).ToLocal(&entry))
103
      return;
104

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

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