GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_blob.cc Lines: 240 279 86.0 %
Date: 2022-08-02 04:16:51 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
1303
void Blob::Initialize(
36
    Local<Object> target,
37
    Local<Value> unused,
38
    Local<Context> context,
39
    void* priv) {
40
1303
  Environment* env = Environment::GetCurrent(context);
41
42
  BlobBindingData* const binding_data =
43
1303
      env->AddBindingData<BlobBindingData>(context, target);
44
1303
  if (binding_data == nullptr) return;
45
46
1303
  SetMethod(context, target, "createBlob", New);
47
1303
  SetMethod(context, target, "storeDataObject", StoreDataObject);
48
1303
  SetMethod(context, target, "getDataObject", GetDataObject);
49
1303
  SetMethod(context, target, "revokeDataObject", RevokeDataObject);
50
1303
  FixedSizeBlobCopyJob::Initialize(env, target);
51
}
52
53
123
Local<FunctionTemplate> Blob::GetConstructorTemplate(Environment* env) {
54
123
  Local<FunctionTemplate> tmpl = env->blob_constructor_template();
55
123
  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
123
  return tmpl;
68
}
69
70
53
bool Blob::HasInstance(Environment* env, v8::Local<v8::Value> object) {
71
106
  return GetConstructorTemplate(env)->HasInstance(object);
72
}
73
74
70
BaseObjectPtr<Blob> Blob::Create(
75
    Environment* env,
76
    const std::vector<BlobEntry> store,
77
    size_t length) {
78
79
140
  HandleScope scope(env->isolate());
80
81
  Local<Function> ctor;
82
210
  if (!GetConstructorTemplate(env)->GetFunction(env->context()).ToLocal(&ctor))
83
    return BaseObjectPtr<Blob>();
84
85
  Local<Object> obj;
86
140
  if (!ctor->NewInstance(env->context()).ToLocal(&obj))
87
    return BaseObjectPtr<Blob>();
88
89
70
  return MakeBaseObject<Blob>(env, obj, store, length);
90
}
91
92
56
void Blob::New(const FunctionCallbackInfo<Value>& args) {
93
56
  Environment* env = Environment::GetCurrent(args);
94
56
  CHECK(args[0]->IsArray());  // sources
95
56
  CHECK(args[1]->IsUint32());  // length
96
97
56
  std::vector<BlobEntry> entries;
98
99
112
  size_t length = args[1].As<Uint32>()->Value();
100
56
  size_t len = 0;
101
56
  Local<Array> ary = args[0].As<Array>();
102
258
  for (size_t n = 0; n < ary->Length(); n++) {
103
    Local<Value> entry;
104
146
    if (!ary->Get(env->context(), n).ToLocal(&entry))
105
      return;
106

73
    CHECK(entry->IsArrayBufferView() || Blob::HasInstance(env, entry));
107
73
    if (entry->IsArrayBufferView()) {
108
72
      Local<ArrayBufferView> view = entry.As<ArrayBufferView>();
109
72
      CHECK_EQ(view->ByteOffset(), 0);
110
144
      std::shared_ptr<BackingStore> store = view->Buffer()->GetBackingStore();
111
72
      size_t byte_length = view->ByteLength();
112
144
      view->Buffer()->Detach();  // The Blob will own the backing store now.
113
72
      entries.emplace_back(BlobEntry{std::move(store), byte_length, 0});
114
72
      len += byte_length;
115
    } else {
116
      Blob* blob;
117
1
      ASSIGN_OR_RETURN_UNWRAP(&blob, entry);
118
1
      auto source = blob->entries();
119
1
      entries.insert(entries.end(), source.begin(), source.end());
120
1
      len += blob->length();
121
    }
122
  }
123
56
  CHECK_EQ(length, len);
124
125
112
  BaseObjectPtr<Blob> blob = Create(env, entries, length);
126
56
  if (blob)
127
112
    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
70
Blob::Blob(
209
    Environment* env,
210
    v8::Local<v8::Object> obj,
211
    const std::vector<BlobEntry>& store,
212
70
    size_t length)
213
    : BaseObject(env, obj),
214
      store_(store),
215
70
      length_(length) {
216
70
  MakeWeak();
217
70
}
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
1303
void FixedSizeBlobCopyJob::Initialize(Environment* env, Local<Object> target) {
367
1303
  Isolate* isolate = env->isolate();
368
1303
  v8::Local<v8::FunctionTemplate> job = NewFunctionTemplate(isolate, New);
369
1303
  job->Inherit(AsyncWrap::GetConstructorTemplate(env));
370
2606
  job->InstanceTemplate()->SetInternalFieldCount(
371
      AsyncWrap::kInternalFieldCount);
372
1303
  SetProtoMethod(isolate, job, "run", Run);
373
1303
  SetConstructorFunction(env->context(), target, "FixedSizeBlobCopyJob", job);
374
1303
}
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
5300
void FixedSizeBlobCopyJob::RegisterExternalReferences(
415
    ExternalReferenceRegistry* registry) {
416
5300
  registry->Register(New);
417
5300
  registry->Register(Run);
418
5300
}
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
6597
BlobBindingData::BlobBindingData(Environment* env, Local<Object> wrap)
435
6597
    : SnapshotableObject(env, wrap, type_int) {
436
6597
  MakeWeak();
437
6597
}
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
5294
void BlobBindingData::Deserialize(
466
    Local<Context> context,
467
    Local<Object> holder,
468
    int index,
469
    InternalFieldInfo* info) {
470
  DCHECK_EQ(index, BaseObject::kSlot);
471
10588
  HandleScope scope(context->GetIsolate());
472
5294
  Environment* env = Environment::GetCurrent(context);
473
  BlobBindingData* binding =
474
5294
      env->AddBindingData<BlobBindingData>(context, holder);
475
5294
  CHECK_NOT_NULL(binding);
476
5294
}
477
478
6
void BlobBindingData::PrepareForSerialization(
479
    Local<Context> context,
480
    v8::SnapshotCreator* creator) {
481
  // Stored blob objects are not actually persisted.
482
6
}
483
484
6
InternalFieldInfo* BlobBindingData::Serialize(int index) {
485
  DCHECK_EQ(index, BaseObject::kSlot);
486
6
  InternalFieldInfo* info = InternalFieldInfo::New(type());
487
6
  return info;
488
}
489
490
5300
void Blob::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
491
5300
  registry->Register(Blob::New);
492
5300
  registry->Register(Blob::ToArrayBuffer);
493
5300
  registry->Register(Blob::ToSlice);
494
5300
  registry->Register(Blob::StoreDataObject);
495
5300
  registry->Register(Blob::GetDataObject);
496
5300
  registry->Register(Blob::RevokeDataObject);
497
498
5300
  FixedSizeBlobCopyJob::RegisterExternalReferences(registry);
499
5300
}
500
501
}  // namespace node
502
503
5368
NODE_MODULE_CONTEXT_AWARE_INTERNAL(blob, node::Blob::Initialize)
504
5300
NODE_MODULE_EXTERNAL_REFERENCE(blob, node::Blob::RegisterExternalReferences)