GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_buffer.cc Lines: 558 620 90.0 %
Date: 2020-05-27 22:15:15 Branches: 406 680 59.7 %

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

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

18
    if (!ab.IsEmpty() && ab->IsDetachable()) {
154
9
      ab->Detach();
155
9
      self->persistent_.Reset();
156
    }
157
  }
158
159
  // Call the callback in this case, but don't delete `this` yet because the
160
  // BackingStore deleter callback will do so later.
161
9
  self->CallAndResetCallback();
162
9
}
163
164
37
void CallbackInfo::CallAndResetCallback() {
165
  FreeCallback callback;
166
  {
167
74
    Mutex::ScopedLock lock(mutex_);
168
37
    callback = callback_;
169
37
    callback_ = nullptr;
170
  }
171
37
  if (callback != nullptr) {
172
    // Clean up all Environment-related state and run the callback.
173
28
    env_->RemoveCleanupHook(CleanupHook, this);
174
28
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
175
28
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
176
177
28
    callback(data_, hint_);
178
  }
179
37
}
180
181
28
void CallbackInfo::OnBackingStoreFree() {
182
  // This method should always release the memory for `this`.
183
56
  std::unique_ptr<CallbackInfo> self { this };
184
56
  Mutex::ScopedLock lock(mutex_);
185
  // If callback_ == nullptr, that means that the callback has already run from
186
  // the cleanup hook, and there is nothing left to do here besides to clean
187
  // up the memory involved. In particular, the underlying `Environment` may
188
  // be gone at this point, so don’t attempt to call SetImmediateThreadsafe().
189
28
  if (callback_ == nullptr) return;
190
191
168
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
192
28
    CHECK_EQ(self->env_, env);  // Consistency check.
193
194
28
    self->CallAndResetCallback();
195
56
  });
196
}
197
198
199
// Parse index for external array data. An empty Maybe indicates
200
// a pending exception. `false` indicates that the index is out-of-bounds.
201
3510308
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
202
                                                   Local<Value> arg,
203
                                                   size_t def,
204
                                                   size_t* ret) {
205
7020616
  if (arg->IsUndefined()) {
206
    *ret = def;
207
    return Just(true);
208
  }
209
210
  int64_t tmp_i;
211
10530924
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
212
    return Nothing<bool>();
213
214
3510308
  if (tmp_i < 0)
215
4
    return Just(false);
216
217
  // Check that the result fits in a size_t.
218
3510304
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
219
  // coverity[pointless_expression]
220
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
221
    return Just(false);
222
223
3510304
  *ret = static_cast<size_t>(tmp_i);
224
3510304
  return Just(true);
225
}
226
227
}  // anonymous namespace
228
229
// Buffer methods
230
231
4753447
bool HasInstance(Local<Value> val) {
232
4753447
  return val->IsArrayBufferView();
233
}
234
235
236
877557
bool HasInstance(Local<Object> obj) {
237
877557
  return obj->IsArrayBufferView();
238
}
239
240
241
249828
char* Data(Local<Value> val) {
242
249828
  CHECK(val->IsArrayBufferView());
243
249828
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
244
749484
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
245
499656
      ui->ByteOffset();
246
}
247
248
249
121548
char* Data(Local<Object> obj) {
250
121548
  return Data(obj.As<Value>());
251
}
252
253
254
101865
size_t Length(Local<Value> val) {
255
101865
  CHECK(val->IsArrayBufferView());
256
101865
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
257
101865
  return ui->ByteLength();
258
}
259
260
261
120238
size_t Length(Local<Object> obj) {
262
120238
  CHECK(obj->IsArrayBufferView());
263
120238
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
264
120238
  return ui->ByteLength();
265
}
266
267
268
16262
MaybeLocal<Uint8Array> New(Environment* env,
269
                           Local<ArrayBuffer> ab,
270
                           size_t byte_offset,
271
                           size_t length) {
272
32525
  CHECK(!env->buffer_prototype_object().IsEmpty());
273
16263
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
274
  Maybe<bool> mb =
275
48788
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
276
16263
  if (mb.IsNothing())
277
    return MaybeLocal<Uint8Array>();
278
16263
  return ui;
279
}
280
281
MaybeLocal<Uint8Array> New(Isolate* isolate,
282
                           Local<ArrayBuffer> ab,
283
                           size_t byte_offset,
284
                           size_t length) {
285
  Environment* env = Environment::GetCurrent(isolate);
286
  if (env == nullptr) {
287
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
288
    return MaybeLocal<Uint8Array>();
289
  }
290
  return New(env, ab, byte_offset, length);
291
}
292
293
294
140
MaybeLocal<Object> New(Isolate* isolate,
295
                       Local<String> string,
296
                       enum encoding enc) {
297
140
  EscapableHandleScope scope(isolate);
298
299
  size_t length;
300
280
  if (!StringBytes::Size(isolate, string, enc).To(&length))
301
    return Local<Object>();
302
140
  size_t actual = 0;
303
140
  char* data = nullptr;
304
305
140
  if (length > 0) {
306
140
    data = UncheckedMalloc(length);
307
308
140
    if (data == nullptr) {
309
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
310
      return Local<Object>();
311
    }
312
313
140
    actual = StringBytes::Write(isolate, data, length, string, enc);
314
140
    CHECK(actual <= length);
315
316
140
    if (actual == 0) {
317
1
      free(data);
318
1
      data = nullptr;
319
139
    } else if (actual < length) {
320
      data = node::Realloc(data, actual);
321
    }
322
  }
323
324
280
  return scope.EscapeMaybe(New(isolate, data, actual));
325
}
326
327
328
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
329
1
  EscapableHandleScope handle_scope(isolate);
330
  Local<Object> obj;
331
1
  Environment* env = Environment::GetCurrent(isolate);
332
1
  if (env == nullptr) {
333
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
334
    return MaybeLocal<Object>();
335
  }
336
2
  if (Buffer::New(env, length).ToLocal(&obj))
337
1
    return handle_scope.Escape(obj);
338
  return Local<Object>();
339
}
340
341
342
1289
MaybeLocal<Object> New(Environment* env, size_t length) {
343
1289
  EscapableHandleScope scope(env->isolate());
344
345
  // V8 currently only allows a maximum Typed Array index of max Smi.
346
1289
  if (length > kMaxLength) {
347
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
348
    return Local<Object>();
349
  }
350
351
2578
  AllocatedBuffer ret(env);
352
1289
  if (length > 0) {
353
748
    ret = env->AllocateManaged(length, false);
354
748
    if (ret.data() == nullptr) {
355
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
356
      return Local<Object>();
357
    }
358
  }
359
360
2578
  return scope.EscapeMaybe(ret.ToBuffer());
361
}
362
363
364
2064
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
365
2064
  EscapableHandleScope handle_scope(isolate);
366
2064
  Environment* env = Environment::GetCurrent(isolate);
367
2064
  if (env == nullptr) {
368
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
369
1
    return MaybeLocal<Object>();
370
  }
371
  Local<Object> obj;
372
4126
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
373
2063
    return handle_scope.Escape(obj);
374
  return Local<Object>();
375
}
376
377
378
10779
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
379
10779
  EscapableHandleScope scope(env->isolate());
380
381
  // V8 currently only allows a maximum Typed Array index of max Smi.
382
10779
  if (length > kMaxLength) {
383
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
384
    return Local<Object>();
385
  }
386
387
21558
  AllocatedBuffer ret(env);
388
10779
  if (length > 0) {
389
10638
    CHECK_NOT_NULL(data);
390
10638
    ret = env->AllocateManaged(length, false);
391
10638
    if (ret.data() == nullptr) {
392
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
393
      return Local<Object>();
394
    }
395
10638
    memcpy(ret.data(), data, length);
396
  }
397
398
21558
  return scope.EscapeMaybe(ret.ToBuffer());
399
}
400
401
402
28
MaybeLocal<Object> New(Isolate* isolate,
403
                       char* data,
404
                       size_t length,
405
                       FreeCallback callback,
406
                       void* hint) {
407
28
  EscapableHandleScope handle_scope(isolate);
408
28
  Environment* env = Environment::GetCurrent(isolate);
409
28
  if (env == nullptr) {
410
    callback(data, hint);
411
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
412
    return MaybeLocal<Object>();
413
  }
414
  return handle_scope.EscapeMaybe(
415
56
      Buffer::New(env, data, length, callback, hint));
416
}
417
418
419
28
MaybeLocal<Object> New(Environment* env,
420
                       char* data,
421
                       size_t length,
422
                       FreeCallback callback,
423
                       void* hint) {
424
28
  EscapableHandleScope scope(env->isolate());
425
426
28
  if (length > kMaxLength) {
427
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
428
    callback(data, hint);
429
    return Local<Object>();
430
  }
431
432
  Local<ArrayBuffer> ab =
433
28
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
434
84
  if (ab->SetPrivate(env->context(),
435
                     env->arraybuffer_untransferable_private_symbol(),
436
84
                     True(env->isolate())).IsNothing()) {
437
    return Local<Object>();
438
  }
439
28
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
440
441
28
  if (ui.IsEmpty())
442
    return MaybeLocal<Object>();
443
444
28
  return scope.Escape(ui.ToLocalChecked());
445
}
446
447
// Warning: This function needs `data` to be allocated with malloc() and not
448
// necessarily isolate's ArrayBuffer::Allocator.
449
140
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
450
140
  EscapableHandleScope handle_scope(isolate);
451
140
  Environment* env = Environment::GetCurrent(isolate);
452
140
  if (env == nullptr) {
453
    free(data);
454
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
455
    return MaybeLocal<Object>();
456
  }
457
  Local<Object> obj;
458
280
  if (Buffer::New(env, data, length, true).ToLocal(&obj))
459
140
    return handle_scope.Escape(obj);
460
  return Local<Object>();
461
}
462
463
// Warning: If this call comes through the public node_buffer.h API,
464
// the contract for this function is that `data` is allocated with malloc()
465
// and not necessarily isolate's ArrayBuffer::Allocator.
466
16212
MaybeLocal<Object> New(Environment* env,
467
                       char* data,
468
                       size_t length,
469
                       bool uses_malloc) {
470
16212
  if (length > 0) {
471
15289
    CHECK_NOT_NULL(data);
472
15289
    CHECK(length <= kMaxLength);
473
  }
474
475
16212
  if (uses_malloc) {
476
475
    if (!env->isolate_data()->uses_node_allocator()) {
477
      // We don't know for sure that the allocator is malloc()-based, so we need
478
      // to fall back to the FreeCallback variant.
479
      auto free_callback = [](char* data, void* hint) { free(data); };
480
      return New(env, data, length, free_callback, nullptr);
481
    } else {
482
      // This is malloc()-based, so we can acquire it into our own
483
      // ArrayBufferAllocator.
484
475
      CHECK_NOT_NULL(env->isolate_data()->node_allocator());
485
475
      env->isolate_data()->node_allocator()->RegisterPointer(data, length);
486
    }
487
  }
488
489
47150
  auto callback = [](void* data, size_t length, void* deleter_data){
490
15469
    CHECK_NOT_NULL(deleter_data);
491
492
15469
    static_cast<v8::ArrayBuffer::Allocator*>(deleter_data)
493
15469
        ->Free(data, length);
494
47150
  };
495
  std::unique_ptr<v8::BackingStore> backing =
496
      v8::ArrayBuffer::NewBackingStore(data,
497
                                       length,
498
                                       callback,
499
                                       env->isolate()
500
32424
                                          ->GetArrayBufferAllocator());
501
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(),
502
16212
                                           std::move(backing));
503
504
32424
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
505
}
506
507
namespace {
508
509
140
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
510
420
  CHECK(args[0]->IsString());
511
280
  CHECK(args[1]->IsInt32());
512
513
420
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
514
  Local<Object> buf;
515
420
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
516
280
    args.GetReturnValue().Set(buf);
517
140
}
518
519
520
template <encoding encoding>
521
410933
void StringSlice(const FunctionCallbackInfo<Value>& args) {
522
410933
  Environment* env = Environment::GetCurrent(args);
523
410933
  Isolate* isolate = env->isolate();
524
525



411117
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
526
410933
  ArrayBufferViewContents<char> buffer(args.This());
527
528



410933
  if (buffer.length() == 0)
529
354
    return args.GetReturnValue().SetEmptyString();
530
531
410756
  size_t start = 0;
532
410756
  size_t end = 0;
533






1643024
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
534






2053780
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
535



410756
  if (end < start) end = start;
536






1232268
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
537
410756
  size_t length = end - start;
538
539
  Local<Value> error;
540
  MaybeLocal<Value> ret =
541
410756
      StringBytes::Encode(isolate,
542
410756
                          buffer.data() + start,
543
                          length,
544
                          encoding,
545
410756
                          &error);
546



410756
  if (ret.IsEmpty()) {
547



7
    CHECK(!error.IsEmpty());
548
7
    isolate->ThrowException(error);
549
7
    return;
550
  }
551
821498
  args.GetReturnValue().Set(ret.ToLocalChecked());
552
}
553
554
555
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
556
13
void Copy(const FunctionCallbackInfo<Value> &args) {
557
13
  Environment* env = Environment::GetCurrent(args);
558
559
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
560
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
561
13
  ArrayBufferViewContents<char> source(args[0]);
562
26
  Local<Object> target_obj = args[1].As<Object>();
563

91
  SPREAD_BUFFER_ARG(target_obj, target);
564
565
13
  size_t target_start = 0;
566
13
  size_t source_start = 0;
567
13
  size_t source_end = 0;
568
569

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

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

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
572
                                          &source_end));
573
574
  // Copy 0 bytes; we're done
575

13
  if (target_start >= target_length || source_start >= source_end)
576
    return args.GetReturnValue().Set(0);
577
578
13
  if (source_start > source.length())
579
    return THROW_ERR_OUT_OF_RANGE(
580
        env, "The value of \"sourceStart\" is out of range.");
581
582
13
  if (source_end - source_start > target_length - target_start)
583
    source_end = source_start + target_length - target_start;
584
585
13
  uint32_t to_copy = std::min(
586
26
      std::min(source_end - source_start, target_length - target_start),
587
52
      source.length() - source_start);
588
589
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
590
26
  args.GetReturnValue().Set(to_copy);
591
}
592
593
594
160
void Fill(const FunctionCallbackInfo<Value>& args) {
595
160
  Environment* env = Environment::GetCurrent(args);
596
160
  Local<Context> ctx = env->context();
597
598
185
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
599

1415
  SPREAD_BUFFER_ARG(args[0], ts_obj);
600
601
  size_t start;
602

640
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
603
  size_t end;
604

636
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
605
606
158
  size_t fill_length = end - start;
607
  Local<String> str_obj;
608
  size_t str_length;
609
  enum encoding enc;
610
611
  // OOB Check. Throw the error in JS.
612

158
  if (start > end || fill_length + start > ts_obj_length)
613
    return args.GetReturnValue().Set(-2);
614
615
  // First check if Buffer has been passed.
616
158
  if (Buffer::HasInstance(args[1])) {
617

63
    SPREAD_BUFFER_ARG(args[1], fill_obj);
618
7
    str_length = fill_obj_length;
619
14
    memcpy(
620
21
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
621
7
    goto start_fill;
622
  }
623
624
  // Then coerce everything that's not a string.
625
453
  if (!args[1]->IsString()) {
626
    uint32_t val;
627
9
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
628
3
    int value = val & 255;
629
3
    memset(ts_obj_data + start, value, fill_length);
630
3
    return;
631
  }
632
633
592
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
634
148
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
635
636
  // Can't use StringBytes::Write() in all cases. For example if attempting
637
  // to write a two byte character into a one byte Buffer.
638
148
  if (enc == UTF8) {
639
96
    str_length = str_obj->Utf8Length(env->isolate());
640
96
    node::Utf8Value str(env->isolate(), args[1]);
641
48
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
642
643
100
  } else if (enc == UCS2) {
644
39
    str_length = str_obj->Length() * sizeof(uint16_t);
645
78
    node::TwoByteValue str(env->isolate(), args[1]);
646
39
    if (IsBigEndian())
647
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
648
649
39
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
650
651
  } else {
652
    // Write initial String to Buffer, then use that memory to copy remainder
653
    // of string. Correct the string length for cases like HEX where less than
654
    // the total string length is written.
655
122
    str_length = StringBytes::Write(env->isolate(),
656
61
                                    ts_obj_data + start,
657
                                    fill_length,
658
                                    str_obj,
659
                                    enc,
660
                                    nullptr);
661
  }
662
663
 start_fill:
664
665
155
  if (str_length >= fill_length)
666
14
    return;
667
668
  // If str_length is zero, then either an empty buffer was provided, or Write()
669
  // indicated that no bytes could be written. If no bytes could be written,
670
  // then return -1 because the fill value is invalid. This will trigger a throw
671
  // in JavaScript. Silently failing should be avoided because it can lead to
672
  // buffers with unexpected contents.
673
141
  if (str_length == 0)
674
12
    return args.GetReturnValue().Set(-1);
675
676
135
  size_t in_there = str_length;
677
135
  char* ptr = ts_obj_data + start + str_length;
678
679
593
  while (in_there < fill_length - in_there) {
680
229
    memcpy(ptr, ts_obj_data + start, in_there);
681
229
    ptr += in_there;
682
229
    in_there *= 2;
683
  }
684
685
135
  if (in_there < fill_length) {
686
135
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
687
  }
688
}
689
690
691
template <encoding encoding>
692
466624
void StringWrite(const FunctionCallbackInfo<Value>& args) {
693
466624
  Environment* env = Environment::GetCurrent(args);
694
695



466628
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
696









4199612
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
697
698



1399872
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
699
700
1866496
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
701
702
  size_t offset;
703
  size_t max_length;
704
705






1866496
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
706



466624
  if (offset > ts_obj_length) {
707
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
708
        env, "\"offset\" is outside of buffer bounds");
709
  }
710
711






2333120
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
712
                                          &max_length));
713
714
466624
  max_length = std::min(ts_obj_length - offset, max_length);
715
716



466624
  if (max_length == 0)
717
8
    return args.GetReturnValue().Set(0);
718
719
1399860
  uint32_t written = StringBytes::Write(env->isolate(),
720
466620
                                        ts_obj_data + offset,
721
                                        max_length,
722
                                        str,
723
                                        encoding,
724
466620
                                        nullptr);
725



933240
  args.GetReturnValue().Set(written);
726
}
727
728
144397
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
729
144397
  Environment* env = Environment::GetCurrent(args);
730
433191
  CHECK(args[0]->IsString());
731
732
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
733
866382
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
734
144397
}
735
736
// Normalize val to be an integer in the range of [1, -1] since
737
// implementations of memcmp() can vary by platform.
738
2953
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
739
2953
  if (val == 0) {
740
2926
    if (a_length > b_length)
741
6
      return 1;
742
2920
    else if (a_length < b_length)
743
5
      return -1;
744
  } else {
745
27
    if (val > 0)
746
7
      return 1;
747
    else
748
20
      return -1;
749
  }
750
2915
  return val;
751
}
752
753
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
754
9
  Environment* env = Environment::GetCurrent(args);
755
756
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
757
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
758
9
  ArrayBufferViewContents<char> source(args[0]);
759
9
  ArrayBufferViewContents<char> target(args[1]);
760
761
9
  size_t target_start = 0;
762
9
  size_t source_start = 0;
763
9
  size_t source_end = 0;
764
9
  size_t target_end = 0;
765
766

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

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

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

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

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

1742
  if ((is_forward && needle_length + offset > haystack_length) ||
897
870
      needle_length > haystack_length) {
898
30
    return args.GetReturnValue().Set(-1);
899
  }
900
901
857
  size_t result = haystack_length;
902
903
857
  if (enc == UCS2) {
904
170
    String::Value needle_value(isolate, needle);
905
85
    if (*needle_value == nullptr)
906
      return args.GetReturnValue().Set(-1);
907
908

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

392
  if ((is_forward && needle_length + offset > haystack_length) ||
1009
195
      needle_length > haystack_length) {
1010
14
    return args.GetReturnValue().Set(-1);
1011
  }
1012
1013
190
  size_t result = haystack_length;
1014
1015
190
  if (enc == UCS2) {
1016

58
    if (haystack_length < 2 || needle_length < 2) {
1017
4
      return args.GetReturnValue().Set(-1);
1018
    }
1019
56
    result = SearchString(
1020
        reinterpret_cast<const uint16_t*>(haystack),
1021
        haystack_length / 2,
1022
        reinterpret_cast<const uint16_t*>(needle),
1023
        needle_length / 2,
1024
        offset / 2,
1025
56
        is_forward);
1026
56
    result *= 2;
1027
  } else {
1028
132
    result = SearchString(
1029
        reinterpret_cast<const uint8_t*>(haystack),
1030
        haystack_length,
1031
        reinterpret_cast<const uint8_t*>(needle),
1032
        needle_length,
1033
        offset,
1034
132
        is_forward);
1035
  }
1036
1037
564
  args.GetReturnValue().Set(
1038
188
      result == haystack_length ? -1 : static_cast<int>(result));
1039
}
1040
1041
3982
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1042
7964
  CHECK(args[1]->IsUint32());
1043
7964
  CHECK(args[2]->IsNumber());
1044
7964
  CHECK(args[3]->IsBoolean());
1045
1046
3986
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1047
3982
  ArrayBufferViewContents<char> buffer(args[0]);
1048
1049
11946
  uint32_t needle = args[1].As<Uint32>()->Value();
1050
11946
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1051
7964
  bool is_forward = args[3]->IsTrue();
1052
1053
  int64_t opt_offset =
1054
3982
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1055

3982
  if (opt_offset <= -1 || buffer.length() == 0) {
1056
8
    return args.GetReturnValue().Set(-1);
1057
  }
1058
3978
  size_t offset = static_cast<size_t>(opt_offset);
1059
3978
  CHECK_LT(offset, buffer.length());
1060
1061
  const void* ptr;
1062
3978
  if (is_forward) {
1063
3970
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1064
  } else {
1065
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1066
  }
1067
3978
  const char* ptr_char = static_cast<const char*>(ptr);
1068
11934
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1069
                                : -1);
1070
}
1071
1072
1073
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1074
2
  Environment* env = Environment::GetCurrent(args);
1075
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1076

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1077
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1078
4
  args.GetReturnValue().Set(args[0]);
1079
}
1080
1081
1082
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1083
2
  Environment* env = Environment::GetCurrent(args);
1084
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1085

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1086
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1087
4
  args.GetReturnValue().Set(args[0]);
1088
}
1089
1090
1091
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1092
2
  Environment* env = Environment::GetCurrent(args);
1093
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1094

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1095
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1096
4
  args.GetReturnValue().Set(args[0]);
1097
}
1098
1099
1100
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1101
// Used in TextEncoder.prototype.encode.
1102
21
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1103
21
  Environment* env = Environment::GetCurrent(args);
1104
21
  Isolate* isolate = env->isolate();
1105
21
  CHECK_GE(args.Length(), 1);
1106
63
  CHECK(args[0]->IsString());
1107
1108
42
  Local<String> str = args[0].As<String>();
1109
21
  size_t length = str->Utf8Length(isolate);
1110
42
  AllocatedBuffer buf = env->AllocateManaged(length);
1111
42
  str->WriteUtf8(isolate,
1112
                 buf.data(),
1113
                 -1,  // We are certain that `data` is sufficiently large
1114
                 nullptr,
1115
21
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1116
21
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1117
42
  args.GetReturnValue().Set(array);
1118
21
}
1119
1120
1121
45
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1122
45
  Environment* env = Environment::GetCurrent(args);
1123
45
  Isolate* isolate = env->isolate();
1124
45
  CHECK_GE(args.Length(), 3);
1125
135
  CHECK(args[0]->IsString());
1126
90
  CHECK(args[1]->IsUint8Array());
1127
90
  CHECK(args[2]->IsUint32Array());
1128
1129
90
  Local<String> source = args[0].As<String>();
1130
1131
90
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1132
45
  Local<ArrayBuffer> buf = dest->Buffer();
1133
  char* write_result =
1134
90
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1135
45
  size_t dest_length = dest->ByteLength();
1136
1137
  // results = [ read, written ]
1138
90
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1139
  uint32_t* results = reinterpret_cast<uint32_t*>(
1140
135
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1141
45
      result_arr->ByteOffset());
1142
1143
  int nchars;
1144
90
  int written = source->WriteUtf8(
1145
      isolate,
1146
      write_result,
1147
      dest_length,
1148
      &nchars,
1149
45
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1150
45
  results[0] = nchars;
1151
45
  results[1] = written;
1152
45
}
1153
1154
1155
4594
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1156
4594
  Environment* env = Environment::GetCurrent(args);
1157
1158
9188
  CHECK(args[0]->IsObject());
1159
9188
  Local<Object> proto = args[0].As<Object>();
1160
4594
  env->set_buffer_prototype_object(proto);
1161
4594
}
1162
1163
1164
4594
void Initialize(Local<Object> target,
1165
                Local<Value> unused,
1166
                Local<Context> context,
1167
                void* priv) {
1168
4594
  Environment* env = Environment::GetCurrent(context);
1169
1170
4594
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1171
4594
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1172
1173
4594
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1174
4594
  env->SetMethod(target, "copy", Copy);
1175
4594
  env->SetMethodNoSideEffect(target, "compare", Compare);
1176
4594
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1177
4594
  env->SetMethod(target, "fill", Fill);
1178
4594
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1179
4594
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1180
4594
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1181
1182
4594
  env->SetMethod(target, "swap16", Swap16);
1183
4594
  env->SetMethod(target, "swap32", Swap32);
1184
4594
  env->SetMethod(target, "swap64", Swap64);
1185
1186
4594
  env->SetMethod(target, "encodeInto", EncodeInto);
1187
4594
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1188
1189
9188
  target->Set(env->context(),
1190
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1191
22970
              Number::New(env->isolate(), kMaxLength)).Check();
1192
1193
9188
  target->Set(env->context(),
1194
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1195
22970
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1196
1197
4594
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1198
4594
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1199
4594
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1200
4594
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1201
4594
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1202
4594
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1203
1204
4594
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1205
4594
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1206
4594
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1207
4594
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1208
4594
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1209
4594
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1210
1211
  // It can be a nullptr when running inside an isolate where we
1212
  // do not own the ArrayBuffer allocator.
1213
4594
  if (NodeArrayBufferAllocator* allocator =
1214
4594
          env->isolate_data()->node_allocator()) {
1215
4563
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1216
    std::unique_ptr<BackingStore> backing =
1217
      ArrayBuffer::NewBackingStore(zero_fill_field,
1218
                                   sizeof(*zero_fill_field),
1219
12827
                                   [](void*, size_t, void*){},
1220
9126
                                   nullptr);
1221
    Local<ArrayBuffer> array_buffer =
1222
4563
        ArrayBuffer::New(env->isolate(), std::move(backing));
1223
9126
    array_buffer->SetPrivate(
1224
        env->context(),
1225
        env->arraybuffer_untransferable_private_symbol(),
1226
13689
        True(env->isolate())).Check();
1227
22815
    CHECK(target
1228
              ->Set(env->context(),
1229
                    FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
1230
                    Uint32Array::New(array_buffer, 0, 1))
1231
              .FromJust());
1232
  }
1233
4594
}
1234
1235
}  // anonymous namespace
1236
}  // namespace Buffer
1237
}  // namespace node
1238
1239
4325
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)