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: 480 527 91.1 %
Date: 2019-02-26 22:23:30 Branches: 436 718 60.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-profiler.h"
32
#include "v8.h"
33
34
#include <string.h>
35
#include <limits.h>
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
#define SLICE_START_END(env, start_arg, end_arg, end_max)                   \
48
  size_t start = 0;                                                         \
49
  size_t end = 0;                                                           \
50
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, start_arg, 0, &start));      \
51
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, end_arg, end_max, &end));    \
52
  if (end < start) end = start;                                             \
53
  THROW_AND_RETURN_IF_OOB(Just(end <= end_max));                            \
54
  size_t length = end - start;
55
56
namespace node {
57
namespace Buffer {
58
59
using v8::ArrayBuffer;
60
using v8::ArrayBufferCreationMode;
61
using v8::ArrayBufferView;
62
using v8::Context;
63
using v8::EscapableHandleScope;
64
using v8::FunctionCallbackInfo;
65
using v8::Integer;
66
using v8::Isolate;
67
using v8::Just;
68
using v8::Local;
69
using v8::Maybe;
70
using v8::MaybeLocal;
71
using v8::Nothing;
72
using v8::Object;
73
using v8::String;
74
using v8::Uint32;
75
using v8::Uint32Array;
76
using v8::Uint8Array;
77
using v8::Value;
78
using v8::WeakCallbackInfo;
79
80
namespace {
81
82
62
class CallbackInfo {
83
 public:
84
  static inline void Free(char* data, void* hint);
85
  static inline CallbackInfo* New(Isolate* isolate,
86
                                  Local<ArrayBuffer> object,
87
                                  FreeCallback callback,
88
                                  char* data,
89
                                  void* hint = nullptr);
90
 private:
91
  static void WeakCallback(const WeakCallbackInfo<CallbackInfo>&);
92
  inline void WeakCallback(Isolate* isolate);
93
  inline CallbackInfo(Isolate* isolate,
94
                      Local<ArrayBuffer> object,
95
                      FreeCallback callback,
96
                      char* data,
97
                      void* hint);
98
  Persistent<ArrayBuffer> persistent_;
99
  FreeCallback const callback_;
100
  char* const data_;
101
  void* const hint_;
102
  DISALLOW_COPY_AND_ASSIGN(CallbackInfo);
103
};
104
105
106
void CallbackInfo::Free(char* data, void*) {
107
  ::free(data);
108
}
109
110
111
5002
CallbackInfo* CallbackInfo::New(Isolate* isolate,
112
                                Local<ArrayBuffer> object,
113
                                FreeCallback callback,
114
                                char* data,
115
                                void* hint) {
116
5002
  return new CallbackInfo(isolate, object, callback, data, hint);
117
}
118
119
120
5002
CallbackInfo::CallbackInfo(Isolate* isolate,
121
                           Local<ArrayBuffer> object,
122
                           FreeCallback callback,
123
                           char* data,
124
                           void* hint)
125
    : persistent_(isolate, object),
126
      callback_(callback),
127
      data_(data),
128
10004
      hint_(hint) {
129
5002
  ArrayBuffer::Contents obj_c = object->GetContents();
130
5002
  CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
131
5002
  if (object->ByteLength() != 0)
132
4999
    CHECK_NOT_NULL(data_);
133
134
5002
  persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
135
5002
  isolate->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
136
5002
}
137
138
139
31
void CallbackInfo::WeakCallback(
140
    const WeakCallbackInfo<CallbackInfo>& data) {
141
31
  CallbackInfo* self = data.GetParameter();
142
31
  self->WeakCallback(data.GetIsolate());
143
31
  delete self;
144
31
}
145
146
147
31
void CallbackInfo::WeakCallback(Isolate* isolate) {
148
31
  callback_(data_, hint_);
149
31
  int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
150
  isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
151
31
}
152
153
154
// Parse index for external array data. An empty Maybe indicates
155
// a pending exception. `false` indicates that the index is out-of-bounds.
156
3155893
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
157
                                                   Local<Value> arg,
158
                                                   size_t def,
159
                                                   size_t* ret) {
160
6311786
  if (arg->IsUndefined()) {
161
1248614
    *ret = def;
162
1248614
    return Just(true);
163
  }
164
165
  int64_t tmp_i;
166
5721837
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
167
1
    return Nothing<bool>();
168
169
1907278
  if (tmp_i < 0)
170
4
    return Just(false);
171
172
  // Check that the result fits in a size_t.
173
1907274
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
174
  // coverity[pointless_expression]
175
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
176
    return Just(false);
177
178
1907274
  *ret = static_cast<size_t>(tmp_i);
179
1907274
  return Just(true);
180
}
181
182
}  // anonymous namespace
183
184
// Buffer methods
185
186
7919980
bool HasInstance(Local<Value> val) {
187
7919980
  return val->IsArrayBufferView();
188
}
189
190
191
293858
bool HasInstance(Local<Object> obj) {
192
293858
  return obj->IsArrayBufferView();
193
}
194
195
196
797637
char* Data(Local<Value> val) {
197
797637
  CHECK(val->IsArrayBufferView());
198
797637
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
199
1595274
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
200
1595274
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
201
}
202
203
204
377986
char* Data(Local<Object> obj) {
205
377986
  CHECK(obj->IsArrayBufferView());
206
377986
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
207
755972
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
208
755972
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
209
}
210
211
212
765491
size_t Length(Local<Value> val) {
213
765491
  CHECK(val->IsArrayBufferView());
214
765491
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
215
765491
  return ui->ByteLength();
216
}
217
218
219
374011
size_t Length(Local<Object> obj) {
220
374011
  CHECK(obj->IsArrayBufferView());
221
374011
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
222
374011
  return ui->ByteLength();
223
}
224
225
226
48718
inline MaybeLocal<Uint8Array> New(Environment* env,
227
                                  Local<ArrayBuffer> ab,
228
                                  size_t byte_offset,
229
                                  size_t length) {
230
97436
  CHECK(!env->buffer_prototype_object().IsEmpty());
231
48718
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
232
  Maybe<bool> mb =
233
146154
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
234
48718
  if (mb.IsNothing())
235
    return MaybeLocal<Uint8Array>();
236
48718
  return ui;
237
}
238
239
240
4832
MaybeLocal<Object> New(Isolate* isolate,
241
                       Local<String> string,
242
                       enum encoding enc) {
243
4832
  EscapableHandleScope scope(isolate);
244
245
  size_t length;
246
9664
  if (!StringBytes::Size(isolate, string, enc).To(&length))
247
    return Local<Object>();
248
4832
  size_t actual = 0;
249
4832
  char* data = nullptr;
250
251
4832
  if (length > 0) {
252
4832
    data = UncheckedMalloc(length);
253
254
4832
    if (data == nullptr) {
255
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
256
      return Local<Object>();
257
    }
258
259
4832
    actual = StringBytes::Write(isolate, data, length, string, enc);
260
4832
    CHECK(actual <= length);
261
262
4832
    if (actual == 0) {
263
1
      free(data);
264
1
      data = nullptr;
265
4831
    } else if (actual < length) {
266
      data = node::Realloc(data, actual);
267
    }
268
  }
269
270
9664
  return scope.EscapeMaybe(New(isolate, data, actual));
271
}
272
273
274
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
275
1
  EscapableHandleScope handle_scope(isolate);
276
  Local<Object> obj;
277
1
  Environment* env = Environment::GetCurrent(isolate);
278
1
  if (env == nullptr) {
279
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
280
    return MaybeLocal<Object>();
281
  }
282
2
  if (Buffer::New(env, length).ToLocal(&obj))
283
1
    return handle_scope.Escape(obj);
284
  return Local<Object>();
285
}
286
287
288
3975
MaybeLocal<Object> New(Environment* env, size_t length) {
289
3975
  EscapableHandleScope scope(env->isolate());
290
291
  // V8 currently only allows a maximum Typed Array index of max Smi.
292
3975
  if (length > kMaxLength) {
293
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
294
    return Local<Object>();
295
  }
296
297
7950
  AllocatedBuffer ret(env);
298
3975
  if (length > 0) {
299
2946
    ret = env->AllocateManaged(length, false);
300
2946
    if (ret.data() == nullptr) {
301
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
302
      return Local<Object>();
303
    }
304
  }
305
306
7950
  return scope.EscapeMaybe(ret.ToBuffer());
307
}
308
309
310
3363
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
311
3363
  EscapableHandleScope handle_scope(isolate);
312
3363
  Environment* env = Environment::GetCurrent(isolate);
313
3363
  if (env == nullptr) {
314
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
315
1
    return MaybeLocal<Object>();
316
  }
317
  Local<Object> obj;
318
6724
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
319
3362
    return handle_scope.Escape(obj);
320
  return Local<Object>();
321
}
322
323
324
18735
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
325
18735
  EscapableHandleScope scope(env->isolate());
326
327
  // V8 currently only allows a maximum Typed Array index of max Smi.
328
18735
  if (length > kMaxLength) {
329
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
330
    return Local<Object>();
331
  }
332
333
37470
  AllocatedBuffer ret(env);
334
18735
  if (length > 0) {
335
18597
    CHECK_NOT_NULL(data);
336
18597
    ret = env->AllocateManaged(length, false);
337
18597
    if (ret.data() == nullptr) {
338
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
339
      return Local<Object>();
340
    }
341
18597
    memcpy(ret.data(), data, length);
342
  }
343
344
37470
  return scope.EscapeMaybe(ret.ToBuffer());
345
}
346
347
348
15
MaybeLocal<Object> New(Isolate* isolate,
349
                       char* data,
350
                       size_t length,
351
                       FreeCallback callback,
352
                       void* hint) {
353
15
  EscapableHandleScope handle_scope(isolate);
354
15
  Environment* env = Environment::GetCurrent(isolate);
355
15
  if (env == nullptr) {
356
    callback(data, hint);
357
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
358
    return MaybeLocal<Object>();
359
  }
360
  Local<Object> obj;
361
30
  if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj))
362
15
    return handle_scope.Escape(obj);
363
  return Local<Object>();
364
}
365
366
367
5002
MaybeLocal<Object> New(Environment* env,
368
                       char* data,
369
                       size_t length,
370
                       FreeCallback callback,
371
                       void* hint) {
372
5002
  EscapableHandleScope scope(env->isolate());
373
374
5002
  if (length > kMaxLength) {
375
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
376
    callback(data, hint);
377
    return Local<Object>();
378
  }
379
380
5002
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
381
5002
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
382
383
5002
  CallbackInfo::New(env->isolate(), ab, callback, data, hint);
384
385
5002
  if (ui.IsEmpty())
386
    return MaybeLocal<Object>();
387
388
5002
  return scope.Escape(ui.ToLocalChecked());
389
}
390
391
// Warning: This function needs `data` to be allocated with malloc() and not
392
// necessarily isolate's ArrayBuffer::Allocator.
393
4832
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
394
4832
  EscapableHandleScope handle_scope(isolate);
395
4832
  Environment* env = Environment::GetCurrent(isolate);
396
4832
  if (env == nullptr) {
397
    free(data);
398
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
399
    return MaybeLocal<Object>();
400
  }
401
  Local<Object> obj;
402
9664
  if (Buffer::New(env, data, length, true).ToLocal(&obj))
403
4832
    return handle_scope.Escape(obj);
404
  return Local<Object>();
405
}
406
407
// Warning: If this call comes through the public node_buffer.h API,
408
// the contract for this function is that `data` is allocated with malloc()
409
// and not necessarily isolate's ArrayBuffer::Allocator.
410
48703
MaybeLocal<Object> New(Environment* env,
411
                       char* data,
412
                       size_t length,
413
                       bool uses_malloc) {
414
48703
  if (length > 0) {
415
47315
    CHECK_NOT_NULL(data);
416
47315
    CHECK(length <= kMaxLength);
417
  }
418
419
48703
  if (uses_malloc) {
420
4987
    if (env->isolate_data()->uses_node_allocator()) {
421
      // We don't know for sure that the allocator is malloc()-based, so we need
422
      // to fall back to the FreeCallback variant.
423
5019
      auto free_callback = [](char* data, void* hint) { free(data); };
424
4987
      return New(env, data, length, free_callback, nullptr);
425
    } else {
426
      // This is malloc()-based, so we can acquire it into our own
427
      // ArrayBufferAllocator.
428
      CHECK_NOT_NULL(env->isolate_data()->node_allocator());
429
      env->isolate_data()->node_allocator()->RegisterPointer(data, length);
430
    }
431
  }
432
433
  Local<ArrayBuffer> ab =
434
      ArrayBuffer::New(env->isolate(),
435
                       data,
436
                       length,
437
43716
                       ArrayBufferCreationMode::kInternalized);
438
87432
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
439
}
440
441
namespace {
442
443
4832
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
444
14496
  CHECK(args[0]->IsString());
445
14496
  CHECK(args[1]->IsString());
446
447
  enum encoding enc = ParseEncoding(args.GetIsolate(),
448
                                    args[1].As<String>(),
449
9664
                                    UTF8);
450
  Local<Object> buf;
451
14496
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
452
9664
    args.GetReturnValue().Set(buf);
453
4832
}
454
455
456
template <encoding encoding>
457
130305
void StringSlice(const FunctionCallbackInfo<Value>& args) {
458
130305
  Environment* env = Environment::GetCurrent(args);
459
130305
  Isolate* isolate = env->isolate();
460
461



130514
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
462









1042440
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
463
464



130305
  if (ts_obj_length == 0)
465
402
    return args.GetReturnValue().SetEmptyString();
466
467





















1431144
  SLICE_START_END(env, args[0], args[1], ts_obj_length)
468
469
  Local<Value> error;
470
  MaybeLocal<Value> ret =
471
      StringBytes::Encode(isolate,
472
                          ts_obj_data + start,
473
                          length,
474
                          encoding,
475
130104
                          &error);
476



130104
  if (ret.IsEmpty()) {
477



8
    CHECK(!error.IsEmpty());
478
8
    isolate->ThrowException(error);
479
8
    return;
480
  }
481
260192
  args.GetReturnValue().Set(ret.ToLocalChecked());
482
}
483
484
485
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
486
330199
void Copy(const FunctionCallbackInfo<Value> &args) {
487
330199
  Environment* env = Environment::GetCurrent(args);
488
489
330724
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
490
330199
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
491
660396
  Local<Object> buffer_obj = args[0].As<Object>();
492
660396
  Local<Object> target_obj = args[1].As<Object>();
493

1981188
  SPREAD_BUFFER_ARG(buffer_obj, ts_obj);
494

1981188
  SPREAD_BUFFER_ARG(target_obj, target);
495
496
330198
  size_t target_start = 0;
497
330198
  size_t source_start = 0;
498
330198
  size_t source_end = 0;
499
500

1320790
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
501

1320788
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
502

1320780
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], ts_obj_length,
503
                                          &source_end));
504
505
  // Copy 0 bytes; we're done
506

330195
  if (target_start >= target_length || source_start >= source_end)
507
1040
    return args.GetReturnValue().Set(0);
508
509
329675
  if (source_start > ts_obj_length)
510
    return THROW_ERR_OUT_OF_RANGE(
511
1
        env, "The value of \"sourceStart\" is out of range.");
512
513
329674
  if (source_end - source_start > target_length - target_start)
514
6
    source_end = source_start + target_length - target_start;
515
516
  uint32_t to_copy = std::min(
517
659348
      std::min(source_end - source_start, target_length - target_start),
518
989022
      ts_obj_length - source_start);
519
520
329674
  memmove(target_data + target_start, ts_obj_data + source_start, to_copy);
521
659348
  args.GetReturnValue().Set(to_copy);
522
}
523
524
525
805262
void Fill(const FunctionCallbackInfo<Value>& args) {
526
805262
  Environment* env = Environment::GetCurrent(args);
527
805262
  Local<Context> ctx = env->context();
528
529
1610388
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
530

6442096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
531
532
  uint32_t start;
533
2415786
  if (!args[2]->Uint32Value(ctx).To(&start)) return;
534
  uint32_t end;
535
2415786
  if (!args[3]->Uint32Value(ctx).To(&end)) return;
536
805262
  size_t fill_length = end - start;
537
  Local<String> str_obj;
538
  size_t str_length;
539
  enum encoding enc;
540
541
  // OOB Check. Throw the error in JS.
542

805262
  if (start > end || fill_length + start > ts_obj_length)
543
6
    return args.GetReturnValue().Set(-2);
544
545
  // First check if Buffer has been passed.
546
805259
  if (Buffer::HasInstance(args[1])) {
547

64
    SPREAD_BUFFER_ARG(args[1], fill_obj);
548
8
    str_length = fill_obj_length;
549
    memcpy(
550
8
        ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
551
8
    goto start_fill;
552
  }
553
554
  // Then coerce everything that's not a string.
555
2415753
  if (!args[1]->IsString()) {
556
    uint32_t val;
557
2415306
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
558
805102
    int value = val & 255;
559
805102
    memset(ts_obj_data + start, value, fill_length);
560
805102
    return;
561
  }
562
563
596
  str_obj = args[1]->ToString(env->context()).ToLocalChecked();
564
149
  enc = ParseEncoding(env->isolate(), args[4], UTF8);
565
566
  // Can't use StringBytes::Write() in all cases. For example if attempting
567
  // to write a two byte character into a one byte Buffer.
568
149
  if (enc == UTF8) {
569
96
    str_length = str_obj->Utf8Length(env->isolate());
570
48
    node::Utf8Value str(env->isolate(), args[1]);
571
48
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
572
573
101
  } else if (enc == UCS2) {
574
39
    str_length = str_obj->Length() * sizeof(uint16_t);
575
39
    node::TwoByteValue str(env->isolate(), args[1]);
576
39
    if (IsBigEndian())
577
      SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
578
579
39
    memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
580
581
  } else {
582
    // Write initial String to Buffer, then use that memory to copy remainder
583
    // of string. Correct the string length for cases like HEX where less than
584
    // the total string length is written.
585
    str_length = StringBytes::Write(env->isolate(),
586
                                    ts_obj_data + start,
587
                                    fill_length,
588
                                    str_obj,
589
                                    enc,
590
62
                                    nullptr);
591
  }
592
593
 start_fill:
594
595
157
  if (str_length >= fill_length)
596
15
    return;
597
598
  // If str_length is zero, then either an empty buffer was provided, or Write()
599
  // indicated that no bytes could be written. If no bytes could be written,
600
  // then return -1 because the fill value is invalid. This will trigger a throw
601
  // in JavaScript. Silently failing should be avoided because it can lead to
602
  // buffers with unexpected contents.
603
142
  if (str_length == 0)
604
12
    return args.GetReturnValue().Set(-1);
605
606
136
  size_t in_there = str_length;
607
136
  char* ptr = ts_obj_data + start + str_length;
608
609
501
  while (in_there < fill_length - in_there) {
610
229
    memcpy(ptr, ts_obj_data + start, in_there);
611
229
    ptr += in_there;
612
229
    in_there *= 2;
613
  }
614
615
136
  if (in_there < fill_length) {
616
136
    memcpy(ptr, ts_obj_data + start, fill_length - in_there);
617
  }
618
}
619
620
621
template <encoding encoding>
622
163553
void StringWrite(const FunctionCallbackInfo<Value>& args) {
623
163553
  Environment* env = Environment::GetCurrent(args);
624
625



163558
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
626









1308424
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
627
628



490659
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
629
630
654212
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
631
632
  size_t offset;
633
  size_t max_length;
634
635






654212
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
636



163553
  if (offset > ts_obj_length) {
637
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
638
1
        env, "\"offset\" is outside of buffer bounds");
639
  }
640
641






817760
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
642
                                          &max_length));
643
644
163552
  max_length = std::min(ts_obj_length - offset, max_length);
645
646



163552
  if (max_length == 0)
647
8
    return args.GetReturnValue().Set(0);
648
649
  uint32_t written = StringBytes::Write(env->isolate(),
650
                                        ts_obj_data + offset,
651
                                        max_length,
652
                                        str,
653
                                        encoding,
654
163548
                                        nullptr);
655
327096
  args.GetReturnValue().Set(written);
656
}
657
658
180941
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
659
180941
  Environment* env = Environment::GetCurrent(args);
660
542823
  CHECK(args[0]->IsString());
661
662
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
663
1085646
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
664
180941
}
665
666
// Normalize val to be an integer in the range of [1, -1] since
667
// implementations of memcmp() can vary by platform.
668
204792
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
669
204792
  if (val == 0) {
670
104760
    if (a_length > b_length)
671
6
      return 1;
672
104754
    else if (a_length < b_length)
673
6
      return -1;
674
  } else {
675
100032
    if (val > 0)
676
7
      return 1;
677
    else
678
100025
      return -1;
679
  }
680
104748
  return val;
681
}
682
683
11
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
684
11
  Environment* env = Environment::GetCurrent(args);
685
686
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
687
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
688

88
  SPREAD_BUFFER_ARG(args[0], ts_obj);
689

88
  SPREAD_BUFFER_ARG(args[1], target);
690
691
11
  size_t target_start = 0;
692
11
  size_t source_start = 0;
693
11
  size_t source_end = 0;
694
11
  size_t target_end = 0;
695
696

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
697

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
698

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target_length,
699
                                          &target_end));
700

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], ts_obj_length,
701
                                          &source_end));
702
703
11
  if (source_start > ts_obj_length)
704
    return THROW_ERR_OUT_OF_RANGE(
705
        env, "The value of \"sourceStart\" is out of range.");
706
11
  if (target_start > target_length)
707
    return THROW_ERR_OUT_OF_RANGE(
708
        env, "The value of \"targetStart\" is out of range.");
709
710
11
  CHECK_LE(source_start, source_end);
711
11
  CHECK_LE(target_start, target_end);
712
713
  size_t to_cmp =
714
22
      std::min(std::min(source_end - source_start, target_end - target_start),
715
33
               ts_obj_length - source_start);
716
717
  int val = normalizeCompareVal(to_cmp > 0 ?
718
                                  memcmp(ts_obj_data + source_start,
719
                                         target_data + target_start,
720
11
                                         to_cmp) : 0,
721
                                source_end - source_start,
722
22
                                target_end - target_start);
723
724
22
  args.GetReturnValue().Set(val);
725
}
726
727
204782
void Compare(const FunctionCallbackInfo<Value> &args) {
728
204782
  Environment* env = Environment::GetCurrent(args);
729
730
204783
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
731
204781
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
732

1638248
  SPREAD_BUFFER_ARG(args[0], obj_a);
733

1638248
  SPREAD_BUFFER_ARG(args[1], obj_b);
734
735
204781
  size_t cmp_length = std::min(obj_a_length, obj_b_length);
736
737
  int val = normalizeCompareVal(cmp_length > 0 ?
738
204720
                                memcmp(obj_a_data, obj_b_data, cmp_length) : 0,
739
409501
                                obj_a_length, obj_b_length);
740
409562
  args.GetReturnValue().Set(val);
741
}
742
743
744
// Computes the offset for starting an indexOf or lastIndexOf search.
745
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
746
// or -1 to signal that there is no possible match.
747
2436
int64_t IndexOfOffset(size_t length,
748
                      int64_t offset_i64,
749
                      int64_t needle_length,
750
                      bool is_forward) {
751
2436
  int64_t length_i64 = static_cast<int64_t>(length);
752
2436
  if (offset_i64 < 0) {
753
77
    if (offset_i64 + length_i64 >= 0) {
754
      // Negative offsets count backwards from the end of the buffer.
755
59
      return length_i64 + offset_i64;
756

18
    } else if (is_forward || needle_length == 0) {
757
      // indexOf from before the start of the buffer: search the whole buffer.
758
10
      return 0;
759
    } else {
760
      // lastIndexOf from before the start of the buffer: no match.
761
8
      return -1;
762
    }
763
  } else {
764
2359
    if (offset_i64 + needle_length <= length_i64) {
765
      // Valid positive offset.
766
2271
      return offset_i64;
767
88
    } else if (needle_length == 0) {
768
      // Out of buffer bounds, but empty needle: point to end of buffer.
769
10
      return length_i64;
770
78
    } else if (is_forward) {
771
      // indexOf from past the end of the buffer: no match.
772
15
      return -1;
773
    } else {
774
      // lastIndexOf from past the end of the buffer: search the whole buffer.
775
63
      return length_i64 - 1;
776
    }
777
  }
778
}
779
780
887
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
781
887
  Environment* env = Environment::GetCurrent(args);
782
887
  Isolate* isolate = env->isolate();
783
784
2661
  CHECK(args[1]->IsString());
785
1774
  CHECK(args[2]->IsNumber());
786
1774
  CHECK(args[4]->IsBoolean());
787
788
887
  enum encoding enc = ParseEncoding(isolate, args[3], UTF8);
789
790
920
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
791

7096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
792
793
1774
  Local<String> needle = args[1].As<String>();
794
2661
  int64_t offset_i64 = args[2].As<Integer>()->Value();
795
1774
  bool is_forward = args[4]->IsTrue();
796
797
887
  const char* haystack = ts_obj_data;
798
  // Round down to the nearest multiple of 2 in case of UCS2.
799
  const size_t haystack_length = (enc == UCS2) ?
800
887
      ts_obj_length &~ 1 : ts_obj_length;  // NOLINT(whitespace/operators)
801
802
  size_t needle_length;
803
1774
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
804
805
  int64_t opt_offset = IndexOfOffset(haystack_length,
806
                                     offset_i64,
807
                                     needle_length,
808
887
                                     is_forward);
809
810
887
  if (needle_length == 0) {
811
    // Match String#indexOf() and String#lastIndexOf() behavior.
812
24
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
813
8
    return;
814
  }
815
816
879
  if (haystack_length == 0) {
817
    return args.GetReturnValue().Set(-1);
818
  }
819
820
879
  if (opt_offset <= -1) {
821
20
    return args.GetReturnValue().Set(-1);
822
  }
823
869
  size_t offset = static_cast<size_t>(opt_offset);
824
869
  CHECK_LT(offset, haystack_length);
825

1736
  if ((is_forward && needle_length + offset > haystack_length) ||
826
867
      needle_length > haystack_length) {
827
30
    return args.GetReturnValue().Set(-1);
828
  }
829
830
854
  size_t result = haystack_length;
831
832
854
  if (enc == UCS2) {
833
85
    String::Value needle_value(isolate, needle);
834
85
    if (*needle_value == nullptr)
835
      return args.GetReturnValue().Set(-1);
836
837

85
    if (haystack_length < 2 || needle_value.length() < 1) {
838
      return args.GetReturnValue().Set(-1);
839
    }
840
841
85
    if (IsBigEndian()) {
842
      StringBytes::InlineDecoder decoder;
843
      if (decoder.Decode(env, needle, args[3], UCS2).IsNothing()) return;
844
      const uint16_t* decoded_string =
845
          reinterpret_cast<const uint16_t*>(decoder.out());
846
847
      if (decoded_string == nullptr)
848
        return args.GetReturnValue().Set(-1);
849
850
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
851
                            haystack_length / 2,
852
                            decoded_string,
853
                            decoder.size() / 2,
854
                            offset / 2,
855
                            is_forward);
856
    } else {
857
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
858
                            haystack_length / 2,
859
85
                            reinterpret_cast<const uint16_t*>(*needle_value),
860
85
                            needle_value.length(),
861
                            offset / 2,
862
255
                            is_forward);
863
    }
864
85
    result *= 2;
865
769
  } else if (enc == UTF8) {
866
757
    String::Utf8Value needle_value(isolate, needle);
867
757
    if (*needle_value == nullptr)
868
      return args.GetReturnValue().Set(-1);
869
870
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
871
                          haystack_length,
872
757
                          reinterpret_cast<const uint8_t*>(*needle_value),
873
                          needle_length,
874
                          offset,
875
1514
                          is_forward);
876
12
  } else if (enc == LATIN1) {
877
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
878
12
    if (needle_data == nullptr) {
879
      return args.GetReturnValue().Set(-1);
880
    }
881
    needle->WriteOneByte(
882
24
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
883
884
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
885
                          haystack_length,
886
                          needle_data,
887
                          needle_length,
888
                          offset,
889
12
                          is_forward);
890
12
    free(needle_data);
891
  }
892
893
  args.GetReturnValue().Set(
894
2562
      result == haystack_length ? -1 : static_cast<int>(result));
895
}
896
897
218
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
898
436
  CHECK(args[1]->IsObject());
899
436
  CHECK(args[2]->IsNumber());
900
436
  CHECK(args[4]->IsBoolean());
901
902
  enum encoding enc = ParseEncoding(args.GetIsolate(),
903
                                    args[3],
904
218
                                    UTF8);
905
906
248
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
907
218
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
908

1744
  SPREAD_BUFFER_ARG(args[0], ts_obj);
909

1744
  SPREAD_BUFFER_ARG(args[1], buf);
910
654
  int64_t offset_i64 = args[2].As<Integer>()->Value();
911
436
  bool is_forward = args[4]->IsTrue();
912
913
218
  const char* haystack = ts_obj_data;
914
218
  const size_t haystack_length = ts_obj_length;
915
218
  const char* needle = buf_data;
916
218
  const size_t needle_length = buf_length;
917
918
  int64_t opt_offset = IndexOfOffset(haystack_length,
919
                                     offset_i64,
920
                                     needle_length,
921
218
                                     is_forward);
922
923
218
  if (needle_length == 0) {
924
    // Match String#indexOf() and String#lastIndexOf() behavior.
925
36
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
926
12
    return;
927
  }
928
929
206
  if (haystack_length == 0) {
930
    return args.GetReturnValue().Set(-1);
931
  }
932
933
206
  if (opt_offset <= -1) {
934
18
    return args.GetReturnValue().Set(-1);
935
  }
936
197
  size_t offset = static_cast<size_t>(opt_offset);
937
197
  CHECK_LT(offset, haystack_length);
938

392
  if ((is_forward && needle_length + offset > haystack_length) ||
939
195
      needle_length > haystack_length) {
940
14
    return args.GetReturnValue().Set(-1);
941
  }
942
943
190
  size_t result = haystack_length;
944
945
190
  if (enc == UCS2) {
946

58
    if (haystack_length < 2 || needle_length < 2) {
947
4
      return args.GetReturnValue().Set(-1);
948
    }
949
    result = SearchString(
950
        reinterpret_cast<const uint16_t*>(haystack),
951
        haystack_length / 2,
952
        reinterpret_cast<const uint16_t*>(needle),
953
        needle_length / 2,
954
        offset / 2,
955
56
        is_forward);
956
56
    result *= 2;
957
  } else {
958
    result = SearchString(
959
        reinterpret_cast<const uint8_t*>(haystack),
960
        haystack_length,
961
        reinterpret_cast<const uint8_t*>(needle),
962
        needle_length,
963
        offset,
964
132
        is_forward);
965
  }
966
967
  args.GetReturnValue().Set(
968
564
      result == haystack_length ? -1 : static_cast<int>(result));
969
}
970
971
1332
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
972
2664
  CHECK(args[1]->IsUint32());
973
2664
  CHECK(args[2]->IsNumber());
974
2664
  CHECK(args[3]->IsBoolean());
975
976
1337
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
977

10648
  SPREAD_BUFFER_ARG(args[0], ts_obj);
978
979
3993
  uint32_t needle = args[1].As<Uint32>()->Value();
980
3993
  int64_t offset_i64 = args[2].As<Integer>()->Value();
981
2662
  bool is_forward = args[3]->IsTrue();
982
983
1331
  int64_t opt_offset = IndexOfOffset(ts_obj_length, offset_i64, 1, is_forward);
984

1331
  if (opt_offset <= -1 || ts_obj_length == 0) {
985
8
    return args.GetReturnValue().Set(-1);
986
  }
987
1327
  size_t offset = static_cast<size_t>(opt_offset);
988
1327
  CHECK_LT(offset, ts_obj_length);
989
990
  const void* ptr;
991
1327
  if (is_forward) {
992
1319
    ptr = memchr(ts_obj_data + offset, needle, ts_obj_length - offset);
993
  } else {
994
8
    ptr = node::stringsearch::MemrchrFill(ts_obj_data, needle, offset + 1);
995
  }
996
1327
  const char* ptr_char = static_cast<const char*>(ptr);
997
33
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - ts_obj_data)
998
4014
                                : -1);
999
}
1000
1001
1002
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1003
2
  Environment* env = Environment::GetCurrent(args);
1004
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1005

16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1006
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1007
4
  args.GetReturnValue().Set(args[0]);
1008
}
1009
1010
1011
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1012
2
  Environment* env = Environment::GetCurrent(args);
1013
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1014

16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1015
2
  SwapBytes32(ts_obj_data, ts_obj_length);
1016
4
  args.GetReturnValue().Set(args[0]);
1017
}
1018
1019
1020
2
void Swap64(const FunctionCallbackInfo<Value>& args) {
1021
2
  Environment* env = Environment::GetCurrent(args);
1022
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1023

16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1024
2
  SwapBytes64(ts_obj_data, ts_obj_length);
1025
4
  args.GetReturnValue().Set(args[0]);
1026
}
1027
1028
1029
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1030
// Used in TextEncoder.prototype.encode.
1031
21
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1032
21
  Environment* env = Environment::GetCurrent(args);
1033
21
  Isolate* isolate = env->isolate();
1034
21
  CHECK_GE(args.Length(), 1);
1035
63
  CHECK(args[0]->IsString());
1036
1037
42
  Local<String> str = args[0].As<String>();
1038
21
  size_t length = str->Utf8Length(isolate);
1039
21
  AllocatedBuffer buf = env->AllocateManaged(length);
1040
  str->WriteUtf8(isolate,
1041
                 buf.data(),
1042
                 -1,  // We are certain that `data` is sufficiently large
1043
                 nullptr,
1044
42
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1045
21
  auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1046
42
  args.GetReturnValue().Set(array);
1047
21
}
1048
1049
1050
4397
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1051
4397
  Environment* env = Environment::GetCurrent(args);
1052
1053
8794
  CHECK(args[0]->IsObject());
1054
8794
  Local<Object> proto = args[0].As<Object>();
1055
4397
  env->set_buffer_prototype_object(proto);
1056
4397
}
1057
1058
1059
4400
void Initialize(Local<Object> target,
1060
                Local<Value> unused,
1061
                Local<Context> context,
1062
                void* priv) {
1063
4400
  Environment* env = Environment::GetCurrent(context);
1064
1065
4400
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1066
4400
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1067
1068
4400
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1069
4400
  env->SetMethod(target, "copy", Copy);
1070
4400
  env->SetMethodNoSideEffect(target, "compare", Compare);
1071
4400
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1072
4400
  env->SetMethod(target, "fill", Fill);
1073
4400
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1074
4400
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1075
4400
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1076
1077
4400
  env->SetMethod(target, "swap16", Swap16);
1078
4400
  env->SetMethod(target, "swap32", Swap32);
1079
4400
  env->SetMethod(target, "swap64", Swap64);
1080
1081
4400
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1082
1083
  target->Set(env->context(),
1084
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1085
22000
              Integer::NewFromUnsigned(env->isolate(), kMaxLength)).FromJust();
1086
1087
  target->Set(env->context(),
1088
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1089
22000
              Integer::New(env->isolate(), String::kMaxLength)).FromJust();
1090
1091
4400
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1092
4400
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1093
4400
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1094
4400
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1095
4400
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1096
4400
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1097
1098
4400
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1099
4400
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1100
4400
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1101
4400
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1102
4400
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1103
4400
  env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1104
1105
  // It can be a nullptr when running inside an isolate where we
1106
  // do not own the ArrayBuffer allocator.
1107
4400
  if (ArrayBufferAllocator* allocator = env->isolate_data()->node_allocator()) {
1108
4400
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1109
    Local<ArrayBuffer> array_buffer = ArrayBuffer::New(
1110
4400
        env->isolate(), zero_fill_field, sizeof(*zero_fill_field));
1111
22000
    CHECK(target
1112
              ->Set(env->context(),
1113
                    FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
1114
                    Uint32Array::New(array_buffer, 0, 1))
1115
              .FromJust());
1116
  }
1117
4400
}
1118
1119
}  // anonymous namespace
1120
}  // namespace Buffer
1121
}  // namespace node
1122
1123
4282
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)