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

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

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

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

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

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

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

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

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

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

13
  if (target_start >= target_length || source_start >= source_end)
591
    return args.GetReturnValue().Set(0);
592
593
13
  if (source_start > source.length())
594
    return THROW_ERR_OUT_OF_RANGE(
595
        env, "The value of \"sourceStart\" is out of range.");
596
597
13
  if (source_end - source_start > target_length - target_start)
598
    source_end = source_start + target_length - target_start;
599
600
13
  uint32_t to_copy = std::min(
601
26
      std::min(source_end - source_start, target_length - target_start),
602
13
      source.length() - source_start);
603
604
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
605
26
  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
310430
void StringWrite(const FunctionCallbackInfo<Value>& args) {
708
310430
  Environment* env = Environment::GetCurrent(args);
709
710
310442
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
711

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

931290
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
721
310430
  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

1241720
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
727
                                          &max_length));
728
729
310430
  max_length = std::min(ts_obj_length - offset, max_length);
730
731
310430
  if (max_length == 0)
732
24
    return args.GetReturnValue().Set(0);
733
734
310418
  uint32_t written = StringBytes::Write(env->isolate(),
735
310418
                                        ts_obj_data + offset,
736
                                        max_length,
737
                                        str,
738
                                        encoding,
739
                                        nullptr);
740
620836
  args.GetReturnValue().Set(written);
741
}
742
743
161244
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
744
161244
  Environment* env = Environment::GetCurrent(args);
745
322488
  CHECK(args[0]->IsString());
746
747
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
748
483732
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
749
161244
}
750
751
// Normalize val to be an integer in the range of [1, -1] since
752
// implementations of memcmp() can vary by platform.
753
3547
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
754
3547
  if (val == 0) {
755
3520
    if (a_length > b_length)
756
6
      return 1;
757
3514
    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
3509
  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
3538
void Compare(const FunctionCallbackInfo<Value> &args) {
813
3538
  Environment* env = Environment::GetCurrent(args);
814
815
3538
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
816
3538
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
817
3538
  ArrayBufferViewContents<char> a(args[0]);
818
3538
  ArrayBufferViewContents<char> b(args[1]);
819
820
3538
  size_t cmp_length = std::min(a.length(), b.length());
821
822
7012
  int val = normalizeCompareVal(cmp_length > 0 ?
823
3474
                                memcmp(a.data(), b.data(), cmp_length) : 0,
824
                                a.length(), b.length());
825
7076
  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
421
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1118
421
  Environment* env = Environment::GetCurrent(args);
1119
421
  Isolate* isolate = env->isolate();
1120
421
  CHECK_GE(args.Length(), 1);
1121
842
  CHECK(args[0]->IsString());
1122
1123
842
  Local<String> str = args[0].As<String>();
1124
421
  size_t length = str->Utf8Length(isolate);
1125
1126
  Local<ArrayBuffer> ab;
1127
  {
1128
842
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1129
    std::unique_ptr<BackingStore> bs =
1130
421
        ArrayBuffer::NewBackingStore(isolate, length);
1131
1132
421
    CHECK(bs);
1133
1134
421
    str->WriteUtf8(isolate,
1135
421
                   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
421
    ab = ArrayBuffer::New(isolate, std::move(bs));
1141
  }
1142
1143
421
  auto array = Uint8Array::New(ab, 0, length);
1144
421
  args.GetReturnValue().Set(array);
1145
421
}
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
848
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1183
848
  Environment* env = Environment::GetCurrent(args);
1184
1185
848
  CHECK(args[0]->IsObject());
1186
848
  Local<Object> proto = args[0].As<Object>();
1187
848
  env->set_buffer_prototype_object(proto);
1188
848
}
1189
1190
6042
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1191
6042
  Environment* env = Environment::GetCurrent(args);
1192
6042
  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
6042
  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
5980
    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
5471
                                     [](void*, size_t, void*) {},
1207
5980
                                     nullptr);
1208
5980
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1209
  }
1210
1211
12084
  ab->SetPrivate(
1212
      env->context(),
1213
      env->untransferable_object_private_symbol(),
1214
18126
      True(env->isolate())).Check();
1215
1216
6042
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1217
6042
}
1218
1219
709
void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1220
709
  Environment* env = Environment::GetCurrent(args);
1221
709
  if (args[0]->IsArrayBuffer()) {
1222
1418
    Local<ArrayBuffer> buf = args[0].As<ArrayBuffer>();
1223
709
    if (buf->IsDetachable()) {
1224
706
      std::shared_ptr<BackingStore> store = buf->GetBackingStore();
1225
706
      buf->Detach();
1226
1412
      args.GetReturnValue().Set(ArrayBuffer::New(env->isolate(), store));
1227
    }
1228
  }
1229
709
}
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
848
void Initialize(Local<Object> target,
1274
                Local<Value> unused,
1275
                Local<Context> context,
1276
                void* priv) {
1277
848
  Environment* env = Environment::GetCurrent(context);
1278
1279
848
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1280
848
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1281
1282
848
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1283
848
  env->SetMethod(target, "copy", Copy);
1284
848
  env->SetMethodNoSideEffect(target, "compare", Compare);
1285
848
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1286
848
  env->SetMethod(target, "fill", Fill);
1287
848
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1288
848
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1289
848
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1290
1291
848
  env->SetMethod(target, "detachArrayBuffer", DetachArrayBuffer);
1292
848
  env->SetMethod(target, "copyArrayBuffer", CopyArrayBuffer);
1293
1294
848
  env->SetMethod(target, "swap16", Swap16);
1295
848
  env->SetMethod(target, "swap32", Swap32);
1296
848
  env->SetMethod(target, "swap64", Swap64);
1297
1298
848
  env->SetMethod(target, "encodeInto", EncodeInto);
1299
848
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1300
1301
848
  target->Set(env->context(),
1302
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1303
3392
              Number::New(env->isolate(), kMaxLength)).Check();
1304
1305
848
  target->Set(env->context(),
1306
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1307
2544
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1308
1309
848
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1310
848
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1311
848
  env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>);
1312
848
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1313
848
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1314
848
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1315
848
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1316
1317
848
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1318
848
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1319
848
  env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>);
1320
848
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1321
848
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1322
848
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1323
848
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1324
1325
848
  env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle);
1326
848
}
1327
1328
}  // anonymous namespace
1329
1330
5176
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1331
5176
  registry->Register(SetBufferPrototype);
1332
5176
  registry->Register(CreateFromString);
1333
1334
5176
  registry->Register(ByteLengthUtf8);
1335
5176
  registry->Register(Copy);
1336
5176
  registry->Register(Compare);
1337
5176
  registry->Register(CompareOffset);
1338
5176
  registry->Register(Fill);
1339
5176
  registry->Register(IndexOfBuffer);
1340
5176
  registry->Register(IndexOfNumber);
1341
5176
  registry->Register(IndexOfString);
1342
1343
5176
  registry->Register(Swap16);
1344
5176
  registry->Register(Swap32);
1345
5176
  registry->Register(Swap64);
1346
1347
5176
  registry->Register(EncodeInto);
1348
5176
  registry->Register(EncodeUtf8String);
1349
1350
5176
  registry->Register(StringSlice<ASCII>);
1351
5176
  registry->Register(StringSlice<BASE64>);
1352
5176
  registry->Register(StringSlice<BASE64URL>);
1353
5176
  registry->Register(StringSlice<LATIN1>);
1354
5176
  registry->Register(StringSlice<HEX>);
1355
5176
  registry->Register(StringSlice<UCS2>);
1356
5176
  registry->Register(StringSlice<UTF8>);
1357
1358
5176
  registry->Register(StringWrite<ASCII>);
1359
5176
  registry->Register(StringWrite<BASE64>);
1360
5176
  registry->Register(StringWrite<BASE64URL>);
1361
5176
  registry->Register(StringWrite<LATIN1>);
1362
5176
  registry->Register(StringWrite<HEX>);
1363
5176
  registry->Register(StringWrite<UCS2>);
1364
5176
  registry->Register(StringWrite<UTF8>);
1365
5176
  registry->Register(GetZeroFillToggle);
1366
1367
5176
  registry->Register(DetachArrayBuffer);
1368
5176
  registry->Register(CopyArrayBuffer);
1369
5176
}
1370
1371
}  // namespace Buffer
1372
}  // namespace node
1373
1374
5244
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1375
5176
NODE_MODULE_EXTERNAL_REFERENCE(buffer, node::Buffer::RegisterExternalReferences)