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



548625
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
466









4383464
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
467
468



547933
  if (ts_obj_length == 0)
469
1368
    return args.GetReturnValue().SetEmptyString();
470
471





















6019739
  SLICE_START_END(env, args[0], args[1], ts_obj_length)
472
473
  Local<Value> error;
474
  MaybeLocal<Value> ret =
475
      StringBytes::Encode(isolate,
476
                          ts_obj_data + start,
477
                          length,
478
                          encoding,
479
547249
                          &error);
480



547249
  if (ret.IsEmpty()) {
481



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

2087952
  SPREAD_BUFFER_ARG(buffer_obj, ts_obj);
498

2087952
  SPREAD_BUFFER_ARG(target_obj, target);
499
500
347992
  size_t target_start = 0;
501
347992
  size_t source_start = 0;
502
347992
  size_t source_end = 0;
503
504

1391966
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
505

1391964
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
506

1391956
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], ts_obj_length,
507
                                          &source_end));
508
509
  // Copy 0 bytes; we're done
510

347989
  if (target_start >= target_length || source_start >= source_end)
511
872
    return args.GetReturnValue().Set(0);
512
513
347553
  if (source_start > ts_obj_length)
514
    return THROW_ERR_OUT_OF_RANGE(
515
1
        env, "The value of \"sourceStart\" is out of range.");
516
517
347552
  if (source_end - source_start > target_length - target_start)
518
6
    source_end = source_start + target_length - target_start;
519
520
  uint32_t to_copy = std::min(
521
695104
      std::min(source_end - source_start, target_length - target_start),
522
1042656
      ts_obj_length - source_start);
523
524
347552
  memmove(target_data + target_start, ts_obj_data + source_start, to_copy);
525
695104
  args.GetReturnValue().Set(to_copy);
526
}
527
528
529
805173
void Fill(const FunctionCallbackInfo<Value>& args) {
530
805173
  Environment* env = Environment::GetCurrent(args);
531
805173
  Local<Context> ctx = env->context();
532
533
1610210
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
534

6441384
  SPREAD_BUFFER_ARG(args[0], ts_obj);
535
536
  uint32_t start;
537
2415519
  if (!args[2]->Uint32Value(ctx).To(&start)) return;
538
  uint32_t end;
539
2415519
  if (!args[3]->Uint32Value(ctx).To(&end)) return;
540
805173
  size_t fill_length = end - start;
541
  Local<String> str_obj;
542
  size_t str_length;
543
  enum encoding enc;
544
545
  // OOB Check. Throw the error in JS.
546

805173
  if (start > end || fill_length + start > ts_obj_length)
547
6
    return args.GetReturnValue().Set(-2);
548
549
  // First check if Buffer has been passed.
550
805170
  if (Buffer::HasInstance(args[1])) {
551

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



601572
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
630









4812544
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
631
632



1804704
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
633
634
2406272
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
635
636
  size_t offset;
637
  size_t max_length;
638
639






2406272
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
640



601568
  if (offset > ts_obj_length) {
641
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
642
        env, "\"offset\" is outside of buffer bounds");
643
  }
644
645






3007840
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
646
                                          &max_length));
647
648
601568
  max_length = std::min(ts_obj_length - offset, max_length);
649
650



601568
  if (max_length == 0)
651
8
    return args.GetReturnValue().Set(0);
652
653
  uint32_t written = StringBytes::Write(env->isolate(),
654
                                        ts_obj_data + offset,
655
                                        max_length,
656
                                        str,
657
                                        encoding,
658
601564
                                        nullptr);
659
1203128
  args.GetReturnValue().Set(written);
660
}
661
662
185748
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
663
185748
  Environment* env = Environment::GetCurrent(args);
664
557244
  CHECK(args[0]->IsString());
665
666
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
667
1114488
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
668
185748
}
669
670
// Normalize val to be an integer in the range of [1, -1] since
671
// implementations of memcmp() can vary by platform.
672
204825
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
673
204825
  if (val == 0) {
674
104794
    if (a_length > b_length)
675
6
      return 1;
676
104788
    else if (a_length < b_length)
677
6
      return -1;
678
  } else {
679
100031
    if (val > 0)
680
7
      return 1;
681
    else
682
100024
      return -1;
683
  }
684
104782
  return val;
685
}
686
687
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
688
9
  Environment* env = Environment::GetCurrent(args);
689
690
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
691
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
692

72
  SPREAD_BUFFER_ARG(args[0], ts_obj);
693

72
  SPREAD_BUFFER_ARG(args[1], target);
694
695
9
  size_t target_start = 0;
696
9
  size_t source_start = 0;
697
9
  size_t source_end = 0;
698
9
  size_t target_end = 0;
699
700

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

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

36
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target_length,
703
                                          &target_end));
704

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

1638528
  SPREAD_BUFFER_ARG(args[0], obj_a);
737

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

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

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

1738
  if ((is_forward && needle_length + offset > haystack_length) ||
830
868
      needle_length > haystack_length) {
831
30
    return args.GetReturnValue().Set(-1);
832
  }
833
834
855
  size_t result = haystack_length;
835
836
855
  if (enc == UCS2) {
837
85
    String::Value needle_value(isolate, needle);
838
85
    if (*needle_value == nullptr)
839
      return args.GetReturnValue().Set(-1);
840
841

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

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

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

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

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

107816
  SPREAD_BUFFER_ARG(args[0], ts_obj);
982
983
40431
  uint32_t needle = args[1].As<Uint32>()->Value();
984
40431
  int64_t offset_i64 = args[2].As<Integer>()->Value();
985
26954
  bool is_forward = args[3]->IsTrue();
986
987
13477
  int64_t opt_offset = IndexOfOffset(ts_obj_length, offset_i64, 1, is_forward);
988

13477
  if (opt_offset <= -1 || ts_obj_length == 0) {
989
8
    return args.GetReturnValue().Set(-1);
990
  }
991
13473
  size_t offset = static_cast<size_t>(opt_offset);
992
13473
  CHECK_LT(offset, ts_obj_length);
993
994
  const void* ptr;
995
13473
  if (is_forward) {
996
13465
    ptr = memchr(ts_obj_data + offset, needle, ts_obj_length - offset);
997
  } else {
998
8
    ptr = node::stringsearch::MemrchrFill(ts_obj_data, needle, offset + 1);
999
  }
1000
13473
  const char* ptr_char = static_cast<const char*>(ptr);
1001
33
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - ts_obj_data)
1002
40452
                                : -1);
1003
}
1004
1005
1006
6
void Swap16(const FunctionCallbackInfo<Value>& args) {
1007
6
  Environment* env = Environment::GetCurrent(args);
1008
12
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1009

48
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1010
6
  SwapBytes16(ts_obj_data, ts_obj_length);
1011
12
  args.GetReturnValue().Set(args[0]);
1012
}
1013
1014
1015
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1016
2
  Environment* env = Environment::GetCurrent(args);
1017
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1018

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

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