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: 482 530 90.9 %
Date: 2019-07-28 22:34:34 Branches: 387 630 61.4 %

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
34
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
17
CallbackInfo* CallbackInfo::New(Isolate* isolate,
116
                                Local<ArrayBuffer> object,
117
                                FreeCallback callback,
118
                                char* data,
119
                                void* hint) {
120
17
  return new CallbackInfo(isolate, object, callback, data, hint);
121
}
122
123
124
17
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
34
      hint_(hint) {
133
17
  ArrayBuffer::Contents obj_c = object->GetContents();
134
17
  CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
135
17
  if (object->ByteLength() != 0)
136
15
    CHECK_NOT_NULL(data_);
137
138
17
  persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
139
17
  isolate->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
140
17
}
141
142
143
17
void CallbackInfo::WeakCallback(
144
    const WeakCallbackInfo<CallbackInfo>& data) {
145
17
  CallbackInfo* self = data.GetParameter();
146
17
  self->WeakCallback(data.GetIsolate());
147
17
  delete self;
148
17
}
149
150
151
17
void CallbackInfo::WeakCallback(Isolate* isolate) {
152
17
  callback_(data_, hint_);
153
17
  int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
154
  isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
155
17
}
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
6431777
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
161
                                                   Local<Value> arg,
162
                                                   size_t def,
163
                                                   size_t* ret) {
164
12863554
  if (arg->IsUndefined()) {
165
1301292
    *ret = def;
166
1301292
    return Just(true);
167
  }
168
169
  int64_t tmp_i;
170
15391455
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
171
1
    return Nothing<bool>();
172
173
5130484
  if (tmp_i < 0)
174
4
    return Just(false);
175
176
  // Check that the result fits in a size_t.
177
5130480
  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
5130480
  *ret = static_cast<size_t>(tmp_i);
183
5130480
  return Just(true);
184
}
185
186
}  // anonymous namespace
187
188
// Buffer methods
189
190
11293365
bool HasInstance(Local<Value> val) {
191
11293365
  return val->IsArrayBufferView();
192
}
193
194
195
1088193
bool HasInstance(Local<Object> obj) {
196
1088193
  return obj->IsArrayBufferView();
197
}
198
199
200
298699
char* Data(Local<Value> val) {
201
298699
  CHECK(val->IsArrayBufferView());
202
298699
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
203
597398
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
204
597398
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
205
}
206
207
208
282115
char* Data(Local<Object> obj) {
209
282115
  CHECK(obj->IsArrayBufferView());
210
282115
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
211
564230
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
212
564230
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
213
}
214
215
216
226474
size_t Length(Local<Value> val) {
217
226474
  CHECK(val->IsArrayBufferView());
218
226474
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
219
226474
  return ui->ByteLength();
220
}
221
222
223
267903
size_t Length(Local<Object> obj) {
224
267903
  CHECK(obj->IsArrayBufferView());
225
267903
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
226
267903
  return ui->ByteLength();
227
}
228
229
230
58783
inline MaybeLocal<Uint8Array> New(Environment* env,
231
                                  Local<ArrayBuffer> ab,
232
                                  size_t byte_offset,
233
                                  size_t length) {
234
117566
  CHECK(!env->buffer_prototype_object().IsEmpty());
235
58783
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
236
  Maybe<bool> mb =
237
176349
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
238
58783
  if (mb.IsNothing())
239
    return MaybeLocal<Uint8Array>();
240
58783
  return ui;
241
}
242
243
244
176
MaybeLocal<Object> New(Isolate* isolate,
245
                       Local<String> string,
246
                       enum encoding enc) {
247
176
  EscapableHandleScope scope(isolate);
248
249
  size_t length;
250
352
  if (!StringBytes::Size(isolate, string, enc).To(&length))
251
    return Local<Object>();
252
176
  size_t actual = 0;
253
176
  char* data = nullptr;
254
255
176
  if (length > 0) {
256
176
    data = UncheckedMalloc(length);
257
258
176
    if (data == nullptr) {
259
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
260
      return Local<Object>();
261
    }
262
263
176
    actual = StringBytes::Write(isolate, data, length, string, enc);
264
176
    CHECK(actual <= length);
265
266
176
    if (actual == 0) {
267
1
      free(data);
268
1
      data = nullptr;
269
175
    } else if (actual < length) {
270
      data = node::Realloc(data, actual);
271
    }
272
  }
273
274
352
  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
14206
MaybeLocal<Object> New(Environment* env, size_t length) {
293
14206
  EscapableHandleScope scope(env->isolate());
294
295
  // V8 currently only allows a maximum Typed Array index of max Smi.
296
14206
  if (length > kMaxLength) {
297
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
298
    return Local<Object>();
299
  }
300
301
28412
  AllocatedBuffer ret(env);
302
14206
  if (length > 0) {
303
8955
    ret = env->AllocateManaged(length, false);
304
8955
    if (ret.data() == nullptr) {
305
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
306
      return Local<Object>();
307
    }
308
  }
309
310
28412
  return scope.EscapeMaybe(ret.ToBuffer());
311
}
312
313
314
7967
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
315
7967
  EscapableHandleScope handle_scope(isolate);
316
7967
  Environment* env = Environment::GetCurrent(isolate);
317
7967
  if (env == nullptr) {
318
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
319
1
    return MaybeLocal<Object>();
320
  }
321
  Local<Object> obj;
322
15932
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
323
7966
    return handle_scope.Escape(obj);
324
  return Local<Object>();
325
}
326
327
328
23576
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
329
23576
  EscapableHandleScope scope(env->isolate());
330
331
  // V8 currently only allows a maximum Typed Array index of max Smi.
332
23576
  if (length > kMaxLength) {
333
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
334
    return Local<Object>();
335
  }
336
337
47152
  AllocatedBuffer ret(env);
338
23576
  if (length > 0) {
339
23438
    CHECK_NOT_NULL(data);
340
23438
    ret = env->AllocateManaged(length, false);
341
23438
    if (ret.data() == nullptr) {
342
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
343
      return Local<Object>();
344
    }
345
23438
    memcpy(ret.data(), data, length);
346
  }
347
348
47152
  return scope.EscapeMaybe(ret.ToBuffer());
349
}
350
351
352
17
MaybeLocal<Object> New(Isolate* isolate,
353
                       char* data,
354
                       size_t length,
355
                       FreeCallback callback,
356
                       void* hint) {
357
17
  EscapableHandleScope handle_scope(isolate);
358
17
  Environment* env = Environment::GetCurrent(isolate);
359
17
  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
34
  if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj))
366
17
    return handle_scope.Escape(obj);
367
  return Local<Object>();
368
}
369
370
371
17
MaybeLocal<Object> New(Environment* env,
372
                       char* data,
373
                       size_t length,
374
                       FreeCallback callback,
375
                       void* hint) {
376
17
  EscapableHandleScope scope(env->isolate());
377
378
17
  if (length > kMaxLength) {
379
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
380
    callback(data, hint);
381
    return Local<Object>();
382
  }
383
384
17
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
385
17
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
386
387
17
  CallbackInfo::New(env->isolate(), ab, callback, data, hint);
388
389
17
  if (ui.IsEmpty())
390
    return MaybeLocal<Object>();
391
392
17
  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
176
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
398
176
  EscapableHandleScope handle_scope(isolate);
399
176
  Environment* env = Environment::GetCurrent(isolate);
400
176
  if (env == nullptr) {
401
    free(data);
402
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
403
    return MaybeLocal<Object>();
404
  }
405
  Local<Object> obj;
406
352
  if (Buffer::New(env, data, length, true).ToLocal(&obj))
407
176
    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
58766
MaybeLocal<Object> New(Environment* env,
415
                       char* data,
416
                       size_t length,
417
                       bool uses_malloc) {
418
58766
  if (length > 0) {
419
53152
    CHECK_NOT_NULL(data);
420
53152
    CHECK(length <= kMaxLength);
421
  }
422
423
58766
  if (uses_malloc) {
424
354
    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
354
      CHECK_NOT_NULL(env->isolate_data()->node_allocator());
433
354
      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
58766
                       ArrayBufferCreationMode::kInternalized);
442
117532
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
443
}
444
445
namespace {
446
447
176
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
448
528
  CHECK(args[0]->IsString());
449
528
  CHECK(args[1]->IsString());
450
451
  enum encoding enc = ParseEncoding(args.GetIsolate(),
452
                                    args[1].As<String>(),
453
352
                                    UTF8);
454
  Local<Object> buf;
455
528
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
456
352
    args.GetReturnValue().Set(buf);
457
176
}
458
459
460
template <encoding encoding>
461
512509
void StringSlice(const FunctionCallbackInfo<Value>& args) {
462
512509
  Environment* env = Environment::GetCurrent(args);
463
512509
  Isolate* isolate = env->isolate();
464
465



514333
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
466
512509
  ArrayBufferViewContents<char> buffer(args.This());
467
468



512509
  if (buffer.length() == 0)
469
3632
    return args.GetReturnValue().SetEmptyString();
470
471





















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



510693
  if (ret.IsEmpty()) {
481



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

2086206
  SPREAD_BUFFER_ARG(target_obj, target);
498
499
347701
  size_t target_start = 0;
500
347701
  size_t source_start = 0;
501
347701
  size_t source_end = 0;
502
503

1390802
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
504

1390800
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
505

1738490
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
506
                                          &source_end));
507
508
  // Copy 0 bytes; we're done
509

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

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

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

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



575688
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
629









4605472
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
630
631



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






2302736
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
639



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






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



575684
  if (max_length == 0)
650
8
    return args.GetReturnValue().Set(0);
651
652
  uint32_t written = StringBytes::Write(env->isolate(),
653
                                        ts_obj_data + offset,
654
                                        max_length,
655
                                        str,
656
                                        encoding,
657
575680
                                        nullptr);
658
1151360
  args.GetReturnValue().Set(written);
659
}
660
661
186762
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
662
186762
  Environment* env = Environment::GetCurrent(args);
663
560286
  CHECK(args[0]->IsString());
664
665
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
666
1120572
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
667
186762
}
668
669
// Normalize val to be an integer in the range of [1, -1] since
670
// implementations of memcmp() can vary by platform.
671
204817
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
672
204817
  if (val == 0) {
673
104787
    if (a_length > b_length)
674
6
      return 1;
675
104781
    else if (a_length < b_length)
676
6
      return -1;
677
  } else {
678
100030
    if (val > 0)
679
7
      return 1;
680
    else
681
100023
      return -1;
682
  }
683
104775
  return val;
684
}
685
686
9
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
687
9
  Environment* env = Environment::GetCurrent(args);
688
689
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
690
9
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
691
9
  ArrayBufferViewContents<char> source(args[0]);
692
9
  ArrayBufferViewContents<char> target(args[1]);
693
694
9
  size_t target_start = 0;
695
9
  size_t source_start = 0;
696
9
  size_t source_end = 0;
697
9
  size_t target_end = 0;
698
699

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

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

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

45
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
704
                                          &source_end));
705
706
9
  if (source_start > source.length())
707
    return THROW_ERR_OUT_OF_RANGE(
708
        env, "The value of \"sourceStart\" is out of range.");
709
9
  if (target_start > target.length())
710
    return THROW_ERR_OUT_OF_RANGE(
711
        env, "The value of \"targetStart\" is out of range.");
712
713
9
  CHECK_LE(source_start, source_end);
714
9
  CHECK_LE(target_start, target_end);
715
716
  size_t to_cmp =
717
18
      std::min(std::min(source_end - source_start, target_end - target_start),
718
27
               source.length() - source_start);
719
720
  int val = normalizeCompareVal(to_cmp > 0 ?
721
18
                                  memcmp(source.data() + source_start,
722
18
                                         target.data() + target_start,
723
18
                                         to_cmp) : 0,
724
                                source_end - source_start,
725
18
                                target_end - target_start);
726
727
18
  args.GetReturnValue().Set(val);
728
}
729
730
204809
void Compare(const FunctionCallbackInfo<Value> &args) {
731
204809
  Environment* env = Environment::GetCurrent(args);
732
733
204810
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
734
204808
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
735
204808
  ArrayBufferViewContents<char> a(args[0]);
736
204808
  ArrayBufferViewContents<char> b(args[1]);
737
738
204808
  size_t cmp_length = std::min(a.length(), b.length());
739
740
  int val = normalizeCompareVal(cmp_length > 0 ?
741
204745
                                memcmp(a.data(), b.data(), cmp_length) : 0,
742
409553
                                a.length(), b.length());
743
409616
  args.GetReturnValue().Set(val);
744
}
745
746
747
// Computes the offset for starting an indexOf or lastIndexOf search.
748
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
749
// or -1 to signal that there is no possible match.
750
14602
int64_t IndexOfOffset(size_t length,
751
                      int64_t offset_i64,
752
                      int64_t needle_length,
753
                      bool is_forward) {
754
14602
  int64_t length_i64 = static_cast<int64_t>(length);
755
14602
  if (offset_i64 < 0) {
756
77
    if (offset_i64 + length_i64 >= 0) {
757
      // Negative offsets count backwards from the end of the buffer.
758
59
      return length_i64 + offset_i64;
759

18
    } else if (is_forward || needle_length == 0) {
760
      // indexOf from before the start of the buffer: search the whole buffer.
761
10
      return 0;
762
    } else {
763
      // lastIndexOf from before the start of the buffer: no match.
764
8
      return -1;
765
    }
766
  } else {
767
14525
    if (offset_i64 + needle_length <= length_i64) {
768
      // Valid positive offset.
769
14437
      return offset_i64;
770
88
    } else if (needle_length == 0) {
771
      // Out of buffer bounds, but empty needle: point to end of buffer.
772
10
      return length_i64;
773
78
    } else if (is_forward) {
774
      // indexOf from past the end of the buffer: no match.
775
15
      return -1;
776
    } else {
777
      // lastIndexOf from past the end of the buffer: search the whole buffer.
778
63
      return length_i64 - 1;
779
    }
780
  }
781
}
782
783
891
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
784
891
  Environment* env = Environment::GetCurrent(args);
785
891
  Isolate* isolate = env->isolate();
786
787
2673
  CHECK(args[1]->IsString());
788
1782
  CHECK(args[2]->IsNumber());
789
1782
  CHECK(args[4]->IsBoolean());
790
791
891
  enum encoding enc = ParseEncoding(isolate, args[3], UTF8);
792
793
924
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
794
891
  ArrayBufferViewContents<char> buffer(args[0]);
795
796
1782
  Local<String> needle = args[1].As<String>();
797
2673
  int64_t offset_i64 = args[2].As<Integer>()->Value();
798
1782
  bool is_forward = args[4]->IsTrue();
799
800
891
  const char* haystack = buffer.data();
801
  // Round down to the nearest multiple of 2 in case of UCS2.
802
  const size_t haystack_length = (enc == UCS2) ?
803
891
      buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
804
805
  size_t needle_length;
806
1782
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
807
808
  int64_t opt_offset = IndexOfOffset(haystack_length,
809
                                     offset_i64,
810
                                     needle_length,
811
891
                                     is_forward);
812
813
891
  if (needle_length == 0) {
814
    // Match String#indexOf() and String#lastIndexOf() behavior.
815
24
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
816
8
    return;
817
  }
818
819
883
  if (haystack_length == 0) {
820
    return args.GetReturnValue().Set(-1);
821
  }
822
823
883
  if (opt_offset <= -1) {
824
20
    return args.GetReturnValue().Set(-1);
825
  }
826
873
  size_t offset = static_cast<size_t>(opt_offset);
827
873
  CHECK_LT(offset, haystack_length);
828

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

85
    if (haystack_length < 2 || needle_value.length() < 1) {
841
      return args.GetReturnValue().Set(-1);
842
    }
843
844
85
    if (IsBigEndian()) {
845
      StringBytes::InlineDecoder decoder;
846
      if (decoder.Decode(env, needle, args[3], UCS2).IsNothing()) return;
847
      const uint16_t* decoded_string =
848
          reinterpret_cast<const uint16_t*>(decoder.out());
849
850
      if (decoded_string == nullptr)
851
        return args.GetReturnValue().Set(-1);
852
853
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
854
                            haystack_length / 2,
855
                            decoded_string,
856
                            decoder.size() / 2,
857
                            offset / 2,
858
                            is_forward);
859
    } else {
860
      result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
861
                            haystack_length / 2,
862
85
                            reinterpret_cast<const uint16_t*>(*needle_value),
863
85
                            needle_value.length(),
864
                            offset / 2,
865
255
                            is_forward);
866
    }
867
85
    result *= 2;
868
773
  } else if (enc == UTF8) {
869
761
    String::Utf8Value needle_value(isolate, needle);
870
761
    if (*needle_value == nullptr)
871
      return args.GetReturnValue().Set(-1);
872
873
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
874
                          haystack_length,
875
761
                          reinterpret_cast<const uint8_t*>(*needle_value),
876
                          needle_length,
877
                          offset,
878
1522
                          is_forward);
879
12
  } else if (enc == LATIN1) {
880
12
    uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
881
12
    if (needle_data == nullptr) {
882
      return args.GetReturnValue().Set(-1);
883
    }
884
    needle->WriteOneByte(
885
24
        isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
886
887
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
888
                          haystack_length,
889
                          needle_data,
890
                          needle_length,
891
                          offset,
892
12
                          is_forward);
893
12
    free(needle_data);
894
  }
895
896
  args.GetReturnValue().Set(
897
2574
      result == haystack_length ? -1 : static_cast<int>(result));
898
}
899
900
218
void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
901
436
  CHECK(args[1]->IsObject());
902
436
  CHECK(args[2]->IsNumber());
903
436
  CHECK(args[4]->IsBoolean());
904
905
  enum encoding enc = ParseEncoding(args.GetIsolate(),
906
                                    args[3],
907
218
                                    UTF8);
908
909
248
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
910
218
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
911
218
  ArrayBufferViewContents<char> haystack_contents(args[0]);
912
218
  ArrayBufferViewContents<char> needle_contents(args[1]);
913
654
  int64_t offset_i64 = args[2].As<Integer>()->Value();
914
436
  bool is_forward = args[4]->IsTrue();
915
916
218
  const char* haystack = haystack_contents.data();
917
218
  const size_t haystack_length = haystack_contents.length();
918
218
  const char* needle = needle_contents.data();
919
218
  const size_t needle_length = needle_contents.length();
920
921
  int64_t opt_offset = IndexOfOffset(haystack_length,
922
                                     offset_i64,
923
                                     needle_length,
924
218
                                     is_forward);
925
926
218
  if (needle_length == 0) {
927
    // Match String#indexOf() and String#lastIndexOf() behavior.
928
36
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
929
12
    return;
930
  }
931
932
206
  if (haystack_length == 0) {
933
    return args.GetReturnValue().Set(-1);
934
  }
935
936
206
  if (opt_offset <= -1) {
937
18
    return args.GetReturnValue().Set(-1);
938
  }
939
197
  size_t offset = static_cast<size_t>(opt_offset);
940
197
  CHECK_LT(offset, haystack_length);
941

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

58
    if (haystack_length < 2 || needle_length < 2) {
950
4
      return args.GetReturnValue().Set(-1);
951
    }
952
    result = SearchString(
953
        reinterpret_cast<const uint16_t*>(haystack),
954
        haystack_length / 2,
955
        reinterpret_cast<const uint16_t*>(needle),
956
        needle_length / 2,
957
        offset / 2,
958
56
        is_forward);
959
56
    result *= 2;
960
  } else {
961
    result = SearchString(
962
        reinterpret_cast<const uint8_t*>(haystack),
963
        haystack_length,
964
        reinterpret_cast<const uint8_t*>(needle),
965
        needle_length,
966
        offset,
967
132
        is_forward);
968
  }
969
970
  args.GetReturnValue().Set(
971
564
      result == haystack_length ? -1 : static_cast<int>(result));
972
}
973
974
13494
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
975
26988
  CHECK(args[1]->IsUint32());
976
26988
  CHECK(args[2]->IsNumber());
977
26988
  CHECK(args[3]->IsBoolean());
978
979
13499
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
980
13493
  ArrayBufferViewContents<char> buffer(args[0]);
981
982
40479
  uint32_t needle = args[1].As<Uint32>()->Value();
983
40479
  int64_t offset_i64 = args[2].As<Integer>()->Value();
984
26986
  bool is_forward = args[3]->IsTrue();
985
986
  int64_t opt_offset =
987
13493
      IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
988

13493
  if (opt_offset <= -1 || buffer.length() == 0) {
989
8
    return args.GetReturnValue().Set(-1);
990
  }
991
13489
  size_t offset = static_cast<size_t>(opt_offset);
992
13489
  CHECK_LT(offset, buffer.length());
993
994
  const void* ptr;
995
13489
  if (is_forward) {
996
13481
    ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
997
  } else {
998
8
    ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
999
  }
1000
13489
  const char* ptr_char = static_cast<const char*>(ptr);
1001
33
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1002
40500
                                : -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
4961
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1055
4961
  Environment* env = Environment::GetCurrent(args);
1056
1057
9922
  CHECK(args[0]->IsObject());
1058
9922
  Local<Object> proto = args[0].As<Object>();
1059
4961
  env->set_buffer_prototype_object(proto);
1060
4961
}
1061
1062
1063
4962
void Initialize(Local<Object> target,
1064
                Local<Value> unused,
1065
                Local<Context> context,
1066
                void* priv) {
1067
4962
  Environment* env = Environment::GetCurrent(context);
1068
1069
4962
  env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1070
4962
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1071
1072
4962
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1073
4962
  env->SetMethod(target, "copy", Copy);
1074
4962
  env->SetMethodNoSideEffect(target, "compare", Compare);
1075
4962
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1076
4962
  env->SetMethod(target, "fill", Fill);
1077
4962
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1078
4962
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1079
4962
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1080
1081
4962
  env->SetMethod(target, "swap16", Swap16);
1082
4962
  env->SetMethod(target, "swap32", Swap32);
1083
4962
  env->SetMethod(target, "swap64", Swap64);
1084
1085
4962
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1086
1087
  target->Set(env->context(),
1088
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1089
24810
              Integer::NewFromUnsigned(env->isolate(), kMaxLength)).Check();
1090
1091
  target->Set(env->context(),
1092
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1093
24810
              Integer::New(env->isolate(), String::kMaxLength)).Check();
1094
1095
4962
  env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1096
4962
  env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1097
4962
  env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1098
4962
  env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1099
4962
  env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1100
4962
  env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1101
1102
4962
  env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1103
4962
  env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1104
4962
  env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1105
4962
  env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1106
4962
  env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1107
4962
  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
4962
  if (NodeArrayBufferAllocator* allocator =
1112
4962
          env->isolate_data()->node_allocator()) {
1113
4962
    uint32_t* zero_fill_field = allocator->zero_fill_field();
1114
    Local<ArrayBuffer> array_buffer = ArrayBuffer::New(
1115
4962
        env->isolate(), zero_fill_field, sizeof(*zero_fill_field));
1116
24810
    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
4962
}
1123
1124
}  // anonymous namespace
1125
}  // namespace Buffer
1126
}  // namespace node
1127
1128
4827
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)