GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 620 686 90.4 %
Date: 2021-10-04 04:12:38 Branches: 308 522 59.0 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_buffer.h"
23
#include "allocated_buffer-inl.h"
24
#include "node.h"
25
#include "node_blob.h"
26
#include "node_errors.h"
27
#include "node_external_reference.h"
28
#include "node_internals.h"
29
30
#include "env-inl.h"
31
#include "string_bytes.h"
32
#include "string_search.h"
33
#include "util-inl.h"
34
#include "v8.h"
35
36
#include <cstring>
37
#include <climits>
38
39
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
40
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
41
42
#define THROW_AND_RETURN_IF_OOB(r)                                          \
43
  do {                                                                      \
44
    if ((r).IsNothing()) return;                                            \
45
    if (!(r).FromJust())                                                    \
46
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
47
  } while (0)                                                               \
48
49
namespace node {
50
namespace Buffer {
51
52
using v8::ArrayBuffer;
53
using v8::ArrayBufferView;
54
using v8::BackingStore;
55
using v8::Context;
56
using v8::EscapableHandleScope;
57
using v8::FunctionCallbackInfo;
58
using v8::Global;
59
using v8::HandleScope;
60
using v8::Int32;
61
using v8::Integer;
62
using v8::Isolate;
63
using v8::Just;
64
using v8::Local;
65
using v8::Maybe;
66
using v8::MaybeLocal;
67
using v8::Nothing;
68
using v8::Number;
69
using v8::Object;
70
using v8::SharedArrayBuffer;
71
using v8::String;
72
using v8::Uint32;
73
using v8::Uint32Array;
74
using v8::Uint8Array;
75
using v8::Value;
76
77
namespace {
78
79
class CallbackInfo {
80
 public:
81
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
82
      Environment* env,
83
      char* data,
84
      size_t length,
85
      FreeCallback callback,
86
      void* hint);
87
88
  CallbackInfo(const CallbackInfo&) = delete;
89
  CallbackInfo& operator=(const CallbackInfo&) = delete;
90
91
 private:
92
  static void CleanupHook(void* data);
93
  inline void OnBackingStoreFree();
94
  inline void CallAndResetCallback();
95
  inline CallbackInfo(Environment* env,
96
                      FreeCallback callback,
97
                      char* data,
98
                      void* hint);
99
  Global<ArrayBuffer> persistent_;
100
  Mutex mutex_;  // Protects callback_.
101
  FreeCallback callback_;
102
  char* const data_;
103
  void* const hint_;
104
  Environment* const env_;
105
};
106
107
108
951
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
109
    Environment* env,
110
    char* data,
111
    size_t length,
112
    FreeCallback callback,
113
    void* hint) {
114
951
  CHECK_NOT_NULL(callback);
115

951
  CHECK_IMPLIES(data == nullptr, length == 0);
116
117
951
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
118
  std::unique_ptr<BackingStore> bs =
119
948
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
120
948
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
121
951
      }, self);
122
951
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
123
124
  // V8 simply ignores the BackingStore deleter callback if data == nullptr,
125
  // but our API contract requires it being called.
126
951
  if (data == nullptr) {
127
3
    ab->Detach();
128
3
    self->OnBackingStoreFree();  // This calls `callback` asynchronously.
129
  } else {
130
    // Store the ArrayBuffer so that we can detach it later.
131
948
    self->persistent_.Reset(env->isolate(), ab);
132
948
    self->persistent_.SetWeak();
133
  }
134
135
951
  return ab;
136
}
137
138
139
951
CallbackInfo::CallbackInfo(Environment* env,
140
                           FreeCallback callback,
141
                           char* data,
142
951
                           void* hint)
143
    : callback_(callback),
144
      data_(data),
145
      hint_(hint),
146
1902
      env_(env) {
147
951
  env->AddCleanupHook(CleanupHook, this);
148
951
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
149
951
}
150
151
681
void CallbackInfo::CleanupHook(void* data) {
152
681
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
153
154
  {
155
1362
    HandleScope handle_scope(self->env_->isolate());
156
1362
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
157

1362
    if (!ab.IsEmpty() && ab->IsDetachable()) {
158
681
      ab->Detach();
159
681
      self->persistent_.Reset();
160
    }
161
  }
162
163
  // Call the callback in this case, but don't delete `this` yet because the
164
  // BackingStore deleter callback will do so later.
165
681
  self->CallAndResetCallback();
166
681
}
167
168
1629
void CallbackInfo::CallAndResetCallback() {
169
  FreeCallback callback;
170
  {
171
1629
    Mutex::ScopedLock lock(mutex_);
172
1629
    callback = callback_;
173
1629
    callback_ = nullptr;
174
  }
175
1629
  if (callback != nullptr) {
176
    // Clean up all Environment-related state and run the callback.
177
948
    env_->RemoveCleanupHook(CleanupHook, this);
178
948
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
179
948
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
180
181
948
    callback(data_, hint_);
182
  }
183
1629
}
184
185
951
void CallbackInfo::OnBackingStoreFree() {
186
  // This method should always release the memory for `this`.
187
951
  std::unique_ptr<CallbackInfo> self { this };
188
951
  Mutex::ScopedLock lock(mutex_);
189
  // If callback_ == nullptr, that means that the callback has already run from
190
  // the cleanup hook, and there is nothing left to do here besides to clean
191
  // up the memory involved. In particular, the underlying `Environment` may
192
  // be gone at this point, so don’t attempt to call SetImmediateThreadsafe().
193
951
  if (callback_ == nullptr) return;
194
195
951
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
196
948
    CHECK_EQ(self->env_, env);  // Consistency check.
197
198
948
    self->CallAndResetCallback();
199
948
  });
200
}
201
202
203
// Parse index for external array data. An empty Maybe indicates
204
// a pending exception. `false` indicates that the index is out-of-bounds.
205
1100956
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
206
                                                   Local<Value> arg,
207
                                                   size_t def,
208
                                                   size_t* ret) {
209
2201912
  if (arg->IsUndefined()) {
210
    *ret = def;
211
    return Just(true);
212
  }
213
214
  int64_t tmp_i;
215
2201912
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
216
    return Nothing<bool>();
217
218
1100956
  if (tmp_i < 0)
219
4
    return Just(false);
220
221
  // Check that the result fits in a size_t.
222
1100952
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
223
  // coverity[pointless_expression]
224
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
225
    return Just(false);
226
227
1100952
  *ret = static_cast<size_t>(tmp_i);
228
1100952
  return Just(true);
229
}
230
231
}  // anonymous namespace
232
233
// Buffer methods
234
235
3468546
bool HasInstance(Local<Value> val) {
236
3468546
  return val->IsArrayBufferView();
237
}
238
239
240
275218
bool HasInstance(Local<Object> obj) {
241
275218
  return obj->IsArrayBufferView();
242
}
243
244
245
273589
char* Data(Local<Value> val) {
246
273589
  CHECK(val->IsArrayBufferView());
247
273589
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
248
820767
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
249
273589
      ui->ByteOffset();
250
}
251
252
253
142853
char* Data(Local<Object> obj) {
254
142853
  return Data(obj.As<Value>());
255
}
256
257
258
104142
size_t Length(Local<Value> val) {
259
104142
  CHECK(val->IsArrayBufferView());
260
104142
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
261
104142
  return ui->ByteLength();
262
}
263
264
265
141440
size_t Length(Local<Object> obj) {
266
141440
  CHECK(obj->IsArrayBufferView());
267
141440
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
268
141440
  return ui->ByteLength();
269
}
270
271
272
13272
MaybeLocal<Uint8Array> New(Environment* env,
273
                           Local<ArrayBuffer> ab,
274
                           size_t byte_offset,
275
                           size_t length) {
276
26544
  CHECK(!env->buffer_prototype_object().IsEmpty());
277
13272
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
278
  Maybe<bool> mb =
279
26544
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
280
13272
  if (mb.IsNothing())
281
    return MaybeLocal<Uint8Array>();
282
13272
  return ui;
283
}
284
285
295
MaybeLocal<Uint8Array> New(Isolate* isolate,
286
                           Local<ArrayBuffer> ab,
287
                           size_t byte_offset,
288
                           size_t length) {
289
295
  Environment* env = Environment::GetCurrent(isolate);
290
295
  if (env == nullptr) {
291
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
292
    return MaybeLocal<Uint8Array>();
293
  }
294
295
  return New(env, ab, byte_offset, length);
295
}
296
297
298
296
MaybeLocal<Object> New(Isolate* isolate,
299
                       Local<String> string,
300
                       enum encoding enc) {
301
296
  EscapableHandleScope scope(isolate);
302
303
  size_t length;
304
592
  if (!StringBytes::Size(isolate, string, enc).To(&length))
305
    return Local<Object>();
306
296
  size_t actual = 0;
307
296
  std::unique_ptr<BackingStore> store;
308
309
296
  if (length > 0) {
310
296
    store = ArrayBuffer::NewBackingStore(isolate, length);
311
312
296
    if (UNLIKELY(!store)) {
313
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
314
      return Local<Object>();
315
    }
316
317
296
    actual = StringBytes::Write(
318
        isolate,
319
296
        static_cast<char*>(store->Data()),
320
        length,
321
        string,
322
        enc);
323
296
    CHECK(actual <= length);
324
325
296
    if (LIKELY(actual > 0)) {
326
295
      if (actual < length)
327
        store = BackingStore::Reallocate(isolate, std::move(store), actual);
328
295
      Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
329
      Local<Object> obj;
330
590
      if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
331
        return MaybeLocal<Object>();
332
295
      return scope.Escape(obj);
333
    }
334
  }
335
336
2
  return scope.EscapeMaybe(New(isolate, 0));
337
}
338
339
340
2
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
341
2
  EscapableHandleScope handle_scope(isolate);
342
  Local<Object> obj;
343
2
  Environment* env = Environment::GetCurrent(isolate);
344
2
  if (env == nullptr) {
345
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
346
    return MaybeLocal<Object>();
347
  }
348
4
  if (Buffer::New(env, length).ToLocal(&obj))
349
2
    return handle_scope.Escape(obj);
350
  return Local<Object>();
351
}
352
353
354
1393
MaybeLocal<Object> New(Environment* env, size_t length) {
355
1393
  Isolate* isolate(env->isolate());
356
1393
  EscapableHandleScope scope(isolate);
357
358
  // V8 currently only allows a maximum Typed Array index of max Smi.
359
1393
  if (length > kMaxLength) {
360
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
361
    return Local<Object>();
362
  }
363
364
  Local<ArrayBuffer> ab;
365
  {
366
2786
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
367
    std::unique_ptr<BackingStore> bs =
368
1393
        ArrayBuffer::NewBackingStore(isolate, length);
369
370
1393
    CHECK(bs);
371
372
1393
    ab = ArrayBuffer::New(isolate, std::move(bs));
373
  }
374
375
  MaybeLocal<Object> obj =
376
1393
      New(env, ab, 0, ab->ByteLength())
377
1393
          .FromMaybe(Local<Uint8Array>());
378
379
1393
  return scope.EscapeMaybe(obj);
380
}
381
382
383
3569
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
384
3569
  EscapableHandleScope handle_scope(isolate);
385
3569
  Environment* env = Environment::GetCurrent(isolate);
386
3569
  if (env == nullptr) {
387
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
388
1
    return MaybeLocal<Object>();
389
  }
390
  Local<Object> obj;
391
7136
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
392
3568
    return handle_scope.Escape(obj);
393
  return Local<Object>();
394
}
395
396
397
6920
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
398
6920
  Isolate* isolate(env->isolate());
399
6920
  EscapableHandleScope scope(isolate);
400
401
  // V8 currently only allows a maximum Typed Array index of max Smi.
402
6920
  if (length > kMaxLength) {
403
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
404
    return Local<Object>();
405
  }
406
407
  Local<ArrayBuffer> ab;
408
  {
409
13840
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
410
    std::unique_ptr<BackingStore> bs =
411
6920
        ArrayBuffer::NewBackingStore(isolate, length);
412
413
6920
    CHECK(bs);
414
415
6920
    memcpy(bs->Data(), data, length);
416
417
6920
    ab = ArrayBuffer::New(isolate, std::move(bs));
418
  }
419
420
  MaybeLocal<Object> obj =
421
6920
      New(env, ab, 0, ab->ByteLength())
422
6920
          .FromMaybe(Local<Uint8Array>());
423
424
6920
  return scope.EscapeMaybe(obj);
425
}
426
427
428
29
MaybeLocal<Object> New(Isolate* isolate,
429
                       char* data,
430
                       size_t length,
431
                       FreeCallback callback,
432
                       void* hint) {
433
29
  EscapableHandleScope handle_scope(isolate);
434
29
  Environment* env = Environment::GetCurrent(isolate);
435
29
  if (env == nullptr) {
436
    callback(data, hint);
437
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
438
    return MaybeLocal<Object>();
439
  }
440
  return handle_scope.EscapeMaybe(
441
58
      Buffer::New(env, data, length, callback, hint));
442
}
443
444
445
951
MaybeLocal<Object> New(Environment* env,
446
                       char* data,
447
                       size_t length,
448
                       FreeCallback callback,
449
                       void* hint) {
450
951
  EscapableHandleScope scope(env->isolate());
451
452
951
  if (length > kMaxLength) {
453
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
454
    callback(data, hint);
455
    return Local<Object>();
456
  }
457
458
  Local<ArrayBuffer> ab =
459
951
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
460
2853
  if (ab->SetPrivate(env->context(),
461
                     env->untransferable_object_private_symbol(),
462
2853
                     True(env->isolate())).IsNothing()) {
463
    return Local<Object>();
464
  }
465
951
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
466
467
  Local<Uint8Array> ui;
468
951
  if (!maybe_ui.ToLocal(&ui))
469
    return MaybeLocal<Object>();
470
471
951
  return scope.Escape(ui);
472
}
473
474
// Warning: This function needs `data` to be allocated with malloc() and not
475
// necessarily isolate's ArrayBuffer::Allocator.
476
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
477
  EscapableHandleScope handle_scope(isolate);
478
  Environment* env = Environment::GetCurrent(isolate);
479
  if (env == nullptr) {
480
    free(data);
481
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
482
    return MaybeLocal<Object>();
483
  }
484
  Local<Object> obj;
485
  if (Buffer::New(env, data, length).ToLocal(&obj))
486
    return handle_scope.Escape(obj);
487
  return Local<Object>();
488
}
489
490
// The contract for this function is that `data` is allocated with malloc()
491
// and not necessarily isolate's ArrayBuffer::Allocator.
492
922
MaybeLocal<Object> New(Environment* env,
493
                       char* data,
494
                       size_t length) {
495
922
  if (length > 0) {
496
921
    CHECK_NOT_NULL(data);
497
921
    CHECK(length <= kMaxLength);
498
  }
499
500
919
  auto free_callback = [](char* data, void* hint) { free(data); };
501
922
  return New(env, data, length, free_callback, nullptr);
502
}
503
504
namespace {
505
506
296
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
507
592
  CHECK(args[0]->IsString());
508
296
  CHECK(args[1]->IsInt32());
509
510
592
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
511
  Local<Object> buf;
512
888
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
513
592
    args.GetReturnValue().Set(buf);
514
296
}
515
516
517
template <encoding encoding>
518
245136
void StringSlice(const FunctionCallbackInfo<Value>& args) {
519
245136
  Environment* env = Environment::GetCurrent(args);
520
245136
  Isolate* isolate = env->isolate();
521
522
245536
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
523
245136
  ArrayBufferViewContents<char> buffer(args.This());
524
525
245136
  if (buffer.length() == 0)
526
772
    return args.GetReturnValue().SetEmptyString();
527
528
244750
  size_t start = 0;
529
244750
  size_t end = 0;
530

979000
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
531

1223750
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
532
244750
  if (end < start) end = start;
533

734250
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
534
244750
  size_t length = end - start;
535
536
  Local<Value> error;
537
  MaybeLocal<Value> maybe_ret =
538
244750
      StringBytes::Encode(isolate,
539
244750
                          buffer.data() + start,
540
                          length,
541
                          encoding,
542
                          &error);
543
  Local<Value> ret;
544
244750
  if (!maybe_ret.ToLocal(&ret)) {
545
14
    CHECK(!error.IsEmpty());
546
14
    isolate->ThrowException(error);
547
14
    return;
548
  }
549
489472
  args.GetReturnValue().Set(ret);
550
}
551
552
553
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
554
13
void Copy(const FunctionCallbackInfo<Value> &args) {
555
13
  Environment* env = Environment::GetCurrent(args);
556
557
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
558
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
559
13
  ArrayBufferViewContents<char> source(args[0]);
560
26
  Local<Object> target_obj = args[1].As<Object>();
561

52
  SPREAD_BUFFER_ARG(target_obj, target);
562
563
13
  size_t target_start = 0;
564
13
  size_t source_start = 0;
565
13
  size_t source_end = 0;
566
567

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
568

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
569

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
570
                                          &source_end));
571
572
  // Copy 0 bytes; we're done
573

13
  if (target_start >= target_length || source_start >= source_end)
574
    return args.GetReturnValue().Set(0);
575
576
13
  if (source_start > source.length())
577
    return THROW_ERR_OUT_OF_RANGE(
578
        env, "The value of \"sourceStart\" is out of range.");
579
580
13
  if (source_end - source_start > target_length - target_start)
581
    source_end = source_start + target_length - target_start;
582
583
13
  uint32_t to_copy = std::min(
584
26
      std::min(source_end - source_start, target_length - target_start),
585
13
      source.length() - source_start);
586
587
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
588
26
  args.GetReturnValue().Set(to_copy);
589
}
590
591
592
177
void Fill(const FunctionCallbackInfo<Value>& args) {
593
177
  Environment* env = Environment::GetCurrent(args);
594
177
  Local<Context> ctx = env->context();
595
596
198
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
597

885
  SPREAD_BUFFER_ARG(args[0], ts_obj);
598
599
177
  size_t start = 0;
600

708
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
601
  size_t end;
602

704
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
603
604
175
  size_t fill_length = end - start;
605
  Local<String> str_obj;
606
  size_t str_length;
607
  enum encoding enc;
608
609
  // OOB Check. Throw the error in JS.
610

175
  if (start > end || fill_length + start > ts_obj_length)
611
    return args.GetReturnValue().Set(-2);
612
613
  // First check if Buffer has been passed.
614
175
  if (Buffer::HasInstance(args[1])) {
615

35
    SPREAD_BUFFER_ARG(args[1], fill_obj);
616
7
    str_length = fill_obj_length;
617
14
    memcpy(
618
7
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
619
7
    goto start_fill;
620
  }
621
622
  // Then coerce everything that's not a string.
623
336
  if (!args[1]->IsString()) {
624
    uint32_t val;
625
6
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
626
3
    int value = val & 255;
627
3
    memset(ts_obj_data + start, value, fill_length);
628
3
    return;
629
  }
630
631
330
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
632
165
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
633
634
  // Can't use StringBytes::Write() in all cases. For example if attempting
635
  // to write a two byte character into a one byte Buffer.
636
165
  if (enc == UTF8) {
637
49
    str_length = str_obj->Utf8Length(env->isolate());
638
49
    node::Utf8Value str(env->isolate(), args[1]);
639
49
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
640
641
116
  } else if (enc == UCS2) {
642
23
    str_length = str_obj->Length() * sizeof(uint16_t);
643
23
    node::TwoByteValue str(env->isolate(), args[1]);
644
23
    if (IsBigEndian())
645
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
646
647
23
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
648
649
  } else {
650
    // Write initial String to Buffer, then use that memory to copy remainder
651
    // of string. Correct the string length for cases like HEX where less than
652
    // the total string length is written.
653
93
    str_length = StringBytes::Write(env->isolate(),
654
93
                                    ts_obj_data + start,
655
                                    fill_length,
656
                                    str_obj,
657
                                    enc,
658
                                    nullptr);
659
  }
660
661
172
start_fill:
662
663
172
  if (str_length >= fill_length)
664
10
    return;
665
666
  // If str_length is zero, then either an empty buffer was provided, or Write()
667
  // indicated that no bytes could be written. If no bytes could be written,
668
  // then return -1 because the fill value is invalid. This will trigger a throw
669
  // in JavaScript. Silently failing should be avoided because it can lead to
670
  // buffers with unexpected contents.
671
162
  if (str_length == 0)
672
12
    return args.GetReturnValue().Set(-1);
673
674
156
  size_t in_there = str_length;
675
156
  char* ptr = ts_obj_data + start + str_length;
676
677
445
  while (in_there < fill_length - in_there) {
678
289
    memcpy(ptr, ts_obj_data + start, in_there);
679
289
    ptr += in_there;
680
289
    in_there *= 2;
681
  }
682
683
156
  if (in_there < fill_length) {
684
156
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
685
  }
686
}
687
688
689
template <encoding encoding>
690
305300
void StringWrite(const FunctionCallbackInfo<Value>& args) {
691
305300
  Environment* env = Environment::GetCurrent(args);
692
693
305310
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
694

1526500
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
695
696
610600
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
697
698
305300
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
699
700
305300
  size_t offset = 0;
701
305300
  size_t max_length = 0;
702
703

1221200
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
704
305300
  if (offset > ts_obj_length) {
705
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
706
        env, "\"offset\" is outside of buffer bounds");
707
  }
708
709


1526500
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
710
                                          &max_length));
711
712
305300
  max_length = std::min(ts_obj_length - offset, max_length);
713
714
305300
  if (max_length == 0)
715
20
    return args.GetReturnValue().Set(0);
716
717
305290
  uint32_t written = StringBytes::Write(env->isolate(),
718
305290
                                        ts_obj_data + offset,
719
                                        max_length,
720
                                        str,
721
                                        encoding,
722
                                        nullptr);
723
610580
  args.GetReturnValue().Set(written);
724
}
725
726
159049
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
727
159049
  Environment* env = Environment::GetCurrent(args);
728
318098
  CHECK(args[0]->IsString());
729
730
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
731
477147
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
732
159049
}
733
734
// Normalize val to be an integer in the range of [1, -1] since
735
// implementations of memcmp() can vary by platform.
736
3561
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
737
3561
  if (val == 0) {
738
3534
    if (a_length > b_length)
739
6
      return 1;
740
3528
    else if (a_length < b_length)
741
5
      return -1;
742
  } else {
743
27
    if (val > 0)
744
7
      return 1;
745
    else
746
20
      return -1;
747
  }
748
3523
  return val;
749
}
750
751
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
752
9
  Environment* env = Environment::GetCurrent(args);
753
754
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
755
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
756
9
  ArrayBufferViewContents<char> source(args[0]);
757
9
  ArrayBufferViewContents<char> target(args[1]);
758
759
9
  size_t target_start = 0;
760
9
  size_t source_start = 0;
761
9
  size_t source_end = 0;
762
9
  size_t target_end = 0;
763
764

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
765

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
766

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
767
                                          &target_end));
768

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
769
                                          &source_end));
770
771
9
  if (source_start > source.length())
772
    return THROW_ERR_OUT_OF_RANGE(
773
        env, "The value of \"sourceStart\" is out of range.");
774
9
  if (target_start > target.length())
775
    return THROW_ERR_OUT_OF_RANGE(
776
        env, "The value of \"targetStart\" is out of range.");
777
778
9
  CHECK_LE(source_start, source_end);
779
9
  CHECK_LE(target_start, target_end);
780
781
  size_t to_cmp =
782
18
      std::min(std::min(source_end - source_start, target_end - target_start),
783
9
               source.length() - source_start);
784
785
18
  int val = normalizeCompareVal(to_cmp > 0 ?
786
9
                                  memcmp(source.data() + source_start,
787
9
                                         target.data() + target_start,
788
                                         to_cmp) : 0,
789
                                source_end - source_start,
790
                                target_end - target_start);
791
792
18
  args.GetReturnValue().Set(val);
793
}
794
795
3552
void Compare(const FunctionCallbackInfo<Value> &args) {
796
3552
  Environment* env = Environment::GetCurrent(args);
797
798
3552
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
799
3552
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
800
3552
  ArrayBufferViewContents<char> a(args[0]);
801
3552
  ArrayBufferViewContents<char> b(args[1]);
802
803
3552
  size_t cmp_length = std::min(a.length(), b.length());
804
805
7040
  int val = normalizeCompareVal(cmp_length > 0 ?
806
3488
                                memcmp(a.data(), b.data(), cmp_length) : 0,
807
                                a.length(), b.length());
808
7104
  args.GetReturnValue().Set(val);
809
}
810
811
812
// Computes the offset for starting an indexOf or lastIndexOf search.
813
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
814
// or -1 to signal that there is no possible match.
815
1169
int64_t IndexOfOffset(size_t length,
816
                      int64_t offset_i64,
817
                      int64_t needle_length,
818
                      bool is_forward) {
819
1169
  int64_t length_i64 = static_cast<int64_t>(length);
820
1169
  if (offset_i64 < 0) {
821
81
    if (offset_i64 + length_i64 >= 0) {
822
      // Negative offsets count backwards from the end of the buffer.
823
63
      return length_i64 + offset_i64;
824

18
    } else if (is_forward || needle_length == 0) {
825
      // indexOf from before the start of the buffer: search the whole buffer.
826
10
      return 0;
827
    } else {
828
      // lastIndexOf from before the start of the buffer: no match.
829
8
      return -1;
830
    }
831
  } else {
832
1088
    if (offset_i64 + needle_length <= length_i64) {
833
      // Valid positive offset.
834
1000
      return offset_i64;
835
88
    } else if (needle_length == 0) {
836
      // Out of buffer bounds, but empty needle: point to end of buffer.
837
10
      return length_i64;
838
78
    } else if (is_forward) {
839
      // indexOf from past the end of the buffer: no match.
840
15
      return -1;
841
    } else {
842
      // lastIndexOf from past the end of the buffer: search the whole buffer.
843
63
      return length_i64 - 1;
844
    }
845
  }
846
}
847
848
899
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
849
899
  Environment* env = Environment::GetCurrent(args);
850
899
  Isolate* isolate = env->isolate();
851
852
1798
  CHECK(args[1]->IsString());
853
899
  CHECK(args[2]->IsNumber());
854
899
  CHECK(args[3]->IsInt32());
855
899
  CHECK(args[4]->IsBoolean());
856
857
1798
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
858
859
932
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
860
899
  ArrayBufferViewContents<char> buffer(args[0]);
861
862
1798
  Local<String> needle = args[1].As<String>();
863
1798
  int64_t offset_i64 = args[2].As<Integer>()->Value();
864
899
  bool is_forward = args[4]->IsTrue();
865
866
899
  const char* haystack = buffer.data();
867
  // Round down to the nearest multiple of 2 in case of UCS2.
868
993
  const size_t haystack_length = (enc == UCS2) ?
869
993
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
870
871
  size_t needle_length;
872
1798
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
873
874
899
  int64_t opt_offset = IndexOfOffset(haystack_length,
875
                                     offset_i64,
876
                                     needle_length,
877
                                     is_forward);
878
879
899
  if (needle_length == 0) {
880
    // Match String#indexOf() and String#lastIndexOf() behavior.
881
8
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
882
8
    return;
883
  }
884
885
891
  if (haystack_length == 0) {
886
    return args.GetReturnValue().Set(-1);
887
  }
888
889
891
  if (opt_offset <= -1) {
890
20
    return args.GetReturnValue().Set(-1);
891
  }
892
881
  size_t offset = static_cast<size_t>(opt_offset);
893
881
  CHECK_LT(offset, haystack_length);
894

881
  if ((is_forward && needle_length + offset > haystack_length) ||
895
879
      needle_length > haystack_length) {
896
30
    return args.GetReturnValue().Set(-1);
897
  }
898
899
866
  size_t result = haystack_length;
900
901
866
  if (enc == UCS2) {
902
89
    String::Value needle_value(isolate, needle);
903
89
    if (*needle_value == nullptr)
904
      return args.GetReturnValue().Set(-1);
905
906

89
    if (haystack_length < 2 || needle_value.length() < 1) {
907
      return args.GetReturnValue().Set(-1);
908
    }
909
910
89
    if (IsBigEndian()) {
911
      StringBytes::InlineDecoder decoder;
912
      if (decoder.Decode(env, needle, enc).IsNothing()) return;
913
      const uint16_t* decoded_string =
914
          reinterpret_cast<const uint16_t*>(decoder.out());
915
916
      if (decoded_string == nullptr)
917
        return args.GetReturnValue().Set(-1);
918
919
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
920
                            haystack_length / 2,
921
                            decoded_string,
922
                            decoder.size() / 2,
923
                            offset / 2,
924
                            is_forward);
925
    } else {
926
89
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
927
                            haystack_length / 2,
928
89
                            reinterpret_cast<const uint16_t*>(*needle_value),
929
89
                            needle_value.length(),
930
                            offset / 2,
931
                            is_forward);
932
    }
933
89
    result *= 2;
934
777
  } else if (enc == UTF8) {
935
765
    String::Utf8Value needle_value(isolate, needle);
936
765
    if (*needle_value == nullptr)
937
      return args.GetReturnValue().Set(-1);
938
939
765
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
940
                          haystack_length,
941
765
                          reinterpret_cast<const uint8_t*>(*needle_value),
942
                          needle_length,
943
                          offset,
944
                          is_forward);
945
12
  } else if (enc == LATIN1) {
946
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
947
12
    if (needle_data == nullptr) {
948
      return args.GetReturnValue().Set(-1);
949
    }
950
12
    needle->WriteOneByte(
951
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
952
953
12
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
954
                          haystack_length,
955
                          needle_data,
956
                          needle_length,
957
                          offset,
958
                          is_forward);
959
12
    free(needle_data);
960
  }
961
962
1732
  args.GetReturnValue().Set(
963
866
      result == haystack_length ? -1 : static_cast<int>(result));
964
}
965
966
220
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
967
220
  CHECK(args[1]->IsObject());
968
220
  CHECK(args[2]->IsNumber());
969
220
  CHECK(args[3]->IsInt32());
970
220
  CHECK(args[4]->IsBoolean());
971
972
440
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
973
974
250
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
975
220
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
976
220
  ArrayBufferViewContents<char> haystack_contents(args[0]);
977
220
  ArrayBufferViewContents<char> needle_contents(args[1]);
978
440
  int64_t offset_i64 = args[2].As<Integer>()->Value();
979
220
  bool is_forward = args[4]->IsTrue();
980
981
220
  const char* haystack = haystack_contents.data();
982
220
  const size_t haystack_length = haystack_contents.length();
983
220
  const char* needle = needle_contents.data();
984
220
  const size_t needle_length = needle_contents.length();
985
986
220
  int64_t opt_offset = IndexOfOffset(haystack_length,
987
                                     offset_i64,
988
                                     needle_length,
989
                                     is_forward);
990
991
220
  if (needle_length == 0) {
992
    // Match String#indexOf() and String#lastIndexOf() behavior.
993
12
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
994
12
    return;
995
  }
996
997
208
  if (haystack_length == 0) {
998
    return args.GetReturnValue().Set(-1);
999
  }
1000
1001
208
  if (opt_offset <= -1) {
1002
18
    return args.GetReturnValue().Set(-1);
1003
  }
1004
199
  size_t offset = static_cast<size_t>(opt_offset);
1005
199
  CHECK_LT(offset, haystack_length);
1006

199
  if ((is_forward && needle_length + offset > haystack_length) ||
1007
197
      needle_length > haystack_length) {
1008
14
    return args.GetReturnValue().Set(-1);
1009
  }
1010
1011
192
  size_t result = haystack_length;
1012
1013
192
  if (enc == UCS2) {
1014

59
    if (haystack_length < 2 || needle_length < 2) {
1015
4
      return args.GetReturnValue().Set(-1);
1016
    }
1017
57
    result = SearchString(
1018
        reinterpret_cast<const uint16_t*>(haystack),
1019
        haystack_length / 2,
1020
        reinterpret_cast<const uint16_t*>(needle),
1021
        needle_length / 2,
1022
        offset / 2,
1023
        is_forward);
1024
57
    result *= 2;
1025
  } else {
1026
133
    result = SearchString(
1027
        reinterpret_cast<const uint8_t*>(haystack),
1028
        haystack_length,
1029
        reinterpret_cast<const uint8_t*>(needle),
1030
        needle_length,
1031
        offset,
1032
        is_forward);
1033
  }
1034
1035
380
  args.GetReturnValue().Set(
1036
190
      result == haystack_length ? -1 : static_cast<int>(result));
1037
}
1038
1039
50
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1040
50
  CHECK(args[1]->IsUint32());
1041
50
  CHECK(args[2]->IsNumber());
1042
50
  CHECK(args[3]->IsBoolean());
1043
1044
54
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1045
50
  ArrayBufferViewContents<char> buffer(args[0]);
1046
1047
100
  uint32_t needle = args[1].As<Uint32>()->Value();
1048
100
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1049
50
  bool is_forward = args[3]->IsTrue();
1050
1051
  int64_t opt_offset =
1052
50
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1053

50
  if (opt_offset <= -1 || buffer.length() == 0) {
1054
8
    return args.GetReturnValue().Set(-1);
1055
  }
1056
46
  size_t offset = static_cast<size_t>(opt_offset);
1057
46
  CHECK_LT(offset, buffer.length());
1058
1059
  const void* ptr;
1060
46
  if (is_forward) {
1061
38
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1062
  } else {
1063
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1064
  }
1065
46
  const char* ptr_char = static_cast<const char*>(ptr);
1066
92
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1067
                                : -1);
1068
}
1069
1070
1071
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1072
2
  Environment* env = Environment::GetCurrent(args);
1073
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1074

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1075
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1076
4
  args.GetReturnValue().Set(args[0]);
1077
}
1078
1079
1080
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1081
2
  Environment* env = Environment::GetCurrent(args);
1082
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1083

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1084
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1085
4
  args.GetReturnValue().Set(args[0]);
1086
}
1087
1088
1089
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1090
2
  Environment* env = Environment::GetCurrent(args);
1091
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1092

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1093
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1094
4
  args.GetReturnValue().Set(args[0]);
1095
}
1096
1097
1098
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1099
// Used in TextEncoder.prototype.encode.
1100
277
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1101
277
  Environment* env = Environment::GetCurrent(args);
1102
277
  Isolate* isolate = env->isolate();
1103
277
  CHECK_GE(args.Length(), 1);
1104
554
  CHECK(args[0]->IsString());
1105
1106
554
  Local<String> str = args[0].As<String>();
1107
277
  size_t length = str->Utf8Length(isolate);
1108
1109
  Local<ArrayBuffer> ab;
1110
  {
1111
554
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1112
    std::unique_ptr<BackingStore> bs =
1113
277
        ArrayBuffer::NewBackingStore(isolate, length);
1114
1115
277
    CHECK(bs);
1116
1117
277
    str->WriteUtf8(isolate,
1118
277
                   static_cast<char*>(bs->Data()),
1119
                   -1,  // We are certain that `data` is sufficiently large
1120
                   nullptr,
1121
                   String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1122
1123
277
    ab = ArrayBuffer::New(isolate, std::move(bs));
1124
  }
1125
1126
277
  auto array = Uint8Array::New(ab, 0, length);
1127
277
  args.GetReturnValue().Set(array);
1128
277
}
1129
1130
1131
87
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1132
87
  Environment* env = Environment::GetCurrent(args);
1133
87
  Isolate* isolate = env->isolate();
1134
87
  CHECK_GE(args.Length(), 3);
1135
174
  CHECK(args[0]->IsString());
1136
87
  CHECK(args[1]->IsUint8Array());
1137
87
  CHECK(args[2]->IsUint32Array());
1138
1139
174
  Local<String> source = args[0].As<String>();
1140
1141
174
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1142
87
  Local<ArrayBuffer> buf = dest->Buffer();
1143
  char* write_result =
1144
174
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1145
87
  size_t dest_length = dest->ByteLength();
1146
1147
  // results = [ read, written ]
1148
174
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1149
  uint32_t* results = reinterpret_cast<uint32_t*>(
1150
261
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1151
87
      result_arr->ByteOffset());
1152
1153
  int nchars;
1154
87
  int written = source->WriteUtf8(
1155
      isolate,
1156
      write_result,
1157
      dest_length,
1158
      &nchars,
1159
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1160
87
  results[0] = nchars;
1161
87
  results[1] = written;
1162
87
}
1163
1164
1165
617
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1166
617
  Environment* env = Environment::GetCurrent(args);
1167
1168
617
  CHECK(args[0]->IsObject());
1169
617
  Local<Object> proto = args[0].As<Object>();
1170
617
  env->set_buffer_prototype_object(proto);
1171
617
}
1172
1173
5487
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1174
5487
  Environment* env = Environment::GetCurrent(args);
1175
5487
  NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator();
1176
  Local<ArrayBuffer> ab;
1177
  // It can be a nullptr when running inside an isolate where we
1178
  // do not own the ArrayBuffer allocator.
1179
5487
  if (allocator == nullptr) {
1180
    // Create a dummy Uint32Array - the JS land can only toggle the C++ land
1181
    // setting when the allocator uses our toggle. With this the toggle in JS
1182
    // land results in no-ops.
1183
62
    ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1184
  } else {
1185
5425
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1186
    std::unique_ptr<BackingStore> backing =
1187
        ArrayBuffer::NewBackingStore(zero_fill_field,
1188
                                     sizeof(*zero_fill_field),
1189
4941
                                     [](void*, size_t, void*) {},
1190
5425
                                     nullptr);
1191
5425
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1192
  }
1193
1194
10974
  ab->SetPrivate(
1195
      env->context(),
1196
      env->untransferable_object_private_symbol(),
1197
16461
      True(env->isolate())).Check();
1198
1199
5487
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1200
5487
}
1201
1202
670
void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1203
670
  Environment* env = Environment::GetCurrent(args);
1204
670
  if (args[0]->IsArrayBuffer()) {
1205
1340
    Local<ArrayBuffer> buf = args[0].As<ArrayBuffer>();
1206
670
    if (buf->IsDetachable()) {
1207
667
      std::shared_ptr<BackingStore> store = buf->GetBackingStore();
1208
667
      buf->Detach();
1209
1334
      args.GetReturnValue().Set(ArrayBuffer::New(env->isolate(), store));
1210
    }
1211
  }
1212
670
}
1213
1214
171
void CopyArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1215
  // args[0] == Destination ArrayBuffer
1216
  // args[1] == Destination ArrayBuffer Offset
1217
  // args[2] == Source ArrayBuffer
1218
  // args[3] == Source ArrayBuffer Offset
1219
  // args[4] == bytesToCopy
1220
1221

171
  CHECK(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer());
1222
171
  CHECK(args[1]->IsUint32());
1223

171
  CHECK(args[2]->IsArrayBuffer() || args[2]->IsSharedArrayBuffer());
1224
171
  CHECK(args[3]->IsUint32());
1225
171
  CHECK(args[4]->IsUint32());
1226
1227
171
  std::shared_ptr<BackingStore> destination;
1228
171
  std::shared_ptr<BackingStore> source;
1229
1230
171
  if (args[0]->IsArrayBuffer()) {
1231
342
    destination = args[0].As<ArrayBuffer>()->GetBackingStore();
1232
  } else if (args[0]->IsSharedArrayBuffer()) {
1233
    destination = args[0].As<SharedArrayBuffer>()->GetBackingStore();
1234
  }
1235
1236
171
  if (args[2]->IsArrayBuffer()) {
1237
342
    source = args[2].As<ArrayBuffer>()->GetBackingStore();
1238
  } else if (args[0]->IsSharedArrayBuffer()) {
1239
    source = args[2].As<SharedArrayBuffer>()->GetBackingStore();
1240
  }
1241
1242
342
  uint32_t destination_offset = args[1].As<Uint32>()->Value();
1243
342
  uint32_t source_offset = args[3].As<Uint32>()->Value();
1244
342
  size_t bytes_to_copy = args[4].As<Uint32>()->Value();
1245
1246
171
  CHECK_GE(destination->ByteLength() - destination_offset, bytes_to_copy);
1247
171
  CHECK_GE(source->ByteLength() - source_offset, bytes_to_copy);
1248
1249
  uint8_t* dest =
1250
171
      static_cast<uint8_t*>(destination->Data()) + destination_offset;
1251
  uint8_t* src =
1252
171
      static_cast<uint8_t*>(source->Data()) + source_offset;
1253
171
  memcpy(dest, src, bytes_to_copy);
1254
171
}
1255
1256
617
void Initialize(Local<Object> target,
1257
                Local<Value> unused,
1258
                Local<Context> context,
1259
                void* priv) {
1260
617
  Environment* env = Environment::GetCurrent(context);
1261
1262
617
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1263
617
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1264
1265
617
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1266
617
  env->SetMethod(target, "copy", Copy);
1267
617
  env->SetMethodNoSideEffect(target, "compare", Compare);
1268
617
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1269
617
  env->SetMethod(target, "fill", Fill);
1270
617
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1271
617
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1272
617
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1273
1274
617
  env->SetMethod(target, "detachArrayBuffer", DetachArrayBuffer);
1275
617
  env->SetMethod(target, "copyArrayBuffer", CopyArrayBuffer);
1276
1277
617
  env->SetMethod(target, "swap16", Swap16);
1278
617
  env->SetMethod(target, "swap32", Swap32);
1279
617
  env->SetMethod(target, "swap64", Swap64);
1280
1281
617
  env->SetMethod(target, "encodeInto", EncodeInto);
1282
617
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1283
1284
617
  target->Set(env->context(),
1285
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1286
2468
              Number::New(env->isolate(), kMaxLength)).Check();
1287
1288
617
  target->Set(env->context(),
1289
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1290
1851
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1291
1292
617
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1293
617
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1294
617
  env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>);
1295
617
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1296
617
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1297
617
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1298
617
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1299
1300
617
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1301
617
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1302
617
  env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>);
1303
617
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1304
617
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1305
617
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1306
617
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1307
1308
617
  env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle);
1309
617
}
1310
1311
}  // anonymous namespace
1312
1313
4853
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1314
4853
  registry->Register(SetBufferPrototype);
1315
4853
  registry->Register(CreateFromString);
1316
1317
4853
  registry->Register(ByteLengthUtf8);
1318
4853
  registry->Register(Copy);
1319
4853
  registry->Register(Compare);
1320
4853
  registry->Register(CompareOffset);
1321
4853
  registry->Register(Fill);
1322
4853
  registry->Register(IndexOfBuffer);
1323
4853
  registry->Register(IndexOfNumber);
1324
4853
  registry->Register(IndexOfString);
1325
1326
4853
  registry->Register(Swap16);
1327
4853
  registry->Register(Swap32);
1328
4853
  registry->Register(Swap64);
1329
1330
4853
  registry->Register(EncodeInto);
1331
4853
  registry->Register(EncodeUtf8String);
1332
1333
4853
  registry->Register(StringSlice<ASCII>);
1334
4853
  registry->Register(StringSlice<BASE64>);
1335
4853
  registry->Register(StringSlice<BASE64URL>);
1336
4853
  registry->Register(StringSlice<LATIN1>);
1337
4853
  registry->Register(StringSlice<HEX>);
1338
4853
  registry->Register(StringSlice<UCS2>);
1339
4853
  registry->Register(StringSlice<UTF8>);
1340
1341
4853
  registry->Register(StringWrite<ASCII>);
1342
4853
  registry->Register(StringWrite<BASE64>);
1343
4853
  registry->Register(StringWrite<BASE64URL>);
1344
4853
  registry->Register(StringWrite<LATIN1>);
1345
4853
  registry->Register(StringWrite<HEX>);
1346
4853
  registry->Register(StringWrite<UCS2>);
1347
4853
  registry->Register(StringWrite<UTF8>);
1348
4853
  registry->Register(GetZeroFillToggle);
1349
1350
4853
  registry->Register(DetachArrayBuffer);
1351
4853
  registry->Register(CopyArrayBuffer);
1352
4853
}
1353
1354
}  // namespace Buffer
1355
}  // namespace node
1356
1357
4926
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1358
4853
NODE_MODULE_EXTERNAL_REFERENCE(buffer, node::Buffer::RegisterExternalReferences)