GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 626 697 89.8 %
Date: 2022-07-25 04:16:17 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
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
594553
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
206
                                                   Local<Value> arg,
207
                                                   size_t def,
208
                                                   size_t* ret) {
209
1189106
  if (arg->IsUndefined()) {
210
    *ret = def;
211
    return Just(true);
212
  }
213
214
  int64_t tmp_i;
215
1189106
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
216
    return Nothing<bool>();
217
218
594553
  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
594551
  if (static_cast<uint64_t>(tmp_i) > std::numeric_limits<size_t>::max())
224
    return Just(false);
225
226
594551
  *ret = static_cast<size_t>(tmp_i);
227
594551
  return Just(true);
228
}
229
230
}  // anonymous namespace
231
232
// Buffer methods
233
234
4198369
bool HasInstance(Local<Value> val) {
235
4198369
  return val->IsArrayBufferView();
236
}
237
238
239
297166
bool HasInstance(Local<Object> obj) {
240
297166
  return obj->IsArrayBufferView();
241
}
242
243
244
446415
char* Data(Local<Value> val) {
245
446415
  CHECK(val->IsArrayBufferView());
246
446415
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
247
1339245
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
248
446415
      ui->ByteOffset();
249
}
250
251
252
309515
char* Data(Local<Object> obj) {
253
309515
  return Data(obj.As<Value>());
254
}
255
256
257
109094
size_t Length(Local<Value> val) {
258
109094
  CHECK(val->IsArrayBufferView());
259
109094
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
260
109094
  return ui->ByteLength();
261
}
262
263
264
307666
size_t Length(Local<Object> obj) {
265
307666
  CHECK(obj->IsArrayBufferView());
266
307666
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
267
307666
  return ui->ByteLength();
268
}
269
270
271
1031085
MaybeLocal<Uint8Array> New(Environment* env,
272
                           Local<ArrayBuffer> ab,
273
                           size_t byte_offset,
274
                           size_t length) {
275
2062170
  CHECK(!env->buffer_prototype_object().IsEmpty());
276
1031085
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
277
  Maybe<bool> mb =
278
2062170
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
279
1031085
  if (mb.IsNothing())
280
    return MaybeLocal<Uint8Array>();
281
1031085
  return ui;
282
}
283
284
357
MaybeLocal<Uint8Array> New(Isolate* isolate,
285
                           Local<ArrayBuffer> ab,
286
                           size_t byte_offset,
287
                           size_t length) {
288
357
  Environment* env = Environment::GetCurrent(isolate);
289
357
  if (env == nullptr) {
290
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
291
    return MaybeLocal<Uint8Array>();
292
  }
293
357
  return New(env, ab, byte_offset, length);
294
}
295
296
297
358
MaybeLocal<Object> New(Isolate* isolate,
298
                       Local<String> string,
299
                       enum encoding enc) {
300
358
  EscapableHandleScope scope(isolate);
301
302
  size_t length;
303
716
  if (!StringBytes::Size(isolate, string, enc).To(&length))
304
    return Local<Object>();
305
358
  size_t actual = 0;
306
358
  std::unique_ptr<BackingStore> store;
307
308
358
  if (length > 0) {
309
358
    store = ArrayBuffer::NewBackingStore(isolate, length);
310
311
358
    if (UNLIKELY(!store)) {
312
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
313
      return Local<Object>();
314
    }
315
316
358
    actual = StringBytes::Write(
317
        isolate,
318
358
        static_cast<char*>(store->Data()),
319
        length,
320
        string,
321
        enc);
322
358
    CHECK(actual <= length);
323
324
358
    if (LIKELY(actual > 0)) {
325
357
      if (actual < length)
326
        store = BackingStore::Reallocate(isolate, std::move(store), actual);
327
357
      Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
328
      Local<Object> obj;
329
714
      if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
330
        return MaybeLocal<Object>();
331
357
      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
1829
MaybeLocal<Object> New(Environment* env, size_t length) {
354
1829
  Isolate* isolate(env->isolate());
355
1829
  EscapableHandleScope scope(isolate);
356
357
  // V8 currently only allows a maximum Typed Array index of max Smi.
358
1829
  if (length > kMaxLength) {
359
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
360
    return Local<Object>();
361
  }
362
363
  Local<ArrayBuffer> ab;
364
  {
365
3658
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
366
    std::unique_ptr<BackingStore> bs =
367
1829
        ArrayBuffer::NewBackingStore(isolate, length);
368
369
1829
    CHECK(bs);
370
371
1829
    ab = ArrayBuffer::New(isolate, std::move(bs));
372
  }
373
374
  MaybeLocal<Object> obj =
375
1829
      New(env, ab, 0, ab->ByteLength())
376
1829
          .FromMaybe(Local<Uint8Array>());
377
378
1829
  return scope.EscapeMaybe(obj);
379
}
380
381
382
3286
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
383
3286
  EscapableHandleScope handle_scope(isolate);
384
3286
  Environment* env = Environment::GetCurrent(isolate);
385
3286
  if (env == nullptr) {
386
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
387
1
    return MaybeLocal<Object>();
388
  }
389
  Local<Object> obj;
390
6570
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
391
3285
    return handle_scope.Escape(obj);
392
  return Local<Object>();
393
}
394
395
396
22160
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
397
22160
  Isolate* isolate(env->isolate());
398
22160
  EscapableHandleScope scope(isolate);
399
400
  // V8 currently only allows a maximum Typed Array index of max Smi.
401
22160
  if (length > kMaxLength) {
402
    isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
403
    return Local<Object>();
404
  }
405
406
  Local<ArrayBuffer> ab;
407
  {
408
44320
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
409
    std::unique_ptr<BackingStore> bs =
410
22160
        ArrayBuffer::NewBackingStore(isolate, length);
411
412
22160
    CHECK(bs);
413
414
22160
    memcpy(bs->Data(), data, length);
415
416
22160
    ab = ArrayBuffer::New(isolate, std::move(bs));
417
  }
418
419
  MaybeLocal<Object> obj =
420
22160
      New(env, ab, 0, ab->ByteLength())
421
22160
          .FromMaybe(Local<Uint8Array>());
422
423
22160
  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
1002468
MaybeLocal<Object> New(Environment* env,
492
                       char* data,
493
                       size_t length) {
494
1002468
  if (length > 0) {
495
1002467
    CHECK_NOT_NULL(data);
496
    // V8 currently only allows a maximum Typed Array index of max Smi.
497
1002467
    if (length > kMaxLength) {
498
      Isolate* isolate(env->isolate());
499
      isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
500
      free(data);
501
      return Local<Object>();
502
    }
503
  }
504
505
1002468
  EscapableHandleScope handle_scope(env->isolate());
506
507
1002467
  auto free_callback = [](void* data, size_t length, void* deleter_data) {
508
1002467
    free(data);
509
1002467
  };
510
  std::unique_ptr<BackingStore> bs =
511
2004936
      v8::ArrayBuffer::NewBackingStore(data, length, free_callback, nullptr);
512
513
1002468
  Local<ArrayBuffer> ab = v8::ArrayBuffer::New(env->isolate(), std::move(bs));
514
515
  Local<Object> obj;
516
2004936
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
517
1002468
    return handle_scope.Escape(obj);
518
  return Local<Object>();
519
}
520
521
namespace {
522
523
358
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
524
716
  CHECK(args[0]->IsString());
525
358
  CHECK(args[1]->IsInt32());
526
527
716
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
528
  Local<Object> buf;
529
1074
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
530
716
    args.GetReturnValue().Set(buf);
531
358
}
532
533
534
template <encoding encoding>
535
281032
void StringSlice(const FunctionCallbackInfo<Value>& args) {
536
281032
  Environment* env = Environment::GetCurrent(args);
537
281032
  Isolate* isolate = env->isolate();
538
539
281460
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
540
281032
  ArrayBufferViewContents<char> buffer(args.This());
541
542
281032
  if (buffer.length() == 0)
543
828
    return args.GetReturnValue().SetEmptyString();
544
545
280618
  size_t start = 0;
546
280618
  size_t end = 0;
547

841854
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
548

1122472
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
549
280618
  if (end < start) end = start;
550

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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