GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 626 696 89.9 %
Date: 2022-06-09 04:15:39 Branches: 309 524 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 "node.h"
24
#include "node_blob.h"
25
#include "node_errors.h"
26
#include "node_external_reference.h"
27
#include "node_internals.h"
28
29
#include "env-inl.h"
30
#include "string_bytes.h"
31
#include "string_search.h"
32
#include "util-inl.h"
33
#include "v8.h"
34
35
#include <cstring>
36
#include <climits>
37
38
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
39
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
40
41
#define THROW_AND_RETURN_IF_OOB(r)                                          \
42
  do {                                                                      \
43
    Maybe<bool> m = (r);                                                    \
44
    if (m.IsNothing()) return;                                              \
45
    if (!m.FromJust())                                                      \
46
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
47
  } while (0)                                                               \
48
49
namespace node {
50
namespace Buffer {
51
52
using v8::ArrayBuffer;
53
using v8::ArrayBufferView;
54
using v8::BackingStore;
55
using v8::Context;
56
using v8::EscapableHandleScope;
57
using v8::FunctionCallbackInfo;
58
using v8::Global;
59
using v8::HandleScope;
60
using v8::Int32;
61
using v8::Integer;
62
using v8::Isolate;
63
using v8::Just;
64
using v8::Local;
65
using v8::Maybe;
66
using v8::MaybeLocal;
67
using v8::Nothing;
68
using v8::Number;
69
using v8::Object;
70
using v8::SharedArrayBuffer;
71
using v8::String;
72
using v8::Uint32;
73
using v8::Uint32Array;
74
using v8::Uint8Array;
75
using v8::Value;
76
77
namespace {
78
79
class CallbackInfo {
80
 public:
81
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
82
      Environment* env,
83
      char* data,
84
      size_t length,
85
      FreeCallback callback,
86
      void* hint);
87
88
  CallbackInfo(const CallbackInfo&) = delete;
89
  CallbackInfo& operator=(const CallbackInfo&) = delete;
90
91
 private:
92
  static void CleanupHook(void* data);
93
  inline void OnBackingStoreFree();
94
  inline void CallAndResetCallback();
95
  inline CallbackInfo(Environment* env,
96
                      FreeCallback callback,
97
                      char* data,
98
                      void* hint);
99
  Global<ArrayBuffer> persistent_;
100
  Mutex mutex_;  // Protects callback_.
101
  FreeCallback callback_;
102
  char* const data_;
103
  void* const hint_;
104
  Environment* const env_;
105
};
106
107
108
30
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
109
    Environment* env,
110
    char* data,
111
    size_t length,
112
    FreeCallback callback,
113
    void* hint) {
114
30
  CHECK_NOT_NULL(callback);
115

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

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

821406
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
547

1095208
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
548
273802
  if (end < start) end = start;
549

547604
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
550
273802
  size_t length = end - start;
551
552
  Local<Value> error;
553
  MaybeLocal<Value> maybe_ret =
554
273802
      StringBytes::Encode(isolate,
555
273802
                          buffer.data() + start,
556
                          length,
557
                          encoding,
558
                          &error);
559
  Local<Value> ret;
560
273802
  if (!maybe_ret.ToLocal(&ret)) {
561
14
    CHECK(!error.IsEmpty());
562
14
    isolate->ThrowException(error);
563
14
    return;
564
  }
565
547576
  args.GetReturnValue().Set(ret);
566
}
567
568
569
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
570
13
void Copy(const FunctionCallbackInfo<Value> &args) {
571
13
  Environment* env = Environment::GetCurrent(args);
572
573
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
574
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
575
13
  ArrayBufferViewContents<char> source(args[0]);
576
26
  Local<Object> target_obj = args[1].As<Object>();
577

52
  SPREAD_BUFFER_ARG(target_obj, target);
578
579
13
  size_t target_start = 0;
580
13
  size_t source_start = 0;
581
13
  size_t source_end = 0;
582
583

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

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

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
586
                                          &source_end));
587
588
  // Copy 0 bytes; we're done
589

13
  if (target_start >= target_length || source_start >= source_end)
590
    return args.GetReturnValue().Set(0);
591
592
13
  if (source_start > source.length())
593
    return THROW_ERR_OUT_OF_RANGE(
594
        env, "The value of \"sourceStart\" is out of range.");
595
596
13
  if (source_end - source_start > target_length - target_start)
597
    source_end = source_start + target_length - target_start;
598
599
13
  uint32_t to_copy = std::min(
600
26
      std::min(source_end - source_start, target_length - target_start),
601
13
      source.length() - source_start);
602
603
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
604
26
  args.GetReturnValue().Set(to_copy);
605
}
606
607
608
177
void Fill(const FunctionCallbackInfo<Value>& args) {
609
177
  Environment* env = Environment::GetCurrent(args);
610
177
  Local<Context> ctx = env->context();
611
612
198
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
613

885
  SPREAD_BUFFER_ARG(args[0], ts_obj);
614
615
177
  size_t start = 0;
616

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

528
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
619
620
175
  size_t fill_length = end - start;
621
  Local<String> str_obj;
622
  size_t str_length;
623
  enum encoding enc;
624
625
  // OOB Check. Throw the error in JS.
626

175
  if (start > end || fill_length + start > ts_obj_length)
627
    return args.GetReturnValue().Set(-2);
628
629
  // First check if Buffer has been passed.
630
175
  if (Buffer::HasInstance(args[1])) {
631

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

1552330
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
711
712
620932
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
713
714
310466
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
715
716
310466
  size_t offset = 0;
717
310466
  size_t max_length = 0;
718
719

931398
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
720
310466
  if (offset > ts_obj_length) {
721
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
722
        env, "\"offset\" is outside of buffer bounds");
723
  }
724
725

1241864
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
726
                                          &max_length));
727
728
310466
  max_length = std::min(ts_obj_length - offset, max_length);
729
730
310466
  if (max_length == 0)
731
24
    return args.GetReturnValue().Set(0);
732
733
310454
  uint32_t written = StringBytes::Write(env->isolate(),
734
310454
                                        ts_obj_data + offset,
735
                                        max_length,
736
                                        str,
737
                                        encoding,
738
                                        nullptr);
739
620908
  args.GetReturnValue().Set(written);
740
}
741
742
161280
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
743
161280
  Environment* env = Environment::GetCurrent(args);
744
322560
  CHECK(args[0]->IsString());
745
746
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
747
483840
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
748
161280
}
749
750
// Normalize val to be an integer in the range of [1, -1] since
751
// implementations of memcmp() can vary by platform.
752
3531
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
753
3531
  if (val == 0) {
754
3504
    if (a_length > b_length)
755
6
      return 1;
756
3498
    else if (a_length < b_length)
757
5
      return -1;
758
  } else {
759
27
    if (val > 0)
760
7
      return 1;
761
    else
762
20
      return -1;
763
  }
764
3493
  return val;
765
}
766
767
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
768
9
  Environment* env = Environment::GetCurrent(args);
769
770
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
771
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
772
9
  ArrayBufferViewContents<char> source(args[0]);
773
9
  ArrayBufferViewContents<char> target(args[1]);
774
775
9
  size_t target_start = 0;
776
9
  size_t source_start = 0;
777
9
  size_t source_end = 0;
778
9
  size_t target_end = 0;
779
780

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

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

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

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

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

881
  if ((is_forward && needle_length + offset > haystack_length) ||
911
879
      needle_length > haystack_length) {
912
30
    return args.GetReturnValue().Set(-1);
913
  }
914
915
866
  size_t result = haystack_length;
916
917
866
  if (enc == UCS2) {
918
89
    String::Value needle_value(isolate, needle);
919
89
    if (*needle_value == nullptr)
920
      return args.GetReturnValue().Set(-1);
921
922

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

199
  if ((is_forward && needle_length + offset > haystack_length) ||
1023
197
      needle_length > haystack_length) {
1024
14
    return args.GetReturnValue().Set(-1);
1025
  }
1026
1027
192
  size_t result = haystack_length;
1028
1029
192
  if (enc == UCS2) {
1030

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

50
  if (opt_offset <= -1 || buffer.length() == 0) {
1070
8
    return args.GetReturnValue().Set(-1);
1071
  }
1072
46
  size_t offset = static_cast<size_t>(opt_offset);
1073
46
  CHECK_LT(offset, buffer.length());
1074
1075
  const void* ptr;
1076
46
  if (is_forward) {
1077
38
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1078
  } else {
1079
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1080
  }
1081
46
  const char* ptr_char = static_cast<const char*>(ptr);
1082
92
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1083
                                : -1);
1084
}
1085
1086
1087
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1088
2
  Environment* env = Environment::GetCurrent(args);
1089
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1090

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

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1100
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1101
4
  args.GetReturnValue().Set(args[0]);
1102
}
1103
1104
1105
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1106
2
  Environment* env = Environment::GetCurrent(args);
1107
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1108

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

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

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