GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 629 702 89.6 %
Date: 2022-08-17 04:19:55 Branches: 309 522 59.2 %

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
9
void CallbackInfo::CleanupHook(void* data) {
152
9
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
153
154
  {
155
18
    HandleScope handle_scope(self->env_->isolate());
156
18
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
157

18
    if (!ab.IsEmpty() && ab->IsDetachable()) {
158
9
      ab->Detach();
159
9
      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
9
  self->CallAndResetCallback();
166
9
}
167
168
39
void CallbackInfo::CallAndResetCallback() {
169
  FreeCallback callback;
170
  {
171
39
    Mutex::ScopedLock lock(mutex_);
172
39
    callback = callback_;
173
39
    callback_ = nullptr;
174
  }
175
39
  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
39
}
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
643151
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
206
                                                   Local<Value> arg,
207
                                                   size_t def,
208
                                                   size_t* ret) {
209
1286302
  if (arg->IsUndefined()) {
210
    *ret = def;
211
    return Just(true);
212
  }
213
214
  int64_t tmp_i;
215
1286302
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
216
    return Nothing<bool>();
217
218
643151
  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
643149
  if (static_cast<uint64_t>(tmp_i) > std::numeric_limits<size_t>::max())
224
    return Just(false);
225
226
643149
  *ret = static_cast<size_t>(tmp_i);
227
643149
  return Just(true);
228
}
229
230
}  // anonymous namespace
231
232
// Buffer methods
233
234
4003832
bool HasInstance(Local<Value> val) {
235
4003832
  return val->IsArrayBufferView();
236
}
237
238
239
321469
bool HasInstance(Local<Object> obj) {
240
321469
  return obj->IsArrayBufferView();
241
}
242
243
244
457425
char* Data(Local<Value> val) {
245
457425
  CHECK(val->IsArrayBufferView());
246
457425
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
247
1372275
  return static_cast<char*>(ui->Buffer()->Data()) + ui->ByteOffset();
248
}
249
250
251
321564
char* Data(Local<Object> obj) {
252
321564
  return Data(obj.As<Value>());
253
}
254
255
256
107235
size_t Length(Local<Value> val) {
257
107235
  CHECK(val->IsArrayBufferView());
258
107235
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
259
107235
  return ui->ByteLength();
260
}
261
262
263
319735
size_t Length(Local<Object> obj) {
264
319735
  CHECK(obj->IsArrayBufferView());
265
319735
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
266
319735
  return ui->ByteLength();
267
}
268
269
270
1031747
MaybeLocal<Uint8Array> New(Environment* env,
271
                           Local<ArrayBuffer> ab,
272
                           size_t byte_offset,
273
                           size_t length) {
274
2063494
  CHECK(!env->buffer_prototype_object().IsEmpty());
275
1031747
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
276
  Maybe<bool> mb =
277
2063494
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
278
1031747
  if (mb.IsNothing())
279
    return MaybeLocal<Uint8Array>();
280
1031747
  return ui;
281
}
282
283
370
MaybeLocal<Uint8Array> New(Isolate* isolate,
284
                           Local<ArrayBuffer> ab,
285
                           size_t byte_offset,
286
                           size_t length) {
287
370
  Environment* env = Environment::GetCurrent(isolate);
288
370
  if (env == nullptr) {
289
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
290
    return MaybeLocal<Uint8Array>();
291
  }
292
370
  return New(env, ab, byte_offset, length);
293
}
294
295
296
371
MaybeLocal<Object> New(Isolate* isolate,
297
                       Local<String> string,
298
                       enum encoding enc) {
299
371
  EscapableHandleScope scope(isolate);
300
301
  size_t length;
302
742
  if (!StringBytes::Size(isolate, string, enc).To(&length))
303
    return Local<Object>();
304
371
  size_t actual = 0;
305
371
  std::unique_ptr<BackingStore> store;
306
307
371
  if (length > 0) {
308
371
    store = ArrayBuffer::NewBackingStore(isolate, length);
309
310
371
    if (UNLIKELY(!store)) {
311
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
312
      return Local<Object>();
313
    }
314
315
371
    actual = StringBytes::Write(
316
        isolate,
317
371
        static_cast<char*>(store->Data()),
318
        length,
319
        string,
320
        enc);
321
371
    CHECK(actual <= length);
322
323
371
    if (LIKELY(actual > 0)) {
324
370
      if (actual < length)
325
        store = BackingStore::Reallocate(isolate, std::move(store), actual);
326
370
      Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
327
      Local<Object> obj;
328
740
      if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
329
        return MaybeLocal<Object>();
330
370
      return scope.Escape(obj);
331
    }
332
  }
333
334
2
  return scope.EscapeMaybe(New(isolate, 0));
335
}
336
337
338
2
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
339
2
  EscapableHandleScope handle_scope(isolate);
340
  Local<Object> obj;
341
2
  Environment* env = Environment::GetCurrent(isolate);
342
2
  if (env == nullptr) {
343
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
344
    return MaybeLocal<Object>();
345
  }
346
4
  if (Buffer::New(env, length).ToLocal(&obj))
347
2
    return handle_scope.Escape(obj);
348
  return Local<Object>();
349
}
350
351
352
1809
MaybeLocal<Object> New(Environment* env, size_t length) {
353
1809
  Isolate* isolate(env->isolate());
354
1809
  EscapableHandleScope scope(isolate);
355
356
  // V8 currently only allows a maximum Typed Array index of max Smi.
357
1809
  if (length > kMaxLength) {
358
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
359
    return Local<Object>();
360
  }
361
362
  Local<ArrayBuffer> ab;
363
  {
364
3618
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
365
    std::unique_ptr<BackingStore> bs =
366
1809
        ArrayBuffer::NewBackingStore(isolate, length);
367
368
1809
    CHECK(bs);
369
370
1809
    ab = ArrayBuffer::New(isolate, std::move(bs));
371
  }
372
373
  MaybeLocal<Object> obj =
374
1809
      New(env, ab, 0, ab->ByteLength())
375
1809
          .FromMaybe(Local<Uint8Array>());
376
377
1809
  return scope.EscapeMaybe(obj);
378
}
379
380
381
3296
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
382
3296
  EscapableHandleScope handle_scope(isolate);
383
3296
  Environment* env = Environment::GetCurrent(isolate);
384
3296
  if (env == nullptr) {
385
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
386
1
    return MaybeLocal<Object>();
387
  }
388
  Local<Object> obj;
389
6590
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
390
3295
    return handle_scope.Escape(obj);
391
  return Local<Object>();
392
}
393
394
395
23870
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
396
23870
  Isolate* isolate(env->isolate());
397
23870
  EscapableHandleScope scope(isolate);
398
399
  // V8 currently only allows a maximum Typed Array index of max Smi.
400
23870
  if (length > kMaxLength) {
401
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
402
    return Local<Object>();
403
  }
404
405
  Local<ArrayBuffer> ab;
406
  {
407
47740
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
408
    std::unique_ptr<BackingStore> bs =
409
23870
        ArrayBuffer::NewBackingStore(isolate, length);
410
411
23870
    CHECK(bs);
412
413
23870
    memcpy(bs->Data(), data, length);
414
415
23870
    ab = ArrayBuffer::New(isolate, std::move(bs));
416
  }
417
418
  MaybeLocal<Object> obj =
419
23870
      New(env, ab, 0, ab->ByteLength())
420
23870
          .FromMaybe(Local<Uint8Array>());
421
422
23870
  return scope.EscapeMaybe(obj);
423
}
424
425
426
30
MaybeLocal<Object> New(Isolate* isolate,
427
                       char* data,
428
                       size_t length,
429
                       FreeCallback callback,
430
                       void* hint) {
431
30
  EscapableHandleScope handle_scope(isolate);
432
30
  Environment* env = Environment::GetCurrent(isolate);
433
30
  if (env == nullptr) {
434
    callback(data, hint);
435
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
436
    return MaybeLocal<Object>();
437
  }
438
  return handle_scope.EscapeMaybe(
439
60
      Buffer::New(env, data, length, callback, hint));
440
}
441
442
443
30
MaybeLocal<Object> New(Environment* env,
444
                       char* data,
445
                       size_t length,
446
                       FreeCallback callback,
447
                       void* hint) {
448
30
  EscapableHandleScope scope(env->isolate());
449
450
30
  if (length > kMaxLength) {
451
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
452
    callback(data, hint);
453
    return Local<Object>();
454
  }
455
456
  Local<ArrayBuffer> ab =
457
30
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
458
90
  if (ab->SetPrivate(env->context(),
459
                     env->untransferable_object_private_symbol(),
460
90
                     True(env->isolate())).IsNothing()) {
461
    return Local<Object>();
462
  }
463
30
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
464
465
  Local<Uint8Array> ui;
466
30
  if (!maybe_ui.ToLocal(&ui))
467
    return MaybeLocal<Object>();
468
469
30
  return scope.Escape(ui);
470
}
471
472
// Warning: This function needs `data` to be allocated with malloc() and not
473
// necessarily isolate's ArrayBuffer::Allocator.
474
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
475
  EscapableHandleScope handle_scope(isolate);
476
  Environment* env = Environment::GetCurrent(isolate);
477
  if (env == nullptr) {
478
    free(data);
479
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
480
    return MaybeLocal<Object>();
481
  }
482
  Local<Object> obj;
483
  if (Buffer::New(env, data, length).ToLocal(&obj))
484
    return handle_scope.Escape(obj);
485
  return Local<Object>();
486
}
487
488
// The contract for this function is that `data` is allocated with malloc()
489
// and not necessarily isolate's ArrayBuffer::Allocator.
490
1001424
MaybeLocal<Object> New(Environment* env,
491
                       char* data,
492
                       size_t length) {
493
1001424
  if (length > 0) {
494
1001423
    CHECK_NOT_NULL(data);
495
    // V8 currently only allows a maximum Typed Array index of max Smi.
496
1001423
    if (length > kMaxLength) {
497
      Isolate* isolate(env->isolate());
498
      isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
499
      free(data);
500
      return Local<Object>();
501
    }
502
  }
503
504
1001424
  EscapableHandleScope handle_scope(env->isolate());
505
506
1001423
  auto free_callback = [](void* data, size_t length, void* deleter_data) {
507
1001423
    free(data);
508
1001423
  };
509
  std::unique_ptr<BackingStore> bs =
510
2002848
      v8::ArrayBuffer::NewBackingStore(data, length, free_callback, nullptr);
511
512
1001424
  Local<ArrayBuffer> ab = v8::ArrayBuffer::New(env->isolate(), std::move(bs));
513
514
  Local<Object> obj;
515
2002848
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
516
1001424
    return handle_scope.Escape(obj);
517
  return Local<Object>();
518
}
519
520
namespace {
521
522
371
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
523
742
  CHECK(args[0]->IsString());
524
371
  CHECK(args[1]->IsInt32());
525
526
742
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
527
  Local<Object> buf;
528
1113
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
529
742
    args.GetReturnValue().Set(buf);
530
371
}
531
532
533
template <encoding encoding>
534
279104
void StringSlice(const FunctionCallbackInfo<Value>& args) {
535
279104
  Environment* env = Environment::GetCurrent(args);
536
279104
  Isolate* isolate = env->isolate();
537
538
279540
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
539
279104
  ArrayBufferViewContents<char> buffer(args.This());
540
541
279104
  if (buffer.length() == 0)
542
844
    return args.GetReturnValue().SetEmptyString();
543
544
278682
  size_t start = 0;
545
278682
  size_t end = 0;
546

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

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

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

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

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

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

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

82
  if (target_start >= target_length || source_start >= source_end)
590
    return args.GetReturnValue().Set(0);
591
592
82
  if (source_start > source.length())
593
    return THROW_ERR_OUT_OF_RANGE(
594
        env, "The value of \"sourceStart\" is out of range.");
595
596
82
  if (source_end - source_start > target_length - target_start)
597
    source_end = source_start + target_length - target_start;
598
599
82
  uint32_t to_copy = std::min(
600
164
      std::min(source_end - source_start, target_length - target_start),
601
82
      source.length() - source_start);
602
603
82
  memmove(target_data + target_start, source.data() + source_start, to_copy);
604
164
  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

1062
  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

42
    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(
670
93
        env->isolate(), ts_obj_data + start, fill_length, str_obj, enc);
671
  }
672
673
172
start_fill:
674
675
172
  if (str_length >= fill_length)
676
10
    return;
677
678
  // If str_length is zero, then either an empty buffer was provided, or Write()
679
  // indicated that no bytes could be written. If no bytes could be written,
680
  // then return -1 because the fill value is invalid. This will trigger a throw
681
  // in JavaScript. Silently failing should be avoided because it can lead to
682
  // buffers with unexpected contents.
683
162
  if (str_length == 0)
684
12
    return args.GetReturnValue().Set(-1);
685
686
156
  size_t in_there = str_length;
687
156
  char* ptr = ts_obj_data + start + str_length;
688
689
445
  while (in_there < fill_length - in_there) {
690
289
    memcpy(ptr, ts_obj_data + start, in_there);
691
289
    ptr += in_there;
692
289
    in_there *= 2;
693
  }
694
695
156
  if (in_there < fill_length) {
696
156
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
697
  }
698
}
699
700
701
template <encoding encoding>
702
363834
void StringWrite(const FunctionCallbackInfo<Value>& args) {
703
363834
  Environment* env = Environment::GetCurrent(args);
704
705
363846
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
706

2183004
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
707
708
727668
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
709
710
363834
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
711
712
363834
  size_t offset = 0;
713
363834
  size_t max_length = 0;
714
715

1091502
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
716
363834
  if (offset > ts_obj_length) {
717
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
718
        env, "\"offset\" is outside of buffer bounds");
719
  }
720
721

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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