GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 603 669 90.1 %
Date: 2021-08-24 04:12:49 Branches: 307 518 59.3 %

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
    if ((r).IsNothing()) return;                                            \
45
    if (!(r).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
865
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
109
    Environment* env,
110
    char* data,
111
    size_t length,
112
    FreeCallback callback,
113
    void* hint) {
114
865
  CHECK_NOT_NULL(callback);
115

865
  CHECK_IMPLIES(data == nullptr, length == 0);
116
117
865
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
118
  std::unique_ptr<BackingStore> bs =
119
862
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
120
862
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
121
865
      }, self);
122
865
  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
865
  if (data == nullptr) {
127
3
    ab->Detach();
128
3
    self->OnBackingStoreFree();  // This calls `callback` asynchronously.
129
  } else {
130
    // Store the ArrayBuffer so that we can detach it later.
131
862
    self->persistent_.Reset(env->isolate(), ab);
132
862
    self->persistent_.SetWeak();
133
  }
134
135
865
  return ab;
136
}
137
138
139
865
CallbackInfo::CallbackInfo(Environment* env,
140
                           FreeCallback callback,
141
                           char* data,
142
865
                           void* hint)
143
    : callback_(callback),
144
      data_(data),
145
      hint_(hint),
146
1730
      env_(env) {
147
865
  env->AddCleanupHook(CleanupHook, this);
148
865
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
149
865
}
150
151
668
void CallbackInfo::CleanupHook(void* data) {
152
668
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
153
154
  {
155
1336
    HandleScope handle_scope(self->env_->isolate());
156
1336
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
157

1336
    if (!ab.IsEmpty() && ab->IsDetachable()) {
158
668
      ab->Detach();
159
668
      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
668
  self->CallAndResetCallback();
166
668
}
167
168
1530
void CallbackInfo::CallAndResetCallback() {
169
  FreeCallback callback;
170
  {
171
1530
    Mutex::ScopedLock lock(mutex_);
172
1530
    callback = callback_;
173
1530
    callback_ = nullptr;
174
  }
175
1530
  if (callback != nullptr) {
176
    // Clean up all Environment-related state and run the callback.
177
862
    env_->RemoveCleanupHook(CleanupHook, this);
178
862
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
179
862
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
180
181
862
    callback(data_, hint_);
182
  }
183
1530
}
184
185
865
void CallbackInfo::OnBackingStoreFree() {
186
  // This method should always release the memory for `this`.
187
865
  std::unique_ptr<CallbackInfo> self { this };
188
865
  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
865
  if (callback_ == nullptr) return;
194
195
865
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
196
862
    CHECK_EQ(self->env_, env);  // Consistency check.
197
198
862
    self->CallAndResetCallback();
199
862
  });
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
1085476
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
206
                                                   Local<Value> arg,
207
                                                   size_t def,
208
                                                   size_t* ret) {
209
2170952
  if (arg->IsUndefined()) {
210
    *ret = def;
211
    return Just(true);
212
  }
213
214
  int64_t tmp_i;
215
2170952
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
216
    return Nothing<bool>();
217
218
1085476
  if (tmp_i < 0)
219
4
    return Just(false);
220
221
  // Check that the result fits in a size_t.
222
1085472
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
223
  // coverity[pointless_expression]
224
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
225
    return Just(false);
226
227
1085472
  *ret = static_cast<size_t>(tmp_i);
228
1085472
  return Just(true);
229
}
230
231
}  // anonymous namespace
232
233
// Buffer methods
234
235
3435361
bool HasInstance(Local<Value> val) {
236
3435361
  return val->IsArrayBufferView();
237
}
238
239
240
271346
bool HasInstance(Local<Object> obj) {
241
271346
  return obj->IsArrayBufferView();
242
}
243
244
245
273879
char* Data(Local<Value> val) {
246
273879
  CHECK(val->IsArrayBufferView());
247
273879
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
248
821637
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
249
273879
      ui->ByteOffset();
250
}
251
252
253
142630
char* Data(Local<Object> obj) {
254
142630
  return Data(obj.As<Value>());
255
}
256
257
258
104102
size_t Length(Local<Value> val) {
259
104102
  CHECK(val->IsArrayBufferView());
260
104102
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
261
104102
  return ui->ByteLength();
262
}
263
264
265
141226
size_t Length(Local<Object> obj) {
266
141226
  CHECK(obj->IsArrayBufferView());
267
141226
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
268
141226
  return ui->ByteLength();
269
}
270
271
272
13097
MaybeLocal<Uint8Array> New(Environment* env,
273
                           Local<ArrayBuffer> ab,
274
                           size_t byte_offset,
275
                           size_t length) {
276
26194
  CHECK(!env->buffer_prototype_object().IsEmpty());
277
13097
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
278
  Maybe<bool> mb =
279
26194
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
280
13097
  if (mb.IsNothing())
281
    return MaybeLocal<Uint8Array>();
282
13097
  return ui;
283
}
284
285
293
MaybeLocal<Uint8Array> New(Isolate* isolate,
286
                           Local<ArrayBuffer> ab,
287
                           size_t byte_offset,
288
                           size_t length) {
289
293
  Environment* env = Environment::GetCurrent(isolate);
290
293
  if (env == nullptr) {
291
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
292
    return MaybeLocal<Uint8Array>();
293
  }
294
293
  return New(env, ab, byte_offset, length);
295
}
296
297
298
294
MaybeLocal<Object> New(Isolate* isolate,
299
                       Local<String> string,
300
                       enum encoding enc) {
301
294
  EscapableHandleScope scope(isolate);
302
303
  size_t length;
304
588
  if (!StringBytes::Size(isolate, string, enc).To(&length))
305
    return Local<Object>();
306
294
  size_t actual = 0;
307
294
  std::unique_ptr<BackingStore> store;
308
309
294
  if (length > 0) {
310
294
    store = ArrayBuffer::NewBackingStore(isolate, length);
311
312
294
    if (UNLIKELY(!store)) {
313
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
314
      return Local<Object>();
315
    }
316
317
294
    actual = StringBytes::Write(
318
        isolate,
319
294
        static_cast<char*>(store->Data()),
320
        length,
321
        string,
322
        enc);
323
294
    CHECK(actual <= length);
324
325
294
    if (LIKELY(actual > 0)) {
326
293
      if (actual < length)
327
        store = BackingStore::Reallocate(isolate, std::move(store), actual);
328
293
      Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
329
      Local<Object> obj;
330
586
      if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
331
        return MaybeLocal<Object>();
332
293
      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
1384
MaybeLocal<Object> New(Environment* env, size_t length) {
355
1384
  EscapableHandleScope scope(env->isolate());
356
357
  // V8 currently only allows a maximum Typed Array index of max Smi.
358
1384
  if (length > kMaxLength) {
359
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
360
    return Local<Object>();
361
  }
362
363
  return scope.EscapeMaybe(
364
2768
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
365
}
366
367
368
3544
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
369
3544
  EscapableHandleScope handle_scope(isolate);
370
3544
  Environment* env = Environment::GetCurrent(isolate);
371
3544
  if (env == nullptr) {
372
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
373
    return MaybeLocal<Object>();
374
  }
375
  Local<Object> obj;
376
7086
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
377
3543
    return handle_scope.Escape(obj);
378
  return Local<Object>();
379
}
380
381
382
6833
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
383
6833
  EscapableHandleScope scope(env->isolate());
384
385
  // V8 currently only allows a maximum Typed Array index of max Smi.
386
6833
  if (length > kMaxLength) {
387
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
388
    return Local<Object>();
389
  }
390
391
6833
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
392
6833
  if (length > 0) {
393
6592
    memcpy(ret.data(), data, length);
394
  }
395
396
13666
  return scope.EscapeMaybe(ret.ToBuffer());
397
}
398
399
400
29
MaybeLocal<Object> New(Isolate* isolate,
401
                       char* data,
402
                       size_t length,
403
                       FreeCallback callback,
404
                       void* hint) {
405
29
  EscapableHandleScope handle_scope(isolate);
406
29
  Environment* env = Environment::GetCurrent(isolate);
407
29
  if (env == nullptr) {
408
    callback(data, hint);
409
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
410
    return MaybeLocal<Object>();
411
  }
412
  return handle_scope.EscapeMaybe(
413
58
      Buffer::New(env, data, length, callback, hint));
414
}
415
416
417
865
MaybeLocal<Object> New(Environment* env,
418
                       char* data,
419
                       size_t length,
420
                       FreeCallback callback,
421
                       void* hint) {
422
865
  EscapableHandleScope scope(env->isolate());
423
424
865
  if (length > kMaxLength) {
425
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
426
    callback(data, hint);
427
    return Local<Object>();
428
  }
429
430
  Local<ArrayBuffer> ab =
431
865
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
432
2595
  if (ab->SetPrivate(env->context(),
433
                     env->untransferable_object_private_symbol(),
434
2595
                     True(env->isolate())).IsNothing()) {
435
    return Local<Object>();
436
  }
437
865
  MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
438
439
  Local<Uint8Array> ui;
440
865
  if (!maybe_ui.ToLocal(&ui))
441
    return MaybeLocal<Object>();
442
443
865
  return scope.Escape(ui);
444
}
445
446
// Warning: This function needs `data` to be allocated with malloc() and not
447
// necessarily isolate's ArrayBuffer::Allocator.
448
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
449
  EscapableHandleScope handle_scope(isolate);
450
  Environment* env = Environment::GetCurrent(isolate);
451
  if (env == nullptr) {
452
    free(data);
453
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
454
    return MaybeLocal<Object>();
455
  }
456
  Local<Object> obj;
457
  if (Buffer::New(env, data, length).ToLocal(&obj))
458
    return handle_scope.Escape(obj);
459
  return Local<Object>();
460
}
461
462
// The contract for this function is that `data` is allocated with malloc()
463
// and not necessarily isolate's ArrayBuffer::Allocator.
464
836
MaybeLocal<Object> New(Environment* env,
465
                       char* data,
466
                       size_t length) {
467
836
  if (length > 0) {
468
835
    CHECK_NOT_NULL(data);
469
835
    CHECK(length <= kMaxLength);
470
  }
471
472
833
  auto free_callback = [](char* data, void* hint) { free(data); };
473
836
  return New(env, data, length, free_callback, nullptr);
474
}
475
476
namespace {
477
478
294
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
479
588
  CHECK(args[0]->IsString());
480
294
  CHECK(args[1]->IsInt32());
481
482
588
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
483
  Local<Object> buf;
484
882
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
485
588
    args.GetReturnValue().Set(buf);
486
294
}
487
488
489
template <encoding encoding>
490
238536
void StringSlice(const FunctionCallbackInfo<Value>& args) {
491
238536
  Environment* env = Environment::GetCurrent(args);
492
238536
  Isolate* isolate = env->isolate();
493
494
238932
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
495
238536
  ArrayBufferViewContents<char> buffer(args.This());
496
497
238536
  if (buffer.length() == 0)
498
764
    return args.GetReturnValue().SetEmptyString();
499
500
238154
  size_t start = 0;
501
238154
  size_t end = 0;
502

952616
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
503

1190770
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
504
238154
  if (end < start) end = start;
505

714462
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
506
238154
  size_t length = end - start;
507
508
  Local<Value> error;
509
  MaybeLocal<Value> maybe_ret =
510
238154
      StringBytes::Encode(isolate,
511
238154
                          buffer.data() + start,
512
                          length,
513
                          encoding,
514
                          &error);
515
  Local<Value> ret;
516
238154
  if (!maybe_ret.ToLocal(&ret)) {
517
14
    CHECK(!error.IsEmpty());
518
14
    isolate->ThrowException(error);
519
14
    return;
520
  }
521
476280
  args.GetReturnValue().Set(ret);
522
}
523
524
525
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
526
13
void Copy(const FunctionCallbackInfo<Value> &args) {
527
13
  Environment* env = Environment::GetCurrent(args);
528
529
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
530
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
531
13
  ArrayBufferViewContents<char> source(args[0]);
532
26
  Local<Object> target_obj = args[1].As<Object>();
533

52
  SPREAD_BUFFER_ARG(target_obj, target);
534
535
13
  size_t target_start = 0;
536
13
  size_t source_start = 0;
537
13
  size_t source_end = 0;
538
539

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
540

52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
541

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
542
                                          &source_end));
543
544
  // Copy 0 bytes; we're done
545

13
  if (target_start >= target_length || source_start >= source_end)
546
    return args.GetReturnValue().Set(0);
547
548
13
  if (source_start > source.length())
549
    return THROW_ERR_OUT_OF_RANGE(
550
        env, "The value of \"sourceStart\" is out of range.");
551
552
13
  if (source_end - source_start > target_length - target_start)
553
    source_end = source_start + target_length - target_start;
554
555
13
  uint32_t to_copy = std::min(
556
26
      std::min(source_end - source_start, target_length - target_start),
557
13
      source.length() - source_start);
558
559
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
560
26
  args.GetReturnValue().Set(to_copy);
561
}
562
563
564
177
void Fill(const FunctionCallbackInfo<Value>& args) {
565
177
  Environment* env = Environment::GetCurrent(args);
566
177
  Local<Context> ctx = env->context();
567
568
198
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
569

885
  SPREAD_BUFFER_ARG(args[0], ts_obj);
570
571
177
  size_t start = 0;
572

708
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
573
  size_t end;
574

704
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
575
576
175
  size_t fill_length = end - start;
577
  Local<String> str_obj;
578
  size_t str_length;
579
  enum encoding enc;
580
581
  // OOB Check. Throw the error in JS.
582

175
  if (start > end || fill_length + start > ts_obj_length)
583
    return args.GetReturnValue().Set(-2);
584
585
  // First check if Buffer has been passed.
586
175
  if (Buffer::HasInstance(args[1])) {
587

35
    SPREAD_BUFFER_ARG(args[1], fill_obj);
588
7
    str_length = fill_obj_length;
589
14
    memcpy(
590
7
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
591
7
    goto start_fill;
592
  }
593
594
  // Then coerce everything that's not a string.
595
336
  if (!args[1]->IsString()) {
596
    uint32_t val;
597
6
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
598
3
    int value = val & 255;
599
3
    memset(ts_obj_data + start, value, fill_length);
600
3
    return;
601
  }
602
603
330
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
604
165
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
605
606
  // Can't use StringBytes::Write() in all cases. For example if attempting
607
  // to write a two byte character into a one byte Buffer.
608
165
  if (enc == UTF8) {
609
49
    str_length = str_obj->Utf8Length(env->isolate());
610
49
    node::Utf8Value str(env->isolate(), args[1]);
611
49
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
612
613
116
  } else if (enc == UCS2) {
614
23
    str_length = str_obj->Length() * sizeof(uint16_t);
615
23
    node::TwoByteValue str(env->isolate(), args[1]);
616
23
    if (IsBigEndian())
617
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
618
619
23
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
620
621
  } else {
622
    // Write initial String to Buffer, then use that memory to copy remainder
623
    // of string. Correct the string length for cases like HEX where less than
624
    // the total string length is written.
625
93
    str_length = StringBytes::Write(env->isolate(),
626
93
                                    ts_obj_data + start,
627
                                    fill_length,
628
                                    str_obj,
629
                                    enc,
630
                                    nullptr);
631
  }
632
633
172
start_fill:
634
635
172
  if (str_length >= fill_length)
636
10
    return;
637
638
  // If str_length is zero, then either an empty buffer was provided, or Write()
639
  // indicated that no bytes could be written. If no bytes could be written,
640
  // then return -1 because the fill value is invalid. This will trigger a throw
641
  // in JavaScript. Silently failing should be avoided because it can lead to
642
  // buffers with unexpected contents.
643
162
  if (str_length == 0)
644
12
    return args.GetReturnValue().Set(-1);
645
646
156
  size_t in_there = str_length;
647
156
  char* ptr = ts_obj_data + start + str_length;
648
649
445
  while (in_there < fill_length - in_there) {
650
289
    memcpy(ptr, ts_obj_data + start, in_there);
651
289
    ptr += in_there;
652
289
    in_there *= 2;
653
  }
654
655
156
  if (in_there < fill_length) {
656
156
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
657
  }
658
}
659
660
661
template <encoding encoding>
662
304156
void StringWrite(const FunctionCallbackInfo<Value>& args) {
663
304156
  Environment* env = Environment::GetCurrent(args);
664
665
304166
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
666

1520780
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
667
668
608312
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
669
670
304156
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
671
672
304156
  size_t offset = 0;
673
304156
  size_t max_length = 0;
674
675

1216624
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
676
304156
  if (offset > ts_obj_length) {
677
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
678
        env, "\"offset\" is outside of buffer bounds");
679
  }
680
681


1520780
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
682
                                          &max_length));
683
684
304156
  max_length = std::min(ts_obj_length - offset, max_length);
685
686
304156
  if (max_length == 0)
687
20
    return args.GetReturnValue().Set(0);
688
689
304146
  uint32_t written = StringBytes::Write(env->isolate(),
690
304146
                                        ts_obj_data + offset,
691
                                        max_length,
692
                                        str,
693
                                        encoding,
694
                                        nullptr);
695
608292
  args.GetReturnValue().Set(written);
696
}
697
698
158481
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
699
158481
  Environment* env = Environment::GetCurrent(args);
700
316962
  CHECK(args[0]->IsString());
701
702
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
703
475443
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
704
158481
}
705
706
// Normalize val to be an integer in the range of [1, -1] since
707
// implementations of memcmp() can vary by platform.
708
3559
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
709
3559
  if (val == 0) {
710
3532
    if (a_length > b_length)
711
6
      return 1;
712
3526
    else if (a_length < b_length)
713
5
      return -1;
714
  } else {
715
27
    if (val > 0)
716
7
      return 1;
717
    else
718
20
      return -1;
719
  }
720
3521
  return val;
721
}
722
723
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
724
9
  Environment* env = Environment::GetCurrent(args);
725
726
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
727
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
728
9
  ArrayBufferViewContents<char> source(args[0]);
729
9
  ArrayBufferViewContents<char> target(args[1]);
730
731
9
  size_t target_start = 0;
732
9
  size_t source_start = 0;
733
9
  size_t source_end = 0;
734
9
  size_t target_end = 0;
735
736

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
737

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
738

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
739
                                          &target_end));
740

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
741
                                          &source_end));
742
743
9
  if (source_start > source.length())
744
    return THROW_ERR_OUT_OF_RANGE(
745
        env, "The value of \"sourceStart\" is out of range.");
746
9
  if (target_start > target.length())
747
    return THROW_ERR_OUT_OF_RANGE(
748
        env, "The value of \"targetStart\" is out of range.");
749
750
9
  CHECK_LE(source_start, source_end);
751
9
  CHECK_LE(target_start, target_end);
752
753
  size_t to_cmp =
754
18
      std::min(std::min(source_end - source_start, target_end - target_start),
755
9
               source.length() - source_start);
756
757
18
  int val = normalizeCompareVal(to_cmp > 0 ?
758
9
                                  memcmp(source.data() + source_start,
759
9
                                         target.data() + target_start,
760
                                         to_cmp) : 0,
761
                                source_end - source_start,
762
                                target_end - target_start);
763
764
18
  args.GetReturnValue().Set(val);
765
}
766
767
3550
void Compare(const FunctionCallbackInfo<Value> &args) {
768
3550
  Environment* env = Environment::GetCurrent(args);
769
770
3550
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
771
3550
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
772
3550
  ArrayBufferViewContents<char> a(args[0]);
773
3550
  ArrayBufferViewContents<char> b(args[1]);
774
775
3550
  size_t cmp_length = std::min(a.length(), b.length());
776
777
7036
  int val = normalizeCompareVal(cmp_length > 0 ?
778
3486
                                memcmp(a.data(), b.data(), cmp_length) : 0,
779
                                a.length(), b.length());
780
7100
  args.GetReturnValue().Set(val);
781
}
782
783
784
// Computes the offset for starting an indexOf or lastIndexOf search.
785
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
786
// or -1 to signal that there is no possible match.
787
1164
int64_t IndexOfOffset(size_t length,
788
                      int64_t offset_i64,
789
                      int64_t needle_length,
790
                      bool is_forward) {
791
1164
  int64_t length_i64 = static_cast<int64_t>(length);
792
1164
  if (offset_i64 < 0) {
793
81
    if (offset_i64 + length_i64 >= 0) {
794
      // Negative offsets count backwards from the end of the buffer.
795
63
      return length_i64 + offset_i64;
796

18
    } else if (is_forward || needle_length == 0) {
797
      // indexOf from before the start of the buffer: search the whole buffer.
798
10
      return 0;
799
    } else {
800
      // lastIndexOf from before the start of the buffer: no match.
801
8
      return -1;
802
    }
803
  } else {
804
1083
    if (offset_i64 + needle_length <= length_i64) {
805
      // Valid positive offset.
806
995
      return offset_i64;
807
88
    } else if (needle_length == 0) {
808
      // Out of buffer bounds, but empty needle: point to end of buffer.
809
10
      return length_i64;
810
78
    } else if (is_forward) {
811
      // indexOf from past the end of the buffer: no match.
812
15
      return -1;
813
    } else {
814
      // lastIndexOf from past the end of the buffer: search the whole buffer.
815
63
      return length_i64 - 1;
816
    }
817
  }
818
}
819
820
894
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
821
894
  Environment* env = Environment::GetCurrent(args);
822
894
  Isolate* isolate = env->isolate();
823
824
1788
  CHECK(args[1]->IsString());
825
894
  CHECK(args[2]->IsNumber());
826
894
  CHECK(args[3]->IsInt32());
827
894
  CHECK(args[4]->IsBoolean());
828
829
1788
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
830
831
927
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
832
894
  ArrayBufferViewContents<char> buffer(args[0]);
833
834
1788
  Local<String> needle = args[1].As<String>();
835
1788
  int64_t offset_i64 = args[2].As<Integer>()->Value();
836
894
  bool is_forward = args[4]->IsTrue();
837
838
894
  const char* haystack = buffer.data();
839
  // Round down to the nearest multiple of 2 in case of UCS2.
840
988
  const size_t haystack_length = (enc == UCS2) ?
841
988
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
842
843
  size_t needle_length;
844
1788
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
845
846
894
  int64_t opt_offset = IndexOfOffset(haystack_length,
847
                                     offset_i64,
848
                                     needle_length,
849
                                     is_forward);
850
851
894
  if (needle_length == 0) {
852
    // Match String#indexOf() and String#lastIndexOf() behavior.
853
8
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
854
8
    return;
855
  }
856
857
886
  if (haystack_length == 0) {
858
    return args.GetReturnValue().Set(-1);
859
  }
860
861
886
  if (opt_offset <= -1) {
862
20
    return args.GetReturnValue().Set(-1);
863
  }
864
876
  size_t offset = static_cast<size_t>(opt_offset);
865
876
  CHECK_LT(offset, haystack_length);
866

876
  if ((is_forward && needle_length + offset > haystack_length) ||
867
874
      needle_length > haystack_length) {
868
30
    return args.GetReturnValue().Set(-1);
869
  }
870
871
861
  size_t result = haystack_length;
872
873
861
  if (enc == UCS2) {
874
89
    String::Value needle_value(isolate, needle);
875
89
    if (*needle_value == nullptr)
876
      return args.GetReturnValue().Set(-1);
877
878

89
    if (haystack_length < 2 || needle_value.length() < 1) {
879
      return args.GetReturnValue().Set(-1);
880
    }
881
882
89
    if (IsBigEndian()) {
883
      StringBytes::InlineDecoder decoder;
884
      if (decoder.Decode(env, needle, enc).IsNothing()) return;
885
      const uint16_t* decoded_string =
886
          reinterpret_cast<const uint16_t*>(decoder.out());
887
888
      if (decoded_string == nullptr)
889
        return args.GetReturnValue().Set(-1);
890
891
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
892
                            haystack_length / 2,
893
                            decoded_string,
894
                            decoder.size() / 2,
895
                            offset / 2,
896
                            is_forward);
897
    } else {
898
89
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
899
                            haystack_length / 2,
900
89
                            reinterpret_cast<const uint16_t*>(*needle_value),
901
89
                            needle_value.length(),
902
                            offset / 2,
903
                            is_forward);
904
    }
905
89
    result *= 2;
906
772
  } else if (enc == UTF8) {
907
760
    String::Utf8Value needle_value(isolate, needle);
908
760
    if (*needle_value == nullptr)
909
      return args.GetReturnValue().Set(-1);
910
911
760
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
912
                          haystack_length,
913
760
                          reinterpret_cast<const uint8_t*>(*needle_value),
914
                          needle_length,
915
                          offset,
916
                          is_forward);
917
12
  } else if (enc == LATIN1) {
918
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
919
12
    if (needle_data == nullptr) {
920
      return args.GetReturnValue().Set(-1);
921
    }
922
12
    needle->WriteOneByte(
923
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
924
925
12
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
926
                          haystack_length,
927
                          needle_data,
928
                          needle_length,
929
                          offset,
930
                          is_forward);
931
12
    free(needle_data);
932
  }
933
934
1722
  args.GetReturnValue().Set(
935
861
      result == haystack_length ? -1 : static_cast<int>(result));
936
}
937
938
220
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
939
220
  CHECK(args[1]->IsObject());
940
220
  CHECK(args[2]->IsNumber());
941
220
  CHECK(args[3]->IsInt32());
942
220
  CHECK(args[4]->IsBoolean());
943
944
440
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
945
946
250
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
947
220
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
948
220
  ArrayBufferViewContents<char> haystack_contents(args[0]);
949
220
  ArrayBufferViewContents<char> needle_contents(args[1]);
950
440
  int64_t offset_i64 = args[2].As<Integer>()->Value();
951
220
  bool is_forward = args[4]->IsTrue();
952
953
220
  const char* haystack = haystack_contents.data();
954
220
  const size_t haystack_length = haystack_contents.length();
955
220
  const char* needle = needle_contents.data();
956
220
  const size_t needle_length = needle_contents.length();
957
958
220
  int64_t opt_offset = IndexOfOffset(haystack_length,
959
                                     offset_i64,
960
                                     needle_length,
961
                                     is_forward);
962
963
220
  if (needle_length == 0) {
964
    // Match String#indexOf() and String#lastIndexOf() behavior.
965
12
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
966
12
    return;
967
  }
968
969
208
  if (haystack_length == 0) {
970
    return args.GetReturnValue().Set(-1);
971
  }
972
973
208
  if (opt_offset <= -1) {
974
18
    return args.GetReturnValue().Set(-1);
975
  }
976
199
  size_t offset = static_cast<size_t>(opt_offset);
977
199
  CHECK_LT(offset, haystack_length);
978

199
  if ((is_forward && needle_length + offset > haystack_length) ||
979
197
      needle_length > haystack_length) {
980
14
    return args.GetReturnValue().Set(-1);
981
  }
982
983
192
  size_t result = haystack_length;
984
985
192
  if (enc == UCS2) {
986

59
    if (haystack_length < 2 || needle_length < 2) {
987
4
      return args.GetReturnValue().Set(-1);
988
    }
989
57
    result = SearchString(
990
        reinterpret_cast<const uint16_t*>(haystack),
991
        haystack_length / 2,
992
        reinterpret_cast<const uint16_t*>(needle),
993
        needle_length / 2,
994
        offset / 2,
995
        is_forward);
996
57
    result *= 2;
997
  } else {
998
133
    result = SearchString(
999
        reinterpret_cast<const uint8_t*>(haystack),
1000
        haystack_length,
1001
        reinterpret_cast<const uint8_t*>(needle),
1002
        needle_length,
1003
        offset,
1004
        is_forward);
1005
  }
1006
1007
380
  args.GetReturnValue().Set(
1008
190
      result == haystack_length ? -1 : static_cast<int>(result));
1009
}
1010
1011
50
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1012
50
  CHECK(args[1]->IsUint32());
1013
50
  CHECK(args[2]->IsNumber());
1014
50
  CHECK(args[3]->IsBoolean());
1015
1016
54
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1017
50
  ArrayBufferViewContents<char> buffer(args[0]);
1018
1019
100
  uint32_t needle = args[1].As<Uint32>()->Value();
1020
100
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1021
50
  bool is_forward = args[3]->IsTrue();
1022
1023
  int64_t opt_offset =
1024
50
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1025

50
  if (opt_offset <= -1 || buffer.length() == 0) {
1026
8
    return args.GetReturnValue().Set(-1);
1027
  }
1028
46
  size_t offset = static_cast<size_t>(opt_offset);
1029
46
  CHECK_LT(offset, buffer.length());
1030
1031
  const void* ptr;
1032
46
  if (is_forward) {
1033
38
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1034
  } else {
1035
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1036
  }
1037
46
  const char* ptr_char = static_cast<const char*>(ptr);
1038
92
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1039
                                : -1);
1040
}
1041
1042
1043
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1044
2
  Environment* env = Environment::GetCurrent(args);
1045
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1046

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1047
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1048
4
  args.GetReturnValue().Set(args[0]);
1049
}
1050
1051
1052
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1053
2
  Environment* env = Environment::GetCurrent(args);
1054
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1055

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1056
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1057
4
  args.GetReturnValue().Set(args[0]);
1058
}
1059
1060
1061
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1062
2
  Environment* env = Environment::GetCurrent(args);
1063
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1064

10
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1065
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1066
4
  args.GetReturnValue().Set(args[0]);
1067
}
1068
1069
1070
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1071
// Used in TextEncoder.prototype.encode.
1072
277
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1073
277
  Environment* env = Environment::GetCurrent(args);
1074
277
  Isolate* isolate = env->isolate();
1075
277
  CHECK_GE(args.Length(), 1);
1076
554
  CHECK(args[0]->IsString());
1077
1078
554
  Local<String> str = args[0].As<String>();
1079
277
  size_t length = str->Utf8Length(isolate);
1080
277
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, length);
1081
277
  str->WriteUtf8(isolate,
1082
                 buf.data(),
1083
                 -1,  // We are certain that `data` is sufficiently large
1084
                 nullptr,
1085
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1086
277
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1087
554
  args.GetReturnValue().Set(array);
1088
277
}
1089
1090
1091
87
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1092
87
  Environment* env = Environment::GetCurrent(args);
1093
87
  Isolate* isolate = env->isolate();
1094
87
  CHECK_GE(args.Length(), 3);
1095
174
  CHECK(args[0]->IsString());
1096
87
  CHECK(args[1]->IsUint8Array());
1097
87
  CHECK(args[2]->IsUint32Array());
1098
1099
174
  Local<String> source = args[0].As<String>();
1100
1101
174
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1102
87
  Local<ArrayBuffer> buf = dest->Buffer();
1103
  char* write_result =
1104
174
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1105
87
  size_t dest_length = dest->ByteLength();
1106
1107
  // results = [ read, written ]
1108
174
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1109
  uint32_t* results = reinterpret_cast<uint32_t*>(
1110
261
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1111
87
      result_arr->ByteOffset());
1112
1113
  int nchars;
1114
87
  int written = source->WriteUtf8(
1115
      isolate,
1116
      write_result,
1117
      dest_length,
1118
      &nchars,
1119
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1120
87
  results[0] = nchars;
1121
87
  results[1] = written;
1122
87
}
1123
1124
1125
615
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1126
615
  Environment* env = Environment::GetCurrent(args);
1127
1128
615
  CHECK(args[0]->IsObject());
1129
615
  Local<Object> proto = args[0].As<Object>();
1130
615
  env->set_buffer_prototype_object(proto);
1131
615
}
1132
1133
5465
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1134
5465
  Environment* env = Environment::GetCurrent(args);
1135
5465
  NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator();
1136
  Local<ArrayBuffer> ab;
1137
  // It can be a nullptr when running inside an isolate where we
1138
  // do not own the ArrayBuffer allocator.
1139
5465
  if (allocator == nullptr) {
1140
    // Create a dummy Uint32Array - the JS land can only toggle the C++ land
1141
    // setting when the allocator uses our toggle. With this the toggle in JS
1142
    // land results in no-ops.
1143
62
    ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1144
  } else {
1145
5403
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1146
    std::unique_ptr<BackingStore> backing =
1147
        ArrayBuffer::NewBackingStore(zero_fill_field,
1148
                                     sizeof(*zero_fill_field),
1149
4922
                                     [](void*, size_t, void*) {},
1150
5403
                                     nullptr);
1151
5403
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1152
  }
1153
1154
10930
  ab->SetPrivate(
1155
      env->context(),
1156
      env->untransferable_object_private_symbol(),
1157
16395
      True(env->isolate())).Check();
1158
1159
5465
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1160
5465
}
1161
1162
670
void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1163
670
  Environment* env = Environment::GetCurrent(args);
1164
670
  if (args[0]->IsArrayBuffer()) {
1165
1340
    Local<ArrayBuffer> buf = args[0].As<ArrayBuffer>();
1166
670
    if (buf->IsDetachable()) {
1167
667
      std::shared_ptr<BackingStore> store = buf->GetBackingStore();
1168
667
      buf->Detach();
1169
1334
      args.GetReturnValue().Set(ArrayBuffer::New(env->isolate(), store));
1170
    }
1171
  }
1172
670
}
1173
1174
171
void CopyArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1175
  // args[0] == Destination ArrayBuffer
1176
  // args[1] == Destination ArrayBuffer Offset
1177
  // args[2] == Source ArrayBuffer
1178
  // args[3] == Source ArrayBuffer Offset
1179
  // args[4] == bytesToCopy
1180
1181

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

171
  CHECK(args[2]->IsArrayBuffer() || args[2]->IsSharedArrayBuffer());
1184
171
  CHECK(args[3]->IsUint32());
1185
171
  CHECK(args[4]->IsUint32());
1186
1187
171
  std::shared_ptr<BackingStore> destination;
1188
171
  std::shared_ptr<BackingStore> source;
1189
1190
171
  if (args[0]->IsArrayBuffer()) {
1191
342
    destination = args[0].As<ArrayBuffer>()->GetBackingStore();
1192
  } else if (args[0]->IsSharedArrayBuffer()) {
1193
    destination = args[0].As<SharedArrayBuffer>()->GetBackingStore();
1194
  }
1195
1196
171
  if (args[2]->IsArrayBuffer()) {
1197
342
    source = args[2].As<ArrayBuffer>()->GetBackingStore();
1198
  } else if (args[0]->IsSharedArrayBuffer()) {
1199
    source = args[2].As<SharedArrayBuffer>()->GetBackingStore();
1200
  }
1201
1202
342
  uint32_t destination_offset = args[1].As<Uint32>()->Value();
1203
342
  uint32_t source_offset = args[3].As<Uint32>()->Value();
1204
342
  size_t bytes_to_copy = args[4].As<Uint32>()->Value();
1205
1206
171
  CHECK_GE(destination->ByteLength() - destination_offset, bytes_to_copy);
1207
171
  CHECK_GE(source->ByteLength() - source_offset, bytes_to_copy);
1208
1209
  uint8_t* dest =
1210
171
      static_cast<uint8_t*>(destination->Data()) + destination_offset;
1211
  uint8_t* src =
1212
171
      static_cast<uint8_t*>(source->Data()) + source_offset;
1213
171
  memcpy(dest, src, bytes_to_copy);
1214
171
}
1215
1216
615
void Initialize(Local<Object> target,
1217
                Local<Value> unused,
1218
                Local<Context> context,
1219
                void* priv) {
1220
615
  Environment* env = Environment::GetCurrent(context);
1221
1222
615
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1223
615
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1224
1225
615
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1226
615
  env->SetMethod(target, "copy", Copy);
1227
615
  env->SetMethodNoSideEffect(target, "compare", Compare);
1228
615
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1229
615
  env->SetMethod(target, "fill", Fill);
1230
615
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1231
615
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1232
615
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1233
1234
615
  env->SetMethod(target, "detachArrayBuffer", DetachArrayBuffer);
1235
615
  env->SetMethod(target, "copyArrayBuffer", CopyArrayBuffer);
1236
1237
615
  env->SetMethod(target, "swap16", Swap16);
1238
615
  env->SetMethod(target, "swap32", Swap32);
1239
615
  env->SetMethod(target, "swap64", Swap64);
1240
1241
615
  env->SetMethod(target, "encodeInto", EncodeInto);
1242
615
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1243
1244
615
  target->Set(env->context(),
1245
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1246
2460
              Number::New(env->isolate(), kMaxLength)).Check();
1247
1248
615
  target->Set(env->context(),
1249
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1250
1845
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1251
1252
615
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1253
615
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1254
615
  env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>);
1255
615
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1256
615
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1257
615
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1258
615
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1259
1260
615
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1261
615
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1262
615
  env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>);
1263
615
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1264
615
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1265
615
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1266
615
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1267
1268
615
  env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle);
1269
615
}
1270
1271
}  // anonymous namespace
1272
1273
4833
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1274
4833
  registry->Register(SetBufferPrototype);
1275
4833
  registry->Register(CreateFromString);
1276
1277
4833
  registry->Register(ByteLengthUtf8);
1278
4833
  registry->Register(Copy);
1279
4833
  registry->Register(Compare);
1280
4833
  registry->Register(CompareOffset);
1281
4833
  registry->Register(Fill);
1282
4833
  registry->Register(IndexOfBuffer);
1283
4833
  registry->Register(IndexOfNumber);
1284
4833
  registry->Register(IndexOfString);
1285
1286
4833
  registry->Register(Swap16);
1287
4833
  registry->Register(Swap32);
1288
4833
  registry->Register(Swap64);
1289
1290
4833
  registry->Register(EncodeInto);
1291
4833
  registry->Register(EncodeUtf8String);
1292
1293
4833
  registry->Register(StringSlice<ASCII>);
1294
4833
  registry->Register(StringSlice<BASE64>);
1295
4833
  registry->Register(StringSlice<BASE64URL>);
1296
4833
  registry->Register(StringSlice<LATIN1>);
1297
4833
  registry->Register(StringSlice<HEX>);
1298
4833
  registry->Register(StringSlice<UCS2>);
1299
4833
  registry->Register(StringSlice<UTF8>);
1300
1301
4833
  registry->Register(StringWrite<ASCII>);
1302
4833
  registry->Register(StringWrite<BASE64>);
1303
4833
  registry->Register(StringWrite<BASE64URL>);
1304
4833
  registry->Register(StringWrite<LATIN1>);
1305
4833
  registry->Register(StringWrite<HEX>);
1306
4833
  registry->Register(StringWrite<UCS2>);
1307
4833
  registry->Register(StringWrite<UTF8>);
1308
4833
  registry->Register(GetZeroFillToggle);
1309
1310
4833
  registry->Register(DetachArrayBuffer);
1311
4833
  registry->Register(CopyArrayBuffer);
1312
4833
}
1313
1314
}  // namespace Buffer
1315
}  // namespace node
1316
1317
4906
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1318
4833
NODE_MODULE_EXTERNAL_REFERENCE(buffer, node::Buffer::RegisterExternalReferences)