GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_blob.cc Lines: 238 277 85.9 %
Date: 2021-09-24 04:12:43 Branches: 77 136 56.6 %

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
616
void Blob::Initialize(
35
    Local<Object> target,
36
    Local<Value> unused,
37
    Local<Context> context,
38
    void* priv) {
39
616
  Environment* env = Environment::GetCurrent(context);
40
41
  BlobBindingData* const binding_data =
42
616
      env->AddBindingData<BlobBindingData>(context, target);
43
616
  if (binding_data == nullptr) return;
44
45
616
  env->SetMethod(target, "createBlob", New);
46
616
  env->SetMethod(target, "storeDataObject", StoreDataObject);
47
616
  env->SetMethod(target, "getDataObject", GetDataObject);
48
616
  env->SetMethod(target, "revokeDataObject", RevokeDataObject);
49
616
  FixedSizeBlobCopyJob::Initialize(env, target);
50
}
51
52
116
Local<FunctionTemplate> Blob::GetConstructorTemplate(Environment* env) {
53
116
  Local<FunctionTemplate> tmpl = env->blob_constructor_template();
54
116
  if (tmpl.IsEmpty()) {
55
8
    tmpl = FunctionTemplate::New(env->isolate());
56
16
    tmpl->InstanceTemplate()->SetInternalFieldCount(
57
        BaseObject::kInternalFieldCount);
58
8
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
59
8
    tmpl->SetClassName(
60
        FIXED_ONE_BYTE_STRING(env->isolate(), "Blob"));
61
8
    env->SetProtoMethod(tmpl, "toArrayBuffer", ToArrayBuffer);
62
8
    env->SetProtoMethod(tmpl, "slice", ToSlice);
63
8
    env->set_blob_constructor_template(tmpl);
64
  }
65
116
  return tmpl;
66
}
67
68
50
bool Blob::HasInstance(Environment* env, v8::Local<v8::Value> object) {
69
100
  return GetConstructorTemplate(env)->HasInstance(object);
70
}
71
72
66
BaseObjectPtr<Blob> Blob::Create(
73
    Environment* env,
74
    const std::vector<BlobEntry> store,
75
    size_t length) {
76
77
132
  HandleScope scope(env->isolate());
78
79
  Local<Function> ctor;
80
198
  if (!GetConstructorTemplate(env)->GetFunction(env->context()).ToLocal(&ctor))
81
    return BaseObjectPtr<Blob>();
82
83
  Local<Object> obj;
84
132
  if (!ctor->NewInstance(env->context()).ToLocal(&obj))
85
    return BaseObjectPtr<Blob>();
86
87
66
  return MakeBaseObject<Blob>(env, obj, store, length);
88
}
89
90
52
void Blob::New(const FunctionCallbackInfo<Value>& args) {
91
52
  Environment* env = Environment::GetCurrent(args);
92
52
  CHECK(args[0]->IsArray());  // sources
93
52
  CHECK(args[1]->IsUint32());  // length
94
95
52
  std::vector<BlobEntry> entries;
96
97
104
  size_t length = args[1].As<Uint32>()->Value();
98
52
  size_t len = 0;
99
52
  Local<Array> ary = args[0].As<Array>();
100
228
  for (size_t n = 0; n < ary->Length(); n++) {
101
    Local<Value> entry;
102
124
    if (!ary->Get(env->context(), n).ToLocal(&entry))
103
      return;
104

62
    CHECK(entry->IsArrayBufferView() || Blob::HasInstance(env, entry));
105
62
    if (entry->IsArrayBufferView()) {
106
61
      Local<ArrayBufferView> view = entry.As<ArrayBufferView>();
107
61
      CHECK_EQ(view->ByteOffset(), 0);
108
122
      std::shared_ptr<BackingStore> store = view->Buffer()->GetBackingStore();
109
61
      size_t byte_length = view->ByteLength();
110
122
      view->Buffer()->Detach();  // The Blob will own the backing store now.
111
61
      entries.emplace_back(BlobEntry{std::move(store), byte_length, 0});
112
61
      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
52
  CHECK_EQ(length, len);
122
123
104
  BaseObjectPtr<Blob> blob = Create(env, entries, length);
124
52
  if (blob)
125
104
    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
66
Blob::Blob(
207
    Environment* env,
208
    v8::Local<v8::Object> obj,
209
    const std::vector<BlobEntry>& store,
210
66
    size_t length)
211
    : BaseObject(env, obj),
212
      store_(store),
213
66
      length_(length) {
214
66
  MakeWeak();
215
66
}
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
1
void Blob::RevokeDataObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
263
  BlobBindingData* binding_data =
264
1
      Environment::GetBindingData<BlobBindingData>(args);
265
266
1
  Environment* env = Environment::GetCurrent(args);
267
2
  CHECK(args[0]->IsString());  // ID key
268
269
1
  Utf8Value key(env->isolate(), args[0]);
270
271
1
  binding_data->revoke_data_object(std::string(*key, key.length()));
272
1
}
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
47
FixedSizeBlobCopyJob::FixedSizeBlobCopyJob(
310
    Environment* env,
311
    Local<Object> object,
312
    Blob* blob,
313
47
    FixedSizeBlobCopyJob::Mode mode)
314
    : AsyncWrap(env, object, AsyncWrap::PROVIDER_FIXEDSIZEBLOBCOPY),
315
      ThreadPoolWork(env),
316
47
      mode_(mode) {
317
47
  if (mode == FixedSizeBlobCopyJob::Mode::SYNC) MakeWeak();
318
47
  source_ = blob->entries();
319
47
  length_ = blob->length();
320
47
}
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
47
void FixedSizeBlobCopyJob::DoThreadPoolWork() {
343
47
  unsigned char* dest = static_cast<unsigned char*>(destination_->Data());
344
47
  if (length_ > 0) {
345
41
    size_t total = 0;
346
104
    for (const auto& entry : source_) {
347
63
      unsigned char* src = static_cast<unsigned char*>(entry.store->Data());
348
63
      src += entry.offset;
349
63
      memcpy(dest, src, entry.length);
350
63
      dest += entry.length;
351
63
      total += entry.length;
352
63
      CHECK_LE(total, length_);
353
    }
354
  }
355
47
}
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
616
void FixedSizeBlobCopyJob::Initialize(Environment* env, Local<Object> target) {
365
616
  v8::Local<v8::FunctionTemplate> job = env->NewFunctionTemplate(New);
366
616
  job->Inherit(AsyncWrap::GetConstructorTemplate(env));
367
1232
  job->InstanceTemplate()->SetInternalFieldCount(
368
      AsyncWrap::kInternalFieldCount);
369
616
  env->SetProtoMethod(job, "run", Run);
370
616
  env->SetConstructorFunction(target, "FixedSizeBlobCopyJob", job);
371
616
}
372
373
47
void FixedSizeBlobCopyJob::New(const FunctionCallbackInfo<Value>& args) {
374
  static constexpr size_t kMaxSyncLength = 4096;
375
  static constexpr size_t kMaxEntryCount = 4;
376
377
47
  Environment* env = Environment::GetCurrent(args);
378
47
  CHECK(args.IsConstructCall());
379
47
  CHECK(args[0]->IsObject());
380
47
  CHECK(Blob::HasInstance(env, args[0]));
381
382
  Blob* blob;
383
47
  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
46
      (blob->length() < kMaxSyncLength &&
390
140
       blob->entries().size() < kMaxEntryCount) ?
391
          FixedSizeBlobCopyJob::Mode::SYNC :
392
47
          FixedSizeBlobCopyJob::Mode::ASYNC;
393
394
47
  new FixedSizeBlobCopyJob(env, args.This(), blob, mode);
395
}
396
397
47
void FixedSizeBlobCopyJob::Run(const FunctionCallbackInfo<Value>& args) {
398
47
  Environment* env = Environment::GetCurrent(args);
399
  FixedSizeBlobCopyJob* job;
400
49
  ASSIGN_OR_RETURN_UNWRAP(&job, args.Holder());
401
47
  job->destination_ =
402
47
      ArrayBuffer::NewBackingStore(env->isolate(), job->length_);
403
47
  if (job->mode() == FixedSizeBlobCopyJob::Mode::ASYNC)
404
2
    return job->ScheduleWork();
405
406
45
  job->DoThreadPoolWork();
407
90
  args.GetReturnValue().Set(
408
45
      ArrayBuffer::New(env->isolate(), job->destination_));
409
}
410
411
4852
void FixedSizeBlobCopyJob::RegisterExternalReferences(
412
    ExternalReferenceRegistry* registry) {
413
4852
  registry->Register(New);
414
4852
  registry->Register(Run);
415
4852
}
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
5462
BlobBindingData::BlobBindingData(Environment* env, Local<Object> wrap)
432
5462
    : SnapshotableObject(env, wrap, type_int) {
433
5462
  MakeWeak();
434
5462
}
435
436
22
void BlobBindingData::MemoryInfo(MemoryTracker* tracker) const {
437
22
  tracker->TrackField("data_objects", data_objects_);
438
22
}
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
1
void BlobBindingData::revoke_data_object(const std::string& uuid) {
447
1
  CHECK_NE(data_objects_.find(uuid), data_objects_.end());
448
1
  data_objects_.erase(uuid);
449
1
  CHECK_EQ(data_objects_.find(uuid), data_objects_.end());
450
1
}
451
452
2
BlobBindingData::StoredDataObject BlobBindingData::get_data_object(
453
    const std::string& uuid) {
454
2
  auto entry = data_objects_.find(uuid);
455
2
  if (entry == data_objects_.end())
456
1
    return BlobBindingData::StoredDataObject {};
457
1
  return entry->second;
458
}
459
460
4846
void BlobBindingData::Deserialize(
461
    Local<Context> context,
462
    Local<Object> holder,
463
    int index,
464
    InternalFieldInfo* info) {
465
  DCHECK_EQ(index, BaseObject::kSlot);
466
9692
  HandleScope scope(context->GetIsolate());
467
4846
  Environment* env = Environment::GetCurrent(context);
468
  BlobBindingData* binding =
469
4846
      env->AddBindingData<BlobBindingData>(context, holder);
470
4846
  CHECK_NOT_NULL(binding);
471
4846
}
472
473
6
void BlobBindingData::PrepareForSerialization(
474
    Local<Context> context,
475
    v8::SnapshotCreator* creator) {
476
  // Stored blob objects are not actually persisted.
477
6
}
478
479
6
InternalFieldInfo* BlobBindingData::Serialize(int index) {
480
  DCHECK_EQ(index, BaseObject::kSlot);
481
6
  InternalFieldInfo* info = InternalFieldInfo::New(type());
482
6
  return info;
483
}
484
485
constexpr FastStringKey BlobBindingData::type_name;
486
487
4852
void Blob::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
488
4852
  registry->Register(Blob::New);
489
4852
  registry->Register(Blob::ToArrayBuffer);
490
4852
  registry->Register(Blob::ToSlice);
491
4852
  registry->Register(Blob::StoreDataObject);
492
4852
  registry->Register(Blob::GetDataObject);
493
4852
  registry->Register(Blob::RevokeDataObject);
494
495
4852
  FixedSizeBlobCopyJob::RegisterExternalReferences(registry);
496
4852
}
497
498
}  // namespace node
499
500
4925
NODE_MODULE_CONTEXT_AWARE_INTERNAL(blob, node::Blob::Initialize)
501
4852
NODE_MODULE_EXTERNAL_REFERENCE(blob, node::Blob::RegisterExternalReferences)