GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_buffer.cc Lines: 650 725 89.7 %
Date: 2022-11-20 04:28:36 Branches: 327 544 60.1 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_buffer.h"
23
#include "node.h"
24
#include "node_blob.h"
25
#include "node_errors.h"
26
#include "node_external_reference.h"
27
#include "node_i18n.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
30
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
110
    Environment* env,
111
    char* data,
112
    size_t length,
113
    FreeCallback callback,
114
    void* hint) {
115
30
  CHECK_NOT_NULL(callback);
116

30
  CHECK_IMPLIES(data == nullptr, length == 0);
117
118
30
  CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
119
  std::unique_ptr<BackingStore> bs =
120
28
      ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
121
28
        static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
122
30
      }, self);
123
30
  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
30
  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
28
    self->persistent_.Reset(env->isolate(), ab);
133
28
    self->persistent_.SetWeak();
134
  }
135
136
30
  return ab;
137
}
138
139
140
30
CallbackInfo::CallbackInfo(Environment* env,
141
                           FreeCallback callback,
142
                           char* data,
143
30
                           void* hint)
144
    : callback_(callback),
145
      data_(data),
146
      hint_(hint),
147
60
      env_(env) {
148
30
  env->AddCleanupHook(CleanupHook, this);
149
30
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
150
30
}
151
152
9
void CallbackInfo::CleanupHook(void* data) {
153
9
  CallbackInfo* self = static_cast<CallbackInfo*>(data);
154
155
  {
156
18
    HandleScope handle_scope(self->env_->isolate());
157
18
    Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
158

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

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

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

549460
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
551
274730
  size_t length = end - start;
552
553
  Local<Value> error;
554
  MaybeLocal<Value> maybe_ret =
555
274730
      StringBytes::Encode(isolate,
556
274730
                          buffer.data() + start,
557
                          length,
558
                          encoding,
559
                          &error);
560
  Local<Value> ret;
561
274730
  if (!maybe_ret.ToLocal(&ret)) {
562
14
    CHECK(!error.IsEmpty());
563
14
    isolate->ThrowException(error);
564
14
    return;
565
  }
566
549432
  args.GetReturnValue().Set(ret);
567
}
568
569
// Convert the input into an encoded string
570
867
void DecodeUTF8(const FunctionCallbackInfo<Value>& args) {
571
867
  Environment* env = Environment::GetCurrent(args);  // list, flags
572
573

2536
  if (!(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer() ||
574

1701
        args[0]->IsArrayBufferView())) {
575
5
    return node::THROW_ERR_INVALID_ARG_TYPE(
576
        env->isolate(),
577
        "The \"list\" argument must be an instance of SharedArrayBuffer, "
578
36
        "ArrayBuffer or ArrayBufferView.");
579
  }
580
581
862
  ArrayBufferViewContents<char> buffer(args[0]);
582
583
862
  CHECK(args[1]->IsBoolean());
584
862
  bool ignore_bom = args[1]->IsTrue();
585
586
862
  const char* data = buffer.data();
587
862
  size_t length = buffer.length();
588
589

862
  if (!ignore_bom && length >= 3) {
590
820
    if (memcmp(data, "\xEF\xBB\xBF", 3) == 0) {
591
10
      data += 3;
592
10
      length -= 3;
593
    }
594
  }
595
596
924
  if (length == 0) return args.GetReturnValue().SetEmptyString();
597
598
  Local<Value> error;
599
  MaybeLocal<Value> maybe_ret =
600
831
      StringBytes::Encode(env->isolate(), data, length, UTF8, &error);
601
  Local<Value> ret;
602
603
831
  if (!maybe_ret.ToLocal(&ret)) {
604
    CHECK(!error.IsEmpty());
605
    env->isolate()->ThrowException(error);
606
    return;
607
  }
608
609
1662
  args.GetReturnValue().Set(ret);
610
}
611
612
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
613
82
void Copy(const FunctionCallbackInfo<Value> &args) {
614
82
  Environment* env = Environment::GetCurrent(args);
615
616
82
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
617
82
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
618
82
  ArrayBufferViewContents<char> source(args[0]);
619
164
  Local<Object> target_obj = args[1].As<Object>();
620

410
  SPREAD_BUFFER_ARG(target_obj, target);
621
622
82
  size_t target_start = 0;
623
82
  size_t source_start = 0;
624
82
  size_t source_end = 0;
625
626

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

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

328
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
629
                                          &source_end));
630
631
  // Copy 0 bytes; we're done
632

82
  if (target_start >= target_length || source_start >= source_end)
633
    return args.GetReturnValue().Set(0);
634
635
82
  if (source_start > source.length())
636
    return THROW_ERR_OUT_OF_RANGE(
637
        env, "The value of \"sourceStart\" is out of range.");
638
639
82
  if (source_end - source_start > target_length - target_start)
640
    source_end = source_start + target_length - target_start;
641
642
82
  uint32_t to_copy = std::min(
643
164
      std::min(source_end - source_start, target_length - target_start),
644
82
      source.length() - source_start);
645
646
82
  memmove(target_data + target_start, source.data() + source_start, to_copy);
647
164
  args.GetReturnValue().Set(to_copy);
648
}
649
650
651
177
void Fill(const FunctionCallbackInfo<Value>& args) {
652
177
  Environment* env = Environment::GetCurrent(args);
653
177
  Local<Context> ctx = env->context();
654
655
198
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
656

1062
  SPREAD_BUFFER_ARG(args[0], ts_obj);
657
658
177
  size_t start = 0;
659

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

528
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
662
663
175
  size_t fill_length = end - start;
664
  Local<String> str_obj;
665
  size_t str_length;
666
  enum encoding enc;
667
668
  // OOB Check. Throw the error in JS.
669

175
  if (start > end || fill_length + start > ts_obj_length)
670
    return args.GetReturnValue().Set(-2);
671
672
  // First check if Buffer has been passed.
673
175
  if (Buffer::HasInstance(args[1])) {
674

42
    SPREAD_BUFFER_ARG(args[1], fill_obj);
675
7
    str_length = fill_obj_length;
676
14
    memcpy(
677
7
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
678
7
    goto start_fill;
679
  }
680
681
  // Then coerce everything that's not a string.
682
336
  if (!args[1]->IsString()) {
683
    uint32_t val;
684
6
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
685
3
    int value = val & 255;
686
3
    memset(ts_obj_data + start, value, fill_length);
687
3
    return;
688
  }
689
690
330
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
691
165
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
692
693
  // Can't use StringBytes::Write() in all cases. For example if attempting
694
  // to write a two byte character into a one byte Buffer.
695
165
  if (enc == UTF8) {
696
49
    str_length = str_obj->Utf8Length(env->isolate());
697
49
    node::Utf8Value str(env->isolate(), args[1]);
698
49
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
699
700
116
  } else if (enc == UCS2) {
701
23
    str_length = str_obj->Length() * sizeof(uint16_t);
702
23
    node::TwoByteValue str(env->isolate(), args[1]);
703
23
    if (IsBigEndian())
704
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
705
706
23
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
707
708
  } else {
709
    // Write initial String to Buffer, then use that memory to copy remainder
710
    // of string. Correct the string length for cases like HEX where less than
711
    // the total string length is written.
712
93
    str_length = StringBytes::Write(
713
93
        env->isolate(), ts_obj_data + start, fill_length, str_obj, enc);
714
  }
715
716
172
start_fill:
717
718
172
  if (str_length >= fill_length)
719
10
    return;
720
721
  // If str_length is zero, then either an empty buffer was provided, or Write()
722
  // indicated that no bytes could be written. If no bytes could be written,
723
  // then return -1 because the fill value is invalid. This will trigger a throw
724
  // in JavaScript. Silently failing should be avoided because it can lead to
725
  // buffers with unexpected contents.
726
162
  if (str_length == 0)
727
12
    return args.GetReturnValue().Set(-1);
728
729
156
  size_t in_there = str_length;
730
156
  char* ptr = ts_obj_data + start + str_length;
731
732
445
  while (in_there < fill_length - in_there) {
733
289
    memcpy(ptr, ts_obj_data + start, in_there);
734
289
    ptr += in_there;
735
289
    in_there *= 2;
736
  }
737
738
156
  if (in_there < fill_length) {
739
156
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
740
  }
741
}
742
743
744
template <encoding encoding>
745
373428
void StringWrite(const FunctionCallbackInfo<Value>& args) {
746
373428
  Environment* env = Environment::GetCurrent(args);
747
748
373440
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
749

2240568
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
750
751
746856
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
752
753
373428
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
754
755
373428
  size_t offset = 0;
756
373428
  size_t max_length = 0;
757
758

1120284
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
759
373428
  if (offset > ts_obj_length) {
760
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
761
        env, "\"offset\" is outside of buffer bounds");
762
  }
763
764

1493712
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
765
                                          &max_length));
766
767
373428
  max_length = std::min(ts_obj_length - offset, max_length);
768
769
373428
  if (max_length == 0)
770
24
    return args.GetReturnValue().Set(0);
771
772
373416
  uint32_t written = StringBytes::Write(
773
373416
      env->isolate(), ts_obj_data + offset, max_length, str, encoding);
774
746832
  args.GetReturnValue().Set(written);
775
}
776
777
193197
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
778
193197
  Environment* env = Environment::GetCurrent(args);
779
386394
  CHECK(args[0]->IsString());
780
781
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
782
579591
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
783
193197
}
784
785
// Normalize val to be an integer in the range of [1, -1] since
786
// implementations of memcmp() can vary by platform.
787
3651
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
788
3651
  if (val == 0) {
789
3624
    if (a_length > b_length)
790
6
      return 1;
791
3618
    else if (a_length < b_length)
792
5
      return -1;
793
  } else {
794
27
    if (val > 0)
795
7
      return 1;
796
    else
797
20
      return -1;
798
  }
799
3613
  return val;
800
}
801
802
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
803
9
  Environment* env = Environment::GetCurrent(args);
804
805
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
806
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
807
9
  ArrayBufferViewContents<char> source(args[0]);
808
9
  ArrayBufferViewContents<char> target(args[1]);
809
810
9
  size_t target_start = 0;
811
9
  size_t source_start = 0;
812
9
  size_t source_end = 0;
813
9
  size_t target_end = 0;
814
815

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

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

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

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
820
                                          &source_end));
821
822
9
  if (source_start > source.length())
823
    return THROW_ERR_OUT_OF_RANGE(
824
        env, "The value of \"sourceStart\" is out of range.");
825
9
  if (target_start > target.length())
826
    return THROW_ERR_OUT_OF_RANGE(
827
        env, "The value of \"targetStart\" is out of range.");
828
829
9
  CHECK_LE(source_start, source_end);
830
9
  CHECK_LE(target_start, target_end);
831
832
  size_t to_cmp =
833
18
      std::min(std::min(source_end - source_start, target_end - target_start),
834
9
               source.length() - source_start);
835
836
18
  int val = normalizeCompareVal(to_cmp > 0 ?
837
9
                                  memcmp(source.data() + source_start,
838
9
                                         target.data() + target_start,
839
                                         to_cmp) : 0,
840
                                source_end - source_start,
841
                                target_end - target_start);
842
843
18
  args.GetReturnValue().Set(val);
844
}
845
846
3642
void Compare(const FunctionCallbackInfo<Value> &args) {
847
3642
  Environment* env = Environment::GetCurrent(args);
848
849
3642
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
850
3642
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
851
3642
  ArrayBufferViewContents<char> a(args[0]);
852
3642
  ArrayBufferViewContents<char> b(args[1]);
853
854
3642
  size_t cmp_length = std::min(a.length(), b.length());
855
856
7218
  int val = normalizeCompareVal(cmp_length > 0 ?
857
3576
                                memcmp(a.data(), b.data(), cmp_length) : 0,
858
                                a.length(), b.length());
859
7284
  args.GetReturnValue().Set(val);
860
}
861
862
863
// Computes the offset for starting an indexOf or lastIndexOf search.
864
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
865
// or -1 to signal that there is no possible match.
866
1294
int64_t IndexOfOffset(size_t length,
867
                      int64_t offset_i64,
868
                      int64_t needle_length,
869
                      bool is_forward) {
870
1294
  int64_t length_i64 = static_cast<int64_t>(length);
871
1294
  if (offset_i64 < 0) {
872
81
    if (offset_i64 + length_i64 >= 0) {
873
      // Negative offsets count backwards from the end of the buffer.
874
63
      return length_i64 + offset_i64;
875

18
    } else if (is_forward || needle_length == 0) {
876
      // indexOf from before the start of the buffer: search the whole buffer.
877
10
      return 0;
878
    } else {
879
      // lastIndexOf from before the start of the buffer: no match.
880
8
      return -1;
881
    }
882
  } else {
883
1213
    if (offset_i64 + needle_length <= length_i64) {
884
      // Valid positive offset.
885
1125
      return offset_i64;
886
88
    } else if (needle_length == 0) {
887
      // Out of buffer bounds, but empty needle: point to end of buffer.
888
10
      return length_i64;
889
78
    } else if (is_forward) {
890
      // indexOf from past the end of the buffer: no match.
891
15
      return -1;
892
    } else {
893
      // lastIndexOf from past the end of the buffer: search the whole buffer.
894
63
      return length_i64 - 1;
895
    }
896
  }
897
}
898
899
1024
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
900
1024
  Environment* env = Environment::GetCurrent(args);
901
1024
  Isolate* isolate = env->isolate();
902
903
2048
  CHECK(args[1]->IsString());
904
1024
  CHECK(args[2]->IsNumber());
905
1024
  CHECK(args[3]->IsInt32());
906
1024
  CHECK(args[4]->IsBoolean());
907
908
2048
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
909
910
1057
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
911
1024
  ArrayBufferViewContents<char> buffer(args[0]);
912
913
2048
  Local<String> needle = args[1].As<String>();
914
2048
  int64_t offset_i64 = args[2].As<Integer>()->Value();
915
1024
  bool is_forward = args[4]->IsTrue();
916
917
1024
  const char* haystack = buffer.data();
918
  // Round down to the nearest multiple of 2 in case of UCS2.
919
1118
  const size_t haystack_length = (enc == UCS2) ?
920
1118
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
921
922
  size_t needle_length;
923
2048
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
924
925
1024
  int64_t opt_offset = IndexOfOffset(haystack_length,
926
                                     offset_i64,
927
                                     needle_length,
928
                                     is_forward);
929
930
1024
  if (needle_length == 0) {
931
    // Match String#indexOf() and String#lastIndexOf() behavior.
932
8
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
933
8
    return;
934
  }
935
936
1016
  if (haystack_length == 0) {
937
    return args.GetReturnValue().Set(-1);
938
  }
939
940
1016
  if (opt_offset <= -1) {
941
20
    return args.GetReturnValue().Set(-1);
942
  }
943
1006
  size_t offset = static_cast<size_t>(opt_offset);
944
1006
  CHECK_LT(offset, haystack_length);
945

1006
  if ((is_forward && needle_length + offset > haystack_length) ||
946
1004
      needle_length > haystack_length) {
947
30
    return args.GetReturnValue().Set(-1);
948
  }
949
950
991
  size_t result = haystack_length;
951
952
991
  if (enc == UCS2) {
953
89
    String::Value needle_value(isolate, needle);
954
89
    if (*needle_value == nullptr)
955
      return args.GetReturnValue().Set(-1);
956
957

89
    if (haystack_length < 2 || needle_value.length() < 1) {
958
      return args.GetReturnValue().Set(-1);
959
    }
960
961
89
    if (IsBigEndian()) {
962
      StringBytes::InlineDecoder decoder;
963
      if (decoder.Decode(env, needle, enc).IsNothing()) return;
964
      const uint16_t* decoded_string =
965
          reinterpret_cast<const uint16_t*>(decoder.out());
966
967
      if (decoded_string == nullptr)
968
        return args.GetReturnValue().Set(-1);
969
970
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
971
                            haystack_length / 2,
972
                            decoded_string,
973
                            decoder.size() / 2,
974
                            offset / 2,
975
                            is_forward);
976
    } else {
977
89
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
978
                            haystack_length / 2,
979
89
                            reinterpret_cast<const uint16_t*>(*needle_value),
980
89
                            needle_value.length(),
981
                            offset / 2,
982
                            is_forward);
983
    }
984
89
    result *= 2;
985
902
  } else if (enc == UTF8) {
986
890
    String::Utf8Value needle_value(isolate, needle);
987
890
    if (*needle_value == nullptr)
988
      return args.GetReturnValue().Set(-1);
989
990
890
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
991
                          haystack_length,
992
890
                          reinterpret_cast<const uint8_t*>(*needle_value),
993
                          needle_length,
994
                          offset,
995
                          is_forward);
996
12
  } else if (enc == LATIN1) {
997
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
998
12
    if (needle_data == nullptr) {
999
      return args.GetReturnValue().Set(-1);
1000
    }
1001
12
    needle->WriteOneByte(
1002
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
1003
1004
12
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
1005
                          haystack_length,
1006
                          needle_data,
1007
                          needle_length,
1008
                          offset,
1009
                          is_forward);
1010
12
    free(needle_data);
1011
  }
1012
1013
1982
  args.GetReturnValue().Set(
1014
991
      result == haystack_length ? -1 : static_cast<int>(result));
1015
}
1016
1017
220
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
1018
220
  CHECK(args[1]->IsObject());
1019
220
  CHECK(args[2]->IsNumber());
1020
220
  CHECK(args[3]->IsInt32());
1021
220
  CHECK(args[4]->IsBoolean());
1022
1023
440
  enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
1024
1025
250
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1026
220
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
1027
220
  ArrayBufferViewContents<char> haystack_contents(args[0]);
1028
220
  ArrayBufferViewContents<char> needle_contents(args[1]);
1029
440
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1030
220
  bool is_forward = args[4]->IsTrue();
1031
1032
220
  const char* haystack = haystack_contents.data();
1033
220
  const size_t haystack_length = haystack_contents.length();
1034
220
  const char* needle = needle_contents.data();
1035
220
  const size_t needle_length = needle_contents.length();
1036
1037
220
  int64_t opt_offset = IndexOfOffset(haystack_length,
1038
                                     offset_i64,
1039
                                     needle_length,
1040
                                     is_forward);
1041
1042
220
  if (needle_length == 0) {
1043
    // Match String#indexOf() and String#lastIndexOf() behavior.
1044
12
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
1045
12
    return;
1046
  }
1047
1048
208
  if (haystack_length == 0) {
1049
    return args.GetReturnValue().Set(-1);
1050
  }
1051
1052
208
  if (opt_offset <= -1) {
1053
18
    return args.GetReturnValue().Set(-1);
1054
  }
1055
199
  size_t offset = static_cast<size_t>(opt_offset);
1056
199
  CHECK_LT(offset, haystack_length);
1057

199
  if ((is_forward && needle_length + offset > haystack_length) ||
1058
197
      needle_length > haystack_length) {
1059
14
    return args.GetReturnValue().Set(-1);
1060
  }
1061
1062
192
  size_t result = haystack_length;
1063
1064
192
  if (enc == UCS2) {
1065

59
    if (haystack_length < 2 || needle_length < 2) {
1066
4
      return args.GetReturnValue().Set(-1);
1067
    }
1068
57
    result = SearchString(
1069
        reinterpret_cast<const uint16_t*>(haystack),
1070
        haystack_length / 2,
1071
        reinterpret_cast<const uint16_t*>(needle),
1072
        needle_length / 2,
1073
        offset / 2,
1074
        is_forward);
1075
57
    result *= 2;
1076
  } else {
1077
133
    result = SearchString(
1078
        reinterpret_cast<const uint8_t*>(haystack),
1079
        haystack_length,
1080
        reinterpret_cast<const uint8_t*>(needle),
1081
        needle_length,
1082
        offset,
1083
        is_forward);
1084
  }
1085
1086
380
  args.GetReturnValue().Set(
1087
190
      result == haystack_length ? -1 : static_cast<int>(result));
1088
}
1089
1090
50
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1091
50
  CHECK(args[1]->IsUint32());
1092
50
  CHECK(args[2]->IsNumber());
1093
50
  CHECK(args[3]->IsBoolean());
1094
1095
54
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1096
50
  ArrayBufferViewContents<char> buffer(args[0]);
1097
1098
100
  uint32_t needle = args[1].As<Uint32>()->Value();
1099
100
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1100
50
  bool is_forward = args[3]->IsTrue();
1101
1102
  int64_t opt_offset =
1103
50
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1104

50
  if (opt_offset <= -1 || buffer.length() == 0) {
1105
8
    return args.GetReturnValue().Set(-1);
1106
  }
1107
46
  size_t offset = static_cast<size_t>(opt_offset);
1108
46
  CHECK_LT(offset, buffer.length());
1109
1110
  const void* ptr;
1111
46
  if (is_forward) {
1112
38
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1113
  } else {
1114
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1115
  }
1116
46
  const char* ptr_char = static_cast<const char*>(ptr);
1117
92
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1118
                                : -1);
1119
}
1120
1121
1122
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1123
2
  Environment* env = Environment::GetCurrent(args);
1124
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1125

12
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1126
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1127
4
  args.GetReturnValue().Set(args[0]);
1128
}
1129
1130
1131
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1132
2
  Environment* env = Environment::GetCurrent(args);
1133
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1134

12
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1135
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1136
4
  args.GetReturnValue().Set(args[0]);
1137
}
1138
1139
1140
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1141
2
  Environment* env = Environment::GetCurrent(args);
1142
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1143

12
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1144
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1145
4
  args.GetReturnValue().Set(args[0]);
1146
}
1147
1148
1149
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1150
// Used in TextEncoder.prototype.encode.
1151
465
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1152
465
  Environment* env = Environment::GetCurrent(args);
1153
465
  Isolate* isolate = env->isolate();
1154
465
  CHECK_GE(args.Length(), 1);
1155
930
  CHECK(args[0]->IsString());
1156
1157
930
  Local<String> str = args[0].As<String>();
1158
465
  size_t length = str->Utf8Length(isolate);
1159
1160
  Local<ArrayBuffer> ab;
1161
  {
1162
930
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1163
    std::unique_ptr<BackingStore> bs =
1164
465
        ArrayBuffer::NewBackingStore(isolate, length);
1165
1166
465
    CHECK(bs);
1167
1168
465
    str->WriteUtf8(isolate,
1169
465
                   static_cast<char*>(bs->Data()),
1170
                   -1,  // We are certain that `data` is sufficiently large
1171
                   nullptr,
1172
                   String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1173
1174
465
    ab = ArrayBuffer::New(isolate, std::move(bs));
1175
  }
1176
1177
465
  auto array = Uint8Array::New(ab, 0, length);
1178
465
  args.GetReturnValue().Set(array);
1179
465
}
1180
1181
1182
87
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1183
87
  Environment* env = Environment::GetCurrent(args);
1184
87
  Isolate* isolate = env->isolate();
1185
87
  CHECK_GE(args.Length(), 3);
1186
174
  CHECK(args[0]->IsString());
1187
87
  CHECK(args[1]->IsUint8Array());
1188
87
  CHECK(args[2]->IsUint32Array());
1189
1190
174
  Local<String> source = args[0].As<String>();
1191
1192
174
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1193
87
  Local<ArrayBuffer> buf = dest->Buffer();
1194
174
  char* write_result = static_cast<char*>(buf->Data()) + dest->ByteOffset();
1195
87
  size_t dest_length = dest->ByteLength();
1196
1197
  // results = [ read, written ]
1198
174
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1199
  uint32_t* results = reinterpret_cast<uint32_t*>(
1200
174
      static_cast<char*>(result_arr->Buffer()->Data()) +
1201
87
      result_arr->ByteOffset());
1202
1203
  int nchars;
1204
87
  int written = source->WriteUtf8(
1205
      isolate,
1206
      write_result,
1207
      dest_length,
1208
      &nchars,
1209
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1210
87
  results[0] = nchars;
1211
87
  results[1] = written;
1212
87
}
1213
1214
1215
792
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1216
792
  Environment* env = Environment::GetCurrent(args);
1217
1218
792
  CHECK(args[0]->IsObject());
1219
792
  Local<Object> proto = args[0].As<Object>();
1220
792
  env->set_buffer_prototype_object(proto);
1221
792
}
1222
1223
7160
void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1224
7160
  Environment* env = Environment::GetCurrent(args);
1225
7160
  NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator();
1226
  Local<ArrayBuffer> ab;
1227
  // It can be a nullptr when running inside an isolate where we
1228
  // do not own the ArrayBuffer allocator.
1229
7160
  if (allocator == nullptr) {
1230
    // Create a dummy Uint32Array - the JS land can only toggle the C++ land
1231
    // setting when the allocator uses our toggle. With this the toggle in JS
1232
    // land results in no-ops.
1233
71
    ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1234
  } else {
1235
7089
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1236
    std::unique_ptr<BackingStore> backing =
1237
        ArrayBuffer::NewBackingStore(zero_fill_field,
1238
                                     sizeof(*zero_fill_field),
1239
6482
                                     [](void*, size_t, void*) {},
1240
7089
                                     nullptr);
1241
7089
    ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1242
  }
1243
1244
14320
  ab->SetPrivate(
1245
      env->context(),
1246
      env->untransferable_object_private_symbol(),
1247
21480
      True(env->isolate())).Check();
1248
1249
7160
  args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1250
7160
}
1251
1252
964
void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1253
964
  Environment* env = Environment::GetCurrent(args);
1254
964
  if (args[0]->IsArrayBuffer()) {
1255
1928
    Local<ArrayBuffer> buf = args[0].As<ArrayBuffer>();
1256
964
    if (buf->IsDetachable()) {
1257
961
      std::shared_ptr<BackingStore> store = buf->GetBackingStore();
1258
961
      buf->Detach();
1259
1922
      args.GetReturnValue().Set(ArrayBuffer::New(env->isolate(), store));
1260
    }
1261
  }
1262
964
}
1263
1264
namespace {
1265
1266
388
std::pair<void*, size_t> DecomposeBufferToParts(Local<Value> buffer) {
1267
  void* pointer;
1268
  size_t byte_length;
1269
388
  if (buffer->IsArrayBuffer()) {
1270
388
    Local<ArrayBuffer> ab = buffer.As<ArrayBuffer>();
1271
388
    pointer = ab->Data();
1272
388
    byte_length = ab->ByteLength();
1273
  } else if (buffer->IsSharedArrayBuffer()) {
1274
    Local<SharedArrayBuffer> ab = buffer.As<SharedArrayBuffer>();
1275
    pointer = ab->Data();
1276
    byte_length = ab->ByteLength();
1277
  } else {
1278
    UNREACHABLE();  // Caller must validate.
1279
  }
1280
388
  return {pointer, byte_length};
1281
}
1282
1283
}  // namespace
1284
1285
194
void CopyArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1286
  // args[0] == Destination ArrayBuffer
1287
  // args[1] == Destination ArrayBuffer Offset
1288
  // args[2] == Source ArrayBuffer
1289
  // args[3] == Source ArrayBuffer Offset
1290
  // args[4] == bytesToCopy
1291
1292

194
  CHECK(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer());
1293
194
  CHECK(args[1]->IsUint32());
1294

194
  CHECK(args[2]->IsArrayBuffer() || args[2]->IsSharedArrayBuffer());
1295
194
  CHECK(args[3]->IsUint32());
1296
194
  CHECK(args[4]->IsUint32());
1297
1298
  void* destination;
1299
  size_t destination_byte_length;
1300
194
  std::tie(destination, destination_byte_length) =
1301
194
      DecomposeBufferToParts(args[0]);
1302
1303
  void* source;
1304
  size_t source_byte_length;
1305
194
  std::tie(source, source_byte_length) = DecomposeBufferToParts(args[2]);
1306
1307
388
  uint32_t destination_offset = args[1].As<Uint32>()->Value();
1308
388
  uint32_t source_offset = args[3].As<Uint32>()->Value();
1309
388
  size_t bytes_to_copy = args[4].As<Uint32>()->Value();
1310
1311
194
  CHECK_GE(destination_byte_length - destination_offset, bytes_to_copy);
1312
194
  CHECK_GE(source_byte_length - source_offset, bytes_to_copy);
1313
1314
194
  uint8_t* dest = static_cast<uint8_t*>(destination) + destination_offset;
1315
194
  uint8_t* src = static_cast<uint8_t*>(source) + source_offset;
1316
194
  memcpy(dest, src, bytes_to_copy);
1317
194
}
1318
1319
792
void Initialize(Local<Object> target,
1320
                Local<Value> unused,
1321
                Local<Context> context,
1322
                void* priv) {
1323
792
  Environment* env = Environment::GetCurrent(context);
1324
792
  Isolate* isolate = env->isolate();
1325
1326
792
  SetMethod(context, target, "setBufferPrototype", SetBufferPrototype);
1327
792
  SetMethodNoSideEffect(context, target, "createFromString", CreateFromString);
1328
792
  SetMethodNoSideEffect(context, target, "decodeUTF8", DecodeUTF8);
1329
1330
792
  SetMethodNoSideEffect(context, target, "byteLengthUtf8", ByteLengthUtf8);
1331
792
  SetMethod(context, target, "copy", Copy);
1332
792
  SetMethodNoSideEffect(context, target, "compare", Compare);
1333
792
  SetMethodNoSideEffect(context, target, "compareOffset", CompareOffset);
1334
792
  SetMethod(context, target, "fill", Fill);
1335
792
  SetMethodNoSideEffect(context, target, "indexOfBuffer", IndexOfBuffer);
1336
792
  SetMethodNoSideEffect(context, target, "indexOfNumber", IndexOfNumber);
1337
792
  SetMethodNoSideEffect(context, target, "indexOfString", IndexOfString);
1338
1339
792
  SetMethod(context, target, "detachArrayBuffer", DetachArrayBuffer);
1340
792
  SetMethod(context, target, "copyArrayBuffer", CopyArrayBuffer);
1341
1342
792
  SetMethod(context, target, "swap16", Swap16);
1343
792
  SetMethod(context, target, "swap32", Swap32);
1344
792
  SetMethod(context, target, "swap64", Swap64);
1345
1346
792
  SetMethod(context, target, "encodeInto", EncodeInto);
1347
792
  SetMethodNoSideEffect(context, target, "encodeUtf8String", EncodeUtf8String);
1348
1349
  target
1350
792
      ->Set(context,
1351
            FIXED_ONE_BYTE_STRING(isolate, "kMaxLength"),
1352
3168
            Number::New(isolate, kMaxLength))
1353
      .Check();
1354
1355
  target
1356
792
      ->Set(context,
1357
            FIXED_ONE_BYTE_STRING(isolate, "kStringMaxLength"),
1358
2376
            Integer::New(isolate, String::kMaxLength))
1359
      .Check();
1360
1361
792
  SetMethodNoSideEffect(context, target, "asciiSlice", StringSlice<ASCII>);
1362
792
  SetMethodNoSideEffect(context, target, "base64Slice", StringSlice<BASE64>);
1363
792
  SetMethodNoSideEffect(
1364
      context, target, "base64urlSlice", StringSlice<BASE64URL>);
1365
792
  SetMethodNoSideEffect(context, target, "latin1Slice", StringSlice<LATIN1>);
1366
792
  SetMethodNoSideEffect(context, target, "hexSlice", StringSlice<HEX>);
1367
792
  SetMethodNoSideEffect(context, target, "ucs2Slice", StringSlice<UCS2>);
1368
792
  SetMethodNoSideEffect(context, target, "utf8Slice", StringSlice<UTF8>);
1369
1370
792
  SetMethod(context, target, "asciiWrite", StringWrite<ASCII>);
1371
792
  SetMethod(context, target, "base64Write", StringWrite<BASE64>);
1372
792
  SetMethod(context, target, "base64urlWrite", StringWrite<BASE64URL>);
1373
792
  SetMethod(context, target, "latin1Write", StringWrite<LATIN1>);
1374
792
  SetMethod(context, target, "hexWrite", StringWrite<HEX>);
1375
792
  SetMethod(context, target, "ucs2Write", StringWrite<UCS2>);
1376
792
  SetMethod(context, target, "utf8Write", StringWrite<UTF8>);
1377
1378
792
  SetMethod(context, target, "getZeroFillToggle", GetZeroFillToggle);
1379
792
}
1380
1381
}  // anonymous namespace
1382
1383
5618
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1384
5618
  registry->Register(SetBufferPrototype);
1385
5618
  registry->Register(CreateFromString);
1386
5618
  registry->Register(DecodeUTF8);
1387
1388
5618
  registry->Register(ByteLengthUtf8);
1389
5618
  registry->Register(Copy);
1390
5618
  registry->Register(Compare);
1391
5618
  registry->Register(CompareOffset);
1392
5618
  registry->Register(Fill);
1393
5618
  registry->Register(IndexOfBuffer);
1394
5618
  registry->Register(IndexOfNumber);
1395
5618
  registry->Register(IndexOfString);
1396
1397
5618
  registry->Register(Swap16);
1398
5618
  registry->Register(Swap32);
1399
5618
  registry->Register(Swap64);
1400
1401
5618
  registry->Register(EncodeInto);
1402
5618
  registry->Register(EncodeUtf8String);
1403
1404
5618
  registry->Register(StringSlice<ASCII>);
1405
5618
  registry->Register(StringSlice<BASE64>);
1406
5618
  registry->Register(StringSlice<BASE64URL>);
1407
5618
  registry->Register(StringSlice<LATIN1>);
1408
5618
  registry->Register(StringSlice<HEX>);
1409
5618
  registry->Register(StringSlice<UCS2>);
1410
5618
  registry->Register(StringSlice<UTF8>);
1411
1412
5618
  registry->Register(StringWrite<ASCII>);
1413
5618
  registry->Register(StringWrite<BASE64>);
1414
5618
  registry->Register(StringWrite<BASE64URL>);
1415
5618
  registry->Register(StringWrite<LATIN1>);
1416
5618
  registry->Register(StringWrite<HEX>);
1417
5618
  registry->Register(StringWrite<UCS2>);
1418
5618
  registry->Register(StringWrite<UTF8>);
1419
5618
  registry->Register(GetZeroFillToggle);
1420
1421
5618
  registry->Register(DetachArrayBuffer);
1422
5618
  registry->Register(CopyArrayBuffer);
1423
5618
}
1424
1425
}  // namespace Buffer
1426
}  // namespace node
1427
1428
5689
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1429
5618
NODE_MODULE_EXTERNAL_REFERENCE(buffer, node::Buffer::RegisterExternalReferences)