GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 620 689 90.0 %
Date: 2022-02-22 04:15:11 Branches: 307 520 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
    Maybe<bool> m = (r);                                                    \
45
    if (m.IsNothing()) return;                                              \
46
    if (!m.FromJust())                                                      \
47
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
48
  } while (0)                                                               \
49
50
namespace node {
51
namespace Buffer {
52
53
using v8::ArrayBuffer;
54
using v8::ArrayBufferView;
55
using v8::BackingStore;
56
using v8::Context;
57
using v8::EscapableHandleScope;
58
using v8::FunctionCallbackInfo;
59
using v8::Global;
60
using v8::HandleScope;
61
using v8::Int32;
62
using v8::Integer;
63
using v8::Isolate;
64
using v8::Just;
65
using v8::Local;
66
using v8::Maybe;
67
using v8::MaybeLocal;
68
using v8::Nothing;
69
using v8::Number;
70
using v8::Object;
71
using v8::SharedArrayBuffer;
72
using v8::String;
73
using v8::Uint32;
74
using v8::Uint32Array;
75
using v8::Uint8Array;
76
using v8::Value;
77
78
namespace {
79
80
class CallbackInfo {
81
 public:
82
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
83
      Environment* env,
84
      char* data,
85
      size_t length,
86
      FreeCallback callback,
87
      void* hint);
88
89
  CallbackInfo(const CallbackInfo&) = delete;
90
  CallbackInfo& operator=(const CallbackInfo&) = delete;
91
92
 private:
93
  static void CleanupHook(void* data);
94
  inline void OnBackingStoreFree();
95
  inline void CallAndResetCallback();
96
  inline CallbackInfo(Environment* env,
97
                      FreeCallback callback,
98
                      char* data,
99
                      void* hint);
100
  Global<ArrayBuffer> persistent_;
101
  Mutex mutex_;  // Protects callback_.
102
  FreeCallback callback_;
103
  char* const data_;
104
  void* const hint_;
105
  Environment* const env_;
106
};
107
108
109
1542
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
110
    Environment* env,
111
    char* data,
112
    size_t length,
113
    FreeCallback callback,
114
    void* hint) {
115
1542
  CHECK_NOT_NULL(callback);
116

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

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

787878
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
537

1050504
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
538
262626
  if (end < start) end = start;
539

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

52
  SPREAD_BUFFER_ARG(target_obj, target);
568
569
13
  size_t target_start = 0;
570
13
  size_t source_start = 0;
571
13
  size_t source_end = 0;
572
573

39
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
574

39
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
575

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
576
                                          &source_end));
577
578
  // Copy 0 bytes; we're done
579

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

885
  SPREAD_BUFFER_ARG(args[0], ts_obj);
604
605
177
  size_t start = 0;
606

531
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
607
  size_t end;
608

528
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
609
610
175
  size_t fill_length = end - start;
611
  Local<String> str_obj;
612
  size_t str_length;
613
  enum encoding enc;
614
615
  // OOB Check. Throw the error in JS.
616

175
  if (start > end || fill_length + start > ts_obj_length)
617
    return args.GetReturnValue().Set(-2);
618
619
  // First check if Buffer has been passed.
620
175
  if (Buffer::HasInstance(args[1])) {
621

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

1531660
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
701
702
612664
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
703
704
306332
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
705
706
306332
  size_t offset = 0;
707
306332
  size_t max_length = 0;
708
709

918996
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
710
306332
  if (offset > ts_obj_length) {
711
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
712
        env, "\"offset\" is outside of buffer bounds");
713
  }
714
715

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

27
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
771

27
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
772

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
773
                                          &target_end));
774

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

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

881
  if ((is_forward && needle_length + offset > haystack_length) ||
901
879
      needle_length > haystack_length) {
902
30
    return args.GetReturnValue().Set(-1);
903
  }
904
905
866
  size_t result = haystack_length;
906
907
866
  if (enc == UCS2) {
908
89
    String::Value needle_value(isolate, needle);
909
89
    if (*needle_value == nullptr)
910
      return args.GetReturnValue().Set(-1);
911
912

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

199
  if ((is_forward && needle_length + offset > haystack_length) ||
1013
197
      needle_length > haystack_length) {
1014
14
    return args.GetReturnValue().Set(-1);
1015
  }
1016
1017
192
  size_t result = haystack_length;
1018
1019
192
  if (enc == UCS2) {
1020

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

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

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

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1090
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1091
4
  args.GetReturnValue().Set(args[0]);
1092
}
1093
1094
1095
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1096
2
  Environment* env = Environment::GetCurrent(args);
1097
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1098

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

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

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