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: 541 597 90.6 %
Date: 2020-06-24 22:13:30 Branches: 396 664 59.6 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_buffer.h"
23
#include "allocated_buffer-inl.h"
24
#include "node.h"
25
#include "node_errors.h"
26
#include "node_internals.h"
27
28
#include "env-inl.h"
29
#include "string_bytes.h"
30
#include "string_search.h"
31
#include "util-inl.h"
32
#include "v8.h"
33
34
#include <cstring>
35
#include <climits>
36
37
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
38
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
39
40
#define THROW_AND_RETURN_IF_OOB(r)                                          \
41
  do {                                                                      \
42
    if ((r).IsNothing()) return;                                            \
43
    if (!(r).FromJust())                                                    \
44
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
45
  } while (0)                                                               \
46
47
namespace node {
48
namespace Buffer {
49
50
using v8::ArrayBuffer;
51
using v8::ArrayBufferView;
52
using v8::BackingStore;
53
using v8::Context;
54
using v8::EscapableHandleScope;
55
using v8::FunctionCallbackInfo;
56
using v8::Global;
57
using v8::HandleScope;
58
using v8::Int32;
59
using v8::Integer;
60
using v8::Isolate;
61
using v8::Just;
62
using v8::Local;
63
using v8::Maybe;
64
using v8::MaybeLocal;
65
using v8::Nothing;
66
using v8::Number;
67
using v8::Object;
68
using v8::String;
69
using v8::Uint32;
70
using v8::Uint32Array;
71
using v8::Uint8Array;
72
using v8::Value;
73
74
namespace {
75
76
964
class CallbackInfo {
77
 public:
78
  static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
79
      Environment* env,
80
      char* data,
81
      size_t length,
82
      FreeCallback callback,
83
      void* hint);
84
85
  CallbackInfo(const CallbackInfo&) = delete;
86
  CallbackInfo& operator=(const CallbackInfo&) = delete;
87
88
 private:
89
  static void CleanupHook(void* data);
90
  inline void OnBackingStoreFree();
91
  inline void CallAndResetCallback();
92
  inline CallbackInfo(Environment* env,
93
                      FreeCallback callback,
94
                      char* data,
95
                      void* hint);
96
  Global<ArrayBuffer> persistent_;
97
  Mutex mutex_;  // Protects callback_.
98
  FreeCallback callback_;
99
  char* const data_;
100
  void* const hint_;
101
  Environment* const env_;
102
};
103
104
105
487
Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
106
    Environment* env,
107
    char* data,
108
    size_t length,
109
    FreeCallback callback,
110
    void* hint) {
111
487
  CHECK_NOT_NULL(callback);
112

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

604
    if (!ab.IsEmpty() && ab->IsDetachable()) {
155
302
      ab->Detach();
156
302
      self->persistent_.Reset();
157
    }
158
  }
159
160
  // Call the callback in this case, but don't delete `this` yet because the
161
  // BackingStore deleter callback will do so later.
162
302
  self->CallAndResetCallback();
163
302
}
164
165
784
void CallbackInfo::CallAndResetCallback() {
166
  FreeCallback callback;
167
  {
168
1568
    Mutex::ScopedLock lock(mutex_);
169
784
    callback = callback_;
170
784
    callback_ = nullptr;
171
  }
172
784
  if (callback != nullptr) {
173
    // Clean up all Environment-related state and run the callback.
174
482
    env_->RemoveCleanupHook(CleanupHook, this);
175
482
    int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
176
482
    env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
177
178
482
    callback(data_, hint_);
179
  }
180
784
}
181
182
487
void CallbackInfo::OnBackingStoreFree() {
183
  // This method should always release the memory for `this`.
184
974
  std::unique_ptr<CallbackInfo> self { this };
185
974
  Mutex::ScopedLock lock(mutex_);
186
  // If callback_ == nullptr, that means that the callback has already run from
187
  // the cleanup hook, and there is nothing left to do here besides to clean
188
  // up the memory involved. In particular, the underlying `Environment` may
189
  // be gone at this point, so don’t attempt to call SetImmediateThreadsafe().
190
487
  if (callback_ == nullptr) return;
191
192
2912
  env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
193
482
    CHECK_EQ(self->env_, env);  // Consistency check.
194
195
482
    self->CallAndResetCallback();
196
969
  });
197
}
198
199
200
// Parse index for external array data. An empty Maybe indicates
201
// a pending exception. `false` indicates that the index is out-of-bounds.
202
3558339
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
203
                                                   Local<Value> arg,
204
                                                   size_t def,
205
                                                   size_t* ret) {
206
7116678
  if (arg->IsUndefined()) {
207
    *ret = def;
208
    return Just(true);
209
  }
210
211
  int64_t tmp_i;
212
10675017
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
213
    return Nothing<bool>();
214
215
3558339
  if (tmp_i < 0)
216
4
    return Just(false);
217
218
  // Check that the result fits in a size_t.
219
3558335
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
220
  // coverity[pointless_expression]
221
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
222
    return Just(false);
223
224
3558335
  *ret = static_cast<size_t>(tmp_i);
225
3558335
  return Just(true);
226
}
227
228
}  // anonymous namespace
229
230
// Buffer methods
231
232
4842847
bool HasInstance(Local<Value> val) {
233
4842847
  return val->IsArrayBufferView();
234
}
235
236
237
889564
bool HasInstance(Local<Object> obj) {
238
889564
  return obj->IsArrayBufferView();
239
}
240
241
242
251628
char* Data(Local<Value> val) {
243
251628
  CHECK(val->IsArrayBufferView());
244
251628
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
245
754884
  return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) +
246
503256
      ui->ByteOffset();
247
}
248
249
250
125149
char* Data(Local<Object> obj) {
251
125149
  return Data(obj.As<Value>());
252
}
253
254
255
101463
size_t Length(Local<Value> val) {
256
101463
  CHECK(val->IsArrayBufferView());
257
101463
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
258
101463
  return ui->ByteLength();
259
}
260
261
262
123836
size_t Length(Local<Object> obj) {
263
123836
  CHECK(obj->IsArrayBufferView());
264
123836
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
265
123836
  return ui->ByteLength();
266
}
267
268
269
16426
MaybeLocal<Uint8Array> New(Environment* env,
270
                           Local<ArrayBuffer> ab,
271
                           size_t byte_offset,
272
                           size_t length) {
273
32852
  CHECK(!env->buffer_prototype_object().IsEmpty());
274
16426
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
275
  Maybe<bool> mb =
276
49278
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
277
16426
  if (mb.IsNothing())
278
    return MaybeLocal<Uint8Array>();
279
16426
  return ui;
280
}
281
282
MaybeLocal<Uint8Array> New(Isolate* isolate,
283
                           Local<ArrayBuffer> ab,
284
                           size_t byte_offset,
285
                           size_t length) {
286
  Environment* env = Environment::GetCurrent(isolate);
287
  if (env == nullptr) {
288
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
289
    return MaybeLocal<Uint8Array>();
290
  }
291
  return New(env, ab, byte_offset, length);
292
}
293
294
295
140
MaybeLocal<Object> New(Isolate* isolate,
296
                       Local<String> string,
297
                       enum encoding enc) {
298
140
  EscapableHandleScope scope(isolate);
299
300
  size_t length;
301
280
  if (!StringBytes::Size(isolate, string, enc).To(&length))
302
    return Local<Object>();
303
140
  size_t actual = 0;
304
140
  char* data = nullptr;
305
306
140
  if (length > 0) {
307
140
    data = UncheckedMalloc(length);
308
309
140
    if (data == nullptr) {
310
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
311
      return Local<Object>();
312
    }
313
314
140
    actual = StringBytes::Write(isolate, data, length, string, enc);
315
140
    CHECK(actual <= length);
316
317
140
    if (actual == 0) {
318
1
      free(data);
319
1
      data = nullptr;
320
139
    } else if (actual < length) {
321
      data = node::Realloc(data, actual);
322
    }
323
  }
324
325
280
  return scope.EscapeMaybe(New(isolate, data, actual));
326
}
327
328
329
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
330
1
  EscapableHandleScope handle_scope(isolate);
331
  Local<Object> obj;
332
1
  Environment* env = Environment::GetCurrent(isolate);
333
1
  if (env == nullptr) {
334
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
335
    return MaybeLocal<Object>();
336
  }
337
2
  if (Buffer::New(env, length).ToLocal(&obj))
338
1
    return handle_scope.Escape(obj);
339
  return Local<Object>();
340
}
341
342
343
1292
MaybeLocal<Object> New(Environment* env, size_t length) {
344
1292
  EscapableHandleScope scope(env->isolate());
345
346
  // V8 currently only allows a maximum Typed Array index of max Smi.
347
1292
  if (length > kMaxLength) {
348
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
349
    return Local<Object>();
350
  }
351
352
  return scope.EscapeMaybe(
353
2584
      AllocatedBuffer::AllocateManaged(env, length).ToBuffer());
354
}
355
356
357
2070
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
358
2070
  EscapableHandleScope handle_scope(isolate);
359
2070
  Environment* env = Environment::GetCurrent(isolate);
360
2070
  if (env == nullptr) {
361
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
362
1
    return MaybeLocal<Object>();
363
  }
364
  Local<Object> obj;
365
4138
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
366
2069
    return handle_scope.Escape(obj);
367
  return Local<Object>();
368
}
369
370
371
10793
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
372
10793
  EscapableHandleScope scope(env->isolate());
373
374
  // V8 currently only allows a maximum Typed Array index of max Smi.
375
10793
  if (length > kMaxLength) {
376
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
377
    return Local<Object>();
378
  }
379
380
21586
  AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length);
381
10793
  if (length > 0) {
382
10652
    memcpy(ret.data(), data, length);
383
  }
384
385
10793
  return scope.EscapeMaybe(ret.ToBuffer());
386
}
387
388
389
29
MaybeLocal<Object> New(Isolate* isolate,
390
                       char* data,
391
                       size_t length,
392
                       FreeCallback callback,
393
                       void* hint) {
394
29
  EscapableHandleScope handle_scope(isolate);
395
29
  Environment* env = Environment::GetCurrent(isolate);
396
29
  if (env == nullptr) {
397
    callback(data, hint);
398
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
399
    return MaybeLocal<Object>();
400
  }
401
  return handle_scope.EscapeMaybe(
402
58
      Buffer::New(env, data, length, callback, hint));
403
}
404
405
406
487
MaybeLocal<Object> New(Environment* env,
407
                       char* data,
408
                       size_t length,
409
                       FreeCallback callback,
410
                       void* hint) {
411
487
  EscapableHandleScope scope(env->isolate());
412
413
487
  if (length > kMaxLength) {
414
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
415
    callback(data, hint);
416
    return Local<Object>();
417
  }
418
419
  Local<ArrayBuffer> ab =
420
487
      CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
421
1461
  if (ab->SetPrivate(env->context(),
422
                     env->arraybuffer_untransferable_private_symbol(),
423
1461
                     True(env->isolate())).IsNothing()) {
424
    return Local<Object>();
425
  }
426
487
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
427
428
487
  if (ui.IsEmpty())
429
    return MaybeLocal<Object>();
430
431
487
  return scope.Escape(ui.ToLocalChecked());
432
}
433
434
// Warning: This function needs `data` to be allocated with malloc() and not
435
// necessarily isolate's ArrayBuffer::Allocator.
436
140
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
437
140
  EscapableHandleScope handle_scope(isolate);
438
140
  Environment* env = Environment::GetCurrent(isolate);
439
140
  if (env == nullptr) {
440
    free(data);
441
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
442
    return MaybeLocal<Object>();
443
  }
444
  Local<Object> obj;
445
280
  if (Buffer::New(env, data, length).ToLocal(&obj))
446
140
    return handle_scope.Escape(obj);
447
  return Local<Object>();
448
}
449
450
// The contract for this function is that `data` is allocated with malloc()
451
// and not necessarily isolate's ArrayBuffer::Allocator.
452
458
MaybeLocal<Object> New(Environment* env,
453
                       char* data,
454
                       size_t length) {
455
458
  if (length > 0) {
456
457
    CHECK_NOT_NULL(data);
457
457
    CHECK(length <= kMaxLength);
458
  }
459
460
1364
  auto free_callback = [](char* data, void* hint) { free(data); };
461
458
  return New(env, data, length, free_callback, nullptr);
462
}
463
464
namespace {
465
466
140
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
467
420
  CHECK(args[0]->IsString());
468
280
  CHECK(args[1]->IsInt32());
469
470
420
  enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
471
  Local<Object> buf;
472
420
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
473
280
    args.GetReturnValue().Set(buf);
474
140
}
475
476
477
template <encoding encoding>
478
417878
void StringSlice(const FunctionCallbackInfo<Value>& args) {
479
417878
  Environment* env = Environment::GetCurrent(args);
480
417879
  Isolate* isolate = env->isolate();
481
482



418063
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
483
417878
  ArrayBufferViewContents<char> buffer(args.This());
484
485



417879
  if (buffer.length() == 0)
486
354
    return args.GetReturnValue().SetEmptyString();
487
488
417702
  size_t start = 0;
489
417702
  size_t end = 0;
490






1670806
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
491






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



417701
  if (end < start) end = start;
493






1253104
  THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
494
417702
  size_t length = end - start;
495
496
  Local<Value> error;
497
  MaybeLocal<Value> ret =
498
417702
      StringBytes::Encode(isolate,
499
417702
                          buffer.data() + start,
500
                          length,
501
                          encoding,
502
417702
                          &error);
503



417702
  if (ret.IsEmpty()) {
504



7
    CHECK(!error.IsEmpty());
505
7
    isolate->ThrowException(error);
506
7
    return;
507
  }
508
835390
  args.GetReturnValue().Set(ret.ToLocalChecked());
509
}
510
511
512
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
513
13
void Copy(const FunctionCallbackInfo<Value> &args) {
514
13
  Environment* env = Environment::GetCurrent(args);
515
516
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
517
13
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
518
13
  ArrayBufferViewContents<char> source(args[0]);
519
26
  Local<Object> target_obj = args[1].As<Object>();
520

91
  SPREAD_BUFFER_ARG(target_obj, target);
521
522
13
  size_t target_start = 0;
523
13
  size_t source_start = 0;
524
13
  size_t source_end = 0;
525
526

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

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

65
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
529
                                          &source_end));
530
531
  // Copy 0 bytes; we're done
532

13
  if (target_start >= target_length || source_start >= source_end)
533
    return args.GetReturnValue().Set(0);
534
535
13
  if (source_start > source.length())
536
    return THROW_ERR_OUT_OF_RANGE(
537
        env, "The value of \"sourceStart\" is out of range.");
538
539
13
  if (source_end - source_start > target_length - target_start)
540
    source_end = source_start + target_length - target_start;
541
542
13
  uint32_t to_copy = std::min(
543
26
      std::min(source_end - source_start, target_length - target_start),
544
52
      source.length() - source_start);
545
546
13
  memmove(target_data + target_start, source.data() + source_start, to_copy);
547
26
  args.GetReturnValue().Set(to_copy);
548
}
549
550
551
160
void Fill(const FunctionCallbackInfo<Value>& args) {
552
160
  Environment* env = Environment::GetCurrent(args);
553
160
  Local<Context> ctx = env->context();
554
555
185
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
556

1415
  SPREAD_BUFFER_ARG(args[0], ts_obj);
557
558
  size_t start;
559

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

636
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
562
563
158
  size_t fill_length = end - start;
564
  Local<String> str_obj;
565
  size_t str_length;
566
  enum encoding enc;
567
568
  // OOB Check. Throw the error in JS.
569

158
  if (start > end || fill_length + start > ts_obj_length)
570
    return args.GetReturnValue().Set(-2);
571
572
  // First check if Buffer has been passed.
573
158
  if (Buffer::HasInstance(args[1])) {
574

63
    SPREAD_BUFFER_ARG(args[1], fill_obj);
575
7
    str_length = fill_obj_length;
576
14
    memcpy(
577
21
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
578
7
    goto start_fill;
579
  }
580
581
  // Then coerce everything that's not a string.
582
453
  if (!args[1]->IsString()) {
583
    uint32_t val;
584
9
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
585
3
    int value = val & 255;
586
3
    memset(ts_obj_data + start, value, fill_length);
587
3
    return;
588
  }
589
590
592
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
591
148
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
592
593
  // Can't use StringBytes::Write() in all cases. For example if attempting
594
  // to write a two byte character into a one byte Buffer.
595
148
  if (enc == UTF8) {
596
96
    str_length = str_obj->Utf8Length(env->isolate());
597
96
    node::Utf8Value str(env->isolate(), args[1]);
598
48
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
599
600
100
  } else if (enc == UCS2) {
601
39
    str_length = str_obj->Length() * sizeof(uint16_t);
602
78
    node::TwoByteValue str(env->isolate(), args[1]);
603
39
    if (IsBigEndian())
604
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
605
606
39
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
607
608
  } else {
609
    // Write initial String to Buffer, then use that memory to copy remainder
610
    // of string. Correct the string length for cases like HEX where less than
611
    // the total string length is written.
612
122
    str_length = StringBytes::Write(env->isolate(),
613
61
                                    ts_obj_data + start,
614
                                    fill_length,
615
                                    str_obj,
616
                                    enc,
617
                                    nullptr);
618
  }
619
620
 start_fill:
621
622
155
  if (str_length >= fill_length)
623
14
    return;
624
625
  // If str_length is zero, then either an empty buffer was provided, or Write()
626
  // indicated that no bytes could be written. If no bytes could be written,
627
  // then return -1 because the fill value is invalid. This will trigger a throw
628
  // in JavaScript. Silently failing should be avoided because it can lead to
629
  // buffers with unexpected contents.
630
141
  if (str_length == 0)
631
12
    return args.GetReturnValue().Set(-1);
632
633
135
  size_t in_there = str_length;
634
135
  char* ptr = ts_obj_data + start + str_length;
635
636
593
  while (in_there < fill_length - in_there) {
637
229
    memcpy(ptr, ts_obj_data + start, in_there);
638
229
    ptr += in_there;
639
229
    in_there *= 2;
640
  }
641
642
135
  if (in_there < fill_length) {
643
135
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
644
  }
645
}
646
647
648
template <encoding encoding>
649
471686
void StringWrite(const FunctionCallbackInfo<Value>& args) {
650
471686
  Environment* env = Environment::GetCurrent(args);
651
652



471690
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
653









4245170
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
654
655



1415058
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
656
657
1886744
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
658
659
  size_t offset;
660
  size_t max_length;
661
662






1886744
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
663



471686
  if (offset > ts_obj_length) {
664
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
665
        env, "\"offset\" is outside of buffer bounds");
666
  }
667
668






2358430
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
669
                                          &max_length));
670
671
471686
  max_length = std::min(ts_obj_length - offset, max_length);
672
673



471686
  if (max_length == 0)
674
8
    return args.GetReturnValue().Set(0);
675
676
1415046
  uint32_t written = StringBytes::Write(env->isolate(),
677
471682
                                        ts_obj_data + offset,
678
                                        max_length,
679
                                        str,
680
                                        encoding,
681
471682
                                        nullptr);
682



943364
  args.GetReturnValue().Set(written);
683
}
684
685
144676
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
686
144676
  Environment* env = Environment::GetCurrent(args);
687
434028
  CHECK(args[0]->IsString());
688
689
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
690
868056
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
691
144676
}
692
693
// Normalize val to be an integer in the range of [1, -1] since
694
// implementations of memcmp() can vary by platform.
695
2956
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
696
2956
  if (val == 0) {
697
2929
    if (a_length > b_length)
698
6
      return 1;
699
2923
    else if (a_length < b_length)
700
5
      return -1;
701
  } else {
702
27
    if (val > 0)
703
7
      return 1;
704
    else
705
20
      return -1;
706
  }
707
2918
  return val;
708
}
709
710
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
711
9
  Environment* env = Environment::GetCurrent(args);
712
713
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
714
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
715
9
  ArrayBufferViewContents<char> source(args[0]);
716
9
  ArrayBufferViewContents<char> target(args[1]);
717
718
9
  size_t target_start = 0;
719
9
  size_t source_start = 0;
720
9
  size_t source_end = 0;
721
9
  size_t target_end = 0;
722
723

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

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

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

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
728
                                          &source_end));
729
730
9
  if (source_start > source.length())
731
    return THROW_ERR_OUT_OF_RANGE(
732
        env, "The value of \"sourceStart\" is out of range.");
733
9
  if (target_start > target.length())
734
    return THROW_ERR_OUT_OF_RANGE(
735
        env, "The value of \"targetStart\" is out of range.");
736
737
9
  CHECK_LE(source_start, source_end);
738
9
  CHECK_LE(target_start, target_end);
739
740
  size_t to_cmp =
741
18
      std::min(std::min(source_end - source_start, target_end - target_start),
742
27
               source.length() - source_start);
743
744
18
  int val = normalizeCompareVal(to_cmp > 0 ?
745
9
                                  memcmp(source.data() + source_start,
746
9
                                         target.data() + target_start,
747
                                         to_cmp) : 0,
748
                                source_end - source_start,
749
9
                                target_end - target_start);
750
751
18
  args.GetReturnValue().Set(val);
752
}
753
754
2947
void Compare(const FunctionCallbackInfo<Value> &args) {
755
2947
  Environment* env = Environment::GetCurrent(args);
756
757
2947
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
758
2947
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
759
2947
  ArrayBufferViewContents<char> a(args[0]);
760
2947
  ArrayBufferViewContents<char> b(args[1]);
761
762
2947
  size_t cmp_length = std::min(a.length(), b.length());
763
764
5833
  int val = normalizeCompareVal(cmp_length > 0 ?
765
2886
                                memcmp(a.data(), b.data(), cmp_length) : 0,
766
2947
                                a.length(), b.length());
767
5894
  args.GetReturnValue().Set(val);
768
}
769
770
771
// Computes the offset for starting an indexOf or lastIndexOf search.
772
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
773
// or -1 to signal that there is no possible match.
774
5098
int64_t IndexOfOffset(size_t length,
775
                      int64_t offset_i64,
776
                      int64_t needle_length,
777
                      bool is_forward) {
778
5098
  int64_t length_i64 = static_cast<int64_t>(length);
779
5098
  if (offset_i64 < 0) {
780
77
    if (offset_i64 + length_i64 >= 0) {
781
      // Negative offsets count backwards from the end of the buffer.
782
59
      return length_i64 + offset_i64;
783

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

1742
  if ((is_forward && needle_length + offset > haystack_length) ||
854
870
      needle_length > haystack_length) {
855
30
    return args.GetReturnValue().Set(-1);
856
  }
857
858
857
  size_t result = haystack_length;
859
860
857
  if (enc == UCS2) {
861
170
    String::Value needle_value(isolate, needle);
862
85
    if (*needle_value == nullptr)
863
      return args.GetReturnValue().Set(-1);
864
865

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

392
  if ((is_forward && needle_length + offset > haystack_length) ||
966
195
      needle_length > haystack_length) {
967
14
    return args.GetReturnValue().Set(-1);
968
  }
969
970
190
  size_t result = haystack_length;
971
972
190
  if (enc == UCS2) {
973

58
    if (haystack_length < 2 || needle_length < 2) {
974
4
      return args.GetReturnValue().Set(-1);
975
    }
976
56
    result = SearchString(
977
        reinterpret_cast<const uint16_t*>(haystack),
978
        haystack_length / 2,
979
        reinterpret_cast<const uint16_t*>(needle),
980
        needle_length / 2,
981
        offset / 2,
982
56
        is_forward);
983
56
    result *= 2;
984
  } else {
985
132
    result = SearchString(
986
        reinterpret_cast<const uint8_t*>(haystack),
987
        haystack_length,
988
        reinterpret_cast<const uint8_t*>(needle),
989
        needle_length,
990
        offset,
991
132
        is_forward);
992
  }
993
994
564
  args.GetReturnValue().Set(
995
188
      result == haystack_length ? -1 : static_cast<int>(result));
996
}
997
998
3990
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
999
7980
  CHECK(args[1]->IsUint32());
1000
7980
  CHECK(args[2]->IsNumber());
1001
7980
  CHECK(args[3]->IsBoolean());
1002
1003
3994
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1004
3990
  ArrayBufferViewContents<char> buffer(args[0]);
1005
1006
11970
  uint32_t needle = args[1].As<Uint32>()->Value();
1007
11970
  int64_t offset_i64 = args[2].As<Integer>()->Value();
1008
7980
  bool is_forward = args[3]->IsTrue();
1009
1010
  int64_t opt_offset =
1011
3990
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1012

3990
  if (opt_offset <= -1 || buffer.length() == 0) {
1013
8
    return args.GetReturnValue().Set(-1);
1014
  }
1015
3986
  size_t offset = static_cast<size_t>(opt_offset);
1016
3986
  CHECK_LT(offset, buffer.length());
1017
1018
  const void* ptr;
1019
3986
  if (is_forward) {
1020
3978
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1021
  } else {
1022
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1023
  }
1024
3986
  const char* ptr_char = static_cast<const char*>(ptr);
1025
11958
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1026
                                : -1);
1027
}
1028
1029
1030
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1031
2
  Environment* env = Environment::GetCurrent(args);
1032
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1033

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1034
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1035
4
  args.GetReturnValue().Set(args[0]);
1036
}
1037
1038
1039
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1040
2
  Environment* env = Environment::GetCurrent(args);
1041
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1042

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1043
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1044
4
  args.GetReturnValue().Set(args[0]);
1045
}
1046
1047
1048
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1049
2
  Environment* env = Environment::GetCurrent(args);
1050
2
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1051

18
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1052
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1053
4
  args.GetReturnValue().Set(args[0]);
1054
}
1055
1056
1057
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1058
// Used in TextEncoder.prototype.encode.
1059
21
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1060
21
  Environment* env = Environment::GetCurrent(args);
1061
21
  Isolate* isolate = env->isolate();
1062
21
  CHECK_GE(args.Length(), 1);
1063
63
  CHECK(args[0]->IsString());
1064
1065
42
  Local<String> str = args[0].As<String>();
1066
21
  size_t length = str->Utf8Length(isolate);
1067
42
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, length);
1068
42
  str->WriteUtf8(isolate,
1069
                 buf.data(),
1070
                 -1,  // We are certain that `data` is sufficiently large
1071
                 nullptr,
1072
21
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1073
21
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1074
42
  args.GetReturnValue().Set(array);
1075
21
}
1076
1077
1078
45
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1079
45
  Environment* env = Environment::GetCurrent(args);
1080
45
  Isolate* isolate = env->isolate();
1081
45
  CHECK_GE(args.Length(), 3);
1082
135
  CHECK(args[0]->IsString());
1083
90
  CHECK(args[1]->IsUint8Array());
1084
90
  CHECK(args[2]->IsUint32Array());
1085
1086
90
  Local<String> source = args[0].As<String>();
1087
1088
90
  Local<Uint8Array> dest = args[1].As<Uint8Array>();
1089
45
  Local<ArrayBuffer> buf = dest->Buffer();
1090
  char* write_result =
1091
90
      static_cast<char*>(buf->GetBackingStore()->Data()) + dest->ByteOffset();
1092
45
  size_t dest_length = dest->ByteLength();
1093
1094
  // results = [ read, written ]
1095
90
  Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1096
  uint32_t* results = reinterpret_cast<uint32_t*>(
1097
135
      static_cast<char*>(result_arr->Buffer()->GetBackingStore()->Data()) +
1098
45
      result_arr->ByteOffset());
1099
1100
  int nchars;
1101
90
  int written = source->WriteUtf8(
1102
      isolate,
1103
      write_result,
1104
      dest_length,
1105
      &nchars,
1106
45
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1107
45
  results[0] = nchars;
1108
45
  results[1] = written;
1109
45
}
1110
1111
1112
4703
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1113
4703
  Environment* env = Environment::GetCurrent(args);
1114
1115
9406
  CHECK(args[0]->IsObject());
1116
9406
  Local<Object> proto = args[0].As<Object>();
1117
4703
  env->set_buffer_prototype_object(proto);
1118
4703
}
1119
1120
1121
4703
void Initialize(Local<Object> target,
1122
                Local<Value> unused,
1123
                Local<Context> context,
1124
                void* priv) {
1125
4703
  Environment* env = Environment::GetCurrent(context);
1126
1127
4703
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1128
4703
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1129
1130
4703
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1131
4703
  env->SetMethod(target, "copy", Copy);
1132
4703
  env->SetMethodNoSideEffect(target, "compare", Compare);
1133
4703
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1134
4703
  env->SetMethod(target, "fill", Fill);
1135
4703
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1136
4703
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1137
4703
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1138
1139
4703
  env->SetMethod(target, "swap16", Swap16);
1140
4703
  env->SetMethod(target, "swap32", Swap32);
1141
4703
  env->SetMethod(target, "swap64", Swap64);
1142
1143
4703
  env->SetMethod(target, "encodeInto", EncodeInto);
1144
4703
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1145
1146
9406
  target->Set(env->context(),
1147
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1148
23515
              Number::New(env->isolate(), kMaxLength)).Check();
1149
1150
9406
  target->Set(env->context(),
1151
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1152
23515
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1153
1154
4703
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1155
4703
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1156
4703
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1157
4703
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1158
4703
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1159
4703
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1160
1161
4703
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1162
4703
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1163
4703
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1164
4703
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1165
4703
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1166
4703
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1167
1168
  // It can be a nullptr when running inside an isolate where we
1169
  // do not own the ArrayBuffer allocator.
1170
4703
  if (NodeArrayBufferAllocator* allocator =
1171
4703
          env->isolate_data()->node_allocator()) {
1172
4671
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1173
    std::unique_ptr<BackingStore> backing =
1174
      ArrayBuffer::NewBackingStore(zero_fill_field,
1175
                                   sizeof(*zero_fill_field),
1176
13073
                                   [](void*, size_t, void*){},
1177
9342
                                   nullptr);
1178
    Local<ArrayBuffer> array_buffer =
1179
4671
        ArrayBuffer::New(env->isolate(), std::move(backing));
1180
9342
    array_buffer->SetPrivate(
1181
        env->context(),
1182
        env->arraybuffer_untransferable_private_symbol(),
1183
14013
        True(env->isolate())).Check();
1184
23355
    CHECK(target
1185
              ->Set(env->context(),
1186
                    FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
1187
                    Uint32Array::New(array_buffer, 0, 1))
1188
              .FromJust());
1189
  }
1190
4703
}
1191
1192
}  // anonymous namespace
1193
}  // namespace Buffer
1194
}  // namespace node
1195
1196
4398
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)