GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 620 690 89.9 %
Date: 2022-03-16 03:14:48 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
    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
1366
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
110
    Environment* env,
111
    char* data,
112
    size_t length,
113
    FreeCallback callback,
114
    void* hint) {
115
1366
  CHECK_NOT_NULL(callback);
116

1366
  CHECK_IMPLIES(data == nullptr, length == 0);
117
118
1366
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
119
  std::unique_ptr<BackingStore> bs =
120
1362
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
121
1362
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
122
1366
      }, self);
123
1366
  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
1366
  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
1363
    self->persistent_.Reset(env->isolate(), ab);
133
1363
    self->persistent_.SetWeak();
134
  }
135
136
1366
  return ab;
137
}
138
139
140
1366
CallbackInfo::CallbackInfo(Environment* env,
141
                           FreeCallback callback,
142
                           char* data,
143
1366
                           void* hint)
144
    : callback_(callback),
145
      data_(data),
146
      hint_(hint),
147
2732
      env_(env) {
148
1366
  env->AddCleanupHook(CleanupHook, this);
149
1366
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
150
1366
}
151
152
508
void CallbackInfo::CleanupHook(void* data) {
153
508
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
154
155
  {
156
1016
    HandleScope handle_scope(self->env_->isolate());
157
1016
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
158

1016
    if (!ab.IsEmpty() && ab->IsDetachable()) {
159
508
      ab->Detach();
160
508
      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
508
  self->CallAndResetCallback();
167
508
}
168
169
1873
void CallbackInfo::CallAndResetCallback() {
170
  FreeCallback callback;
171
  {
172
1873
    Mutex::ScopedLock lock(mutex_);
173
1873
    callback = callback_;
174
1873
    callback_ = nullptr;
175
  }
176
1873
  if (callback != nullptr) {
177
    // Clean up all Environment-related state and run the callback.
178
1365
    env_->RemoveCleanupHook(CleanupHook, this);
179
1365
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
180
1365
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
181
182
1365
    callback(data_, hint_);
183
  }
184
1873
}
185
186
1365
void CallbackInfo::OnBackingStoreFree() {
187
  // This method should always release the memory for `this`.
188
1365
  std::unique_ptr<CallbackInfo> self { this };
189
1365
  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
1365
  if (callback_ == nullptr) return;
195
196
1365
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
197
1365
    CHECK_EQ(self->env_, env);  // Consistency check.
198
199
1365
    self->CallAndResetCallback();
200
1365
  });
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
561736
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
207
                                                   Local<Value> arg,
208
                                                   size_t def,
209
                                                   size_t* ret) {
210
1123472
  if (arg->IsUndefined()) {
211
    *ret = def;
212
    return Just(true);
213
  }
214
215
  int64_t tmp_i;
216
1123472
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
217
    return Nothing<bool>();
218
219
561736
  if (tmp_i < 0)
220
2
    return Just(false);
221
222
  // Check that the result fits in a size_t.
223
  // coverity[pointless_expression]
224
561734
  if (static_cast<uint64_t>(tmp_i) > std::numeric_limits<size_t>::max())
225
    return Just(false);
226
227
561734
  *ret = static_cast<size_t>(tmp_i);
228
561734
  return Just(true);
229
}
230
231
}  // anonymous namespace
232
233
// Buffer methods
234
235
3551241
bool HasInstance(Local<Value> val) {
236
3551241
  return val->IsArrayBufferView();
237
}
238
239
240
280847
bool HasInstance(Local<Object> obj) {
241
280847
  return obj->IsArrayBufferView();
242
}
243
244
245
278131
char* Data(Local<Value> val) {
246
278131
  CHECK(val->IsArrayBufferView());
247
278131
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
248
834393
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
249
278131
      ui->ByteOffset();
250
}
251
252
253
146371
char* Data(Local<Object> obj) {
254
146371
  return Data(obj.As<Value>());
255
}
256
257
258
104584
size_t Length(Local<Value> val) {
259
104584
  CHECK(val->IsArrayBufferView());
260
104584
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
261
104584
  return ui->ByteLength();
262
}
263
264
265
144918
size_t Length(Local<Object> obj) {
266
144918
  CHECK(obj->IsArrayBufferView());
267
144918
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
268
144918
  return ui->ByteLength();
269
}
270
271
272
14136
MaybeLocal<Uint8Array> New(Environment* env,
273
                           Local<ArrayBuffer> ab,
274
                           size_t byte_offset,
275
                           size_t length) {
276
28272
  CHECK(!env->buffer_prototype_object().IsEmpty());
277
14136
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
278
  Maybe<bool> mb =
279
28272
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
280
14136
  if (mb.IsNothing())
281
    return MaybeLocal<Uint8Array>();
282
14136
  return ui;
283
}
284
285
330
MaybeLocal<Uint8Array> New(Isolate* isolate,
286
                           Local<ArrayBuffer> ab,
287
                           size_t byte_offset,
288
                           size_t length) {
289
330
  Environment* env = Environment::GetCurrent(isolate);
290
330
  if (env == nullptr) {
291
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
292
    return MaybeLocal<Uint8Array>();
293
  }
294
330
  return New(env, ab, byte_offset, length);
295
}
296
297
298
331
MaybeLocal<Object> New(Isolate* isolate,
299
                       Local<String> string,
300
                       enum encoding enc) {
301
331
  EscapableHandleScope scope(isolate);
302
303
  size_t length;
304
662
  if (!StringBytes::Size(isolate, string, enc).To(&length))
305
    return Local<Object>();
306
331
  size_t actual = 0;
307
331
  std::unique_ptr<BackingStore> store;
308
309
331
  if (length > 0) {
310
331
    store = ArrayBuffer::NewBackingStore(isolate, length);
311
312
331
    if (UNLIKELY(!store)) {
313
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
314
      return Local<Object>();
315
    }
316
317
331
    actual = StringBytes::Write(
318
        isolate,
319
331
        static_cast<char*>(store->Data()),
320
        length,
321
        string,
322
        enc);
323
331
    CHECK(actual <= length);
324
325
331
    if (LIKELY(actual > 0)) {
326
330
      if (actual < length)
327
        store = BackingStore::Reallocate(isolate, std::move(store), actual);
328
330
      Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
329
      Local<Object> obj;
330
660
      if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
331
        return MaybeLocal<Object>();
332
330
      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
1433
MaybeLocal<Object> New(Environment* env, size_t length) {
355
1433
  Isolate* isolate(env->isolate());
356
1433
  EscapableHandleScope scope(isolate);
357
358
  // V8 currently only allows a maximum Typed Array index of max Smi.
359
1433
  if (length > kMaxLength) {
360
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
361
    return Local<Object>();
362
  }
363
364
  Local<ArrayBuffer> ab;
365
  {
366
2866
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
367
    std::unique_ptr<BackingStore> bs =
368
1433
        ArrayBuffer::NewBackingStore(isolate, length);
369
370
1433
    CHECK(bs);
371
372
1433
    ab = ArrayBuffer::New(isolate, std::move(bs));
373
  }
374
375
  MaybeLocal<Object> obj =
376
1433
      New(env, ab, 0, ab->ByteLength())
377
1433
          .FromMaybe(Local<Uint8Array>());
378
379
1433
  return scope.EscapeMaybe(obj);
380
}
381
382
383
3717
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
384
3717
  EscapableHandleScope handle_scope(isolate);
385
3717
  Environment* env = Environment::GetCurrent(isolate);
386
3717
  if (env == nullptr) {
387
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
388
1
    return MaybeLocal<Object>();
389
  }
390
  Local<Object> obj;
391
7432
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
392
3716
    return handle_scope.Escape(obj);
393
  return Local<Object>();
394
}
395
396
397
7137
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
398
7137
  Isolate* isolate(env->isolate());
399
7137
  EscapableHandleScope scope(isolate);
400
401
  // V8 currently only allows a maximum Typed Array index of max Smi.
402
7137
  if (length > kMaxLength) {
403
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
404
    return Local<Object>();
405
  }
406
407
  Local<ArrayBuffer> ab;
408
  {
409
14274
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
410
    std::unique_ptr<BackingStore> bs =
411
7137
        ArrayBuffer::NewBackingStore(isolate, length);
412
413
7137
    CHECK(bs);
414
415
7137
    memcpy(bs->Data(), data, length);
416
417
7137
    ab = ArrayBuffer::New(isolate, std::move(bs));
418
  }
419
420
  MaybeLocal<Object> obj =
421
7137
      New(env, ab, 0, ab->ByteLength())
422
7137
          .FromMaybe(Local<Uint8Array>());
423
424
7137
  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
1366
MaybeLocal<Object> New(Environment* env,
446
                       char* data,
447
                       size_t length,
448
                       FreeCallback callback,
449
                       void* hint) {
450
1366
  EscapableHandleScope scope(env->isolate());
451
452
1366
  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
1366
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
460
4098
  if (ab->SetPrivate(env->context(),
461
                     env->untransferable_object_private_symbol(),
462
4098
                     True(env->isolate())).IsNothing()) {
463
    return Local<Object>();
464
  }
465
1366
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
466
467
  Local<Uint8Array> ui;
468
1366
  if (!maybe_ui.ToLocal(&ui))
469
    return MaybeLocal<Object>();
470
471
1366
  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
1337
MaybeLocal<Object> New(Environment* env,
493
                       char* data,
494
                       size_t length) {
495
1337
  if (length > 0) {
496
1336
    CHECK_NOT_NULL(data);
497
    // V8 currently only allows a maximum Typed Array index of max Smi.
498
1336
    if (length > kMaxLength) {
499
      Isolate* isolate(env->isolate());
500
      isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
501
      return Local<Object>();
502
    }
503
  }
504
505
1336
  auto free_callback = [](char* data, void* hint) { free(data); };
506
1337
  return New(env, data, length, free_callback, nullptr);
507
}
508
509
namespace {
510
511
331
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
512
662
  CHECK(args[0]->IsString());
513
331
  CHECK(args[1]->IsInt32());
514
515
662
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
516
  Local<Object> buf;
517
993
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
518
662
    args.GetReturnValue().Set(buf);
519
331
}
520
521
522
template <encoding encoding>
523
255522
void StringSlice(const FunctionCallbackInfo<Value>& args) {
524
255522
  Environment* env = Environment::GetCurrent(args);
525
255522
  Isolate* isolate = env->isolate();
526
527
255922
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
528
255522
  ArrayBufferViewContents<char> buffer(args.This());
529
530
255522
  if (buffer.length() == 0)
531
772
    return args.GetReturnValue().SetEmptyString();
532
533
255136
  size_t start = 0;
534
255136
  size_t end = 0;
535

765408
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
536

1020544
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
537
255136
  if (end < start) end = start;
538

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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