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: 484 533 90.8 %
Date: 2019-02-23 22:23:05 Branches: 438 720 60.8 %

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
58
namespace {
59
60
7782
inline void* BufferMalloc(size_t length) {
61
7782
  return per_process::cli_options->zero_fill_all_buffers ?
62
             node::UncheckedCalloc(length) :
63
7782
             node::UncheckedMalloc(length);
64
}
65
66
}  // namespace
67
68
namespace Buffer {
69
70
using v8::ArrayBuffer;
71
using v8::ArrayBufferCreationMode;
72
using v8::ArrayBufferView;
73
using v8::Context;
74
using v8::EscapableHandleScope;
75
using v8::FunctionCallbackInfo;
76
using v8::Integer;
77
using v8::Isolate;
78
using v8::Just;
79
using v8::Local;
80
using v8::Maybe;
81
using v8::MaybeLocal;
82
using v8::Nothing;
83
using v8::Object;
84
using v8::String;
85
using v8::Uint32;
86
using v8::Uint32Array;
87
using v8::Uint8Array;
88
using v8::Value;
89
using v8::WeakCallbackInfo;
90
91
namespace {
92
93
30
class CallbackInfo {
94
 public:
95
  static inline void Free(char* data, void* hint);
96
  static inline CallbackInfo* New(Isolate* isolate,
97
                                  Local<ArrayBuffer> object,
98
                                  FreeCallback callback,
99
                                  char* data,
100
                                  void* hint = nullptr);
101
 private:
102
  static void WeakCallback(const WeakCallbackInfo<CallbackInfo>&);
103
  inline void WeakCallback(Isolate* isolate);
104
  inline CallbackInfo(Isolate* isolate,
105
                      Local<ArrayBuffer> object,
106
                      FreeCallback callback,
107
                      char* data,
108
                      void* hint);
109
  Persistent<ArrayBuffer> persistent_;
110
  FreeCallback const callback_;
111
  char* const data_;
112
  void* const hint_;
113
  DISALLOW_COPY_AND_ASSIGN(CallbackInfo);
114
};
115
116
117
void CallbackInfo::Free(char* data, void*) {
118
  ::free(data);
119
}
120
121
122
15
CallbackInfo* CallbackInfo::New(Isolate* isolate,
123
                                Local<ArrayBuffer> object,
124
                                FreeCallback callback,
125
                                char* data,
126
                                void* hint) {
127
15
  return new CallbackInfo(isolate, object, callback, data, hint);
128
}
129
130
131
15
CallbackInfo::CallbackInfo(Isolate* isolate,
132
                           Local<ArrayBuffer> object,
133
                           FreeCallback callback,
134
                           char* data,
135
                           void* hint)
136
    : persistent_(isolate, object),
137
      callback_(callback),
138
      data_(data),
139
30
      hint_(hint) {
140
15
  ArrayBuffer::Contents obj_c = object->GetContents();
141
15
  CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
142
15
  if (object->ByteLength() != 0)
143
13
    CHECK_NOT_NULL(data_);
144
145
15
  persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
146
15
  isolate->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
147
15
}
148
149
150
15
void CallbackInfo::WeakCallback(
151
    const WeakCallbackInfo<CallbackInfo>& data) {
152
15
  CallbackInfo* self = data.GetParameter();
153
15
  self->WeakCallback(data.GetIsolate());
154
15
  delete self;
155
15
}
156
157
158
15
void CallbackInfo::WeakCallback(Isolate* isolate) {
159
15
  callback_(data_, hint_);
160
15
  int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
161
  isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
162
15
}
163
164
165
// Parse index for external array data. An empty Maybe indicates
166
// a pending exception. `false` indicates that the index is out-of-bounds.
167
3154423
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
168
                                                   Local<Value> arg,
169
                                                   size_t def,
170
                                                   size_t* ret) {
171
6308846
  if (arg->IsUndefined()) {
172
1248168
    *ret = def;
173
1248168
    return Just(true);
174
  }
175
176
  int64_t tmp_i;
177
5718765
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
178
1
    return Nothing<bool>();
179
180
1906254
  if (tmp_i < 0)
181
4
    return Just(false);
182
183
  // Check that the result fits in a size_t.
184
1906250
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
185
  // coverity[pointless_expression]
186
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
187
    return Just(false);
188
189
1906250
  *ret = static_cast<size_t>(tmp_i);
190
1906250
  return Just(true);
191
}
192
193
}  // anonymous namespace
194
195
// Buffer methods
196
197
7916883
bool HasInstance(Local<Value> val) {
198
7916883
  return val->IsArrayBufferView();
199
}
200
201
202
293651
bool HasInstance(Local<Object> obj) {
203
293651
  return obj->IsArrayBufferView();
204
}
205
206
207
797512
char* Data(Local<Value> val) {
208
797512
  CHECK(val->IsArrayBufferView());
209
797512
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
210
1595024
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
211
1595024
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
212
}
213
214
215
378075
char* Data(Local<Object> obj) {
216
378075
  CHECK(obj->IsArrayBufferView());
217
378075
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
218
756150
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
219
756150
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
220
}
221
222
223
765728
size_t Length(Local<Value> val) {
224
765728
  CHECK(val->IsArrayBufferView());
225
765728
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
226
765728
  return ui->ByteLength();
227
}
228
229
230
374100
size_t Length(Local<Object> obj) {
231
374100
  CHECK(obj->IsArrayBufferView());
232
374100
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
233
374100
  return ui->ByteLength();
234
}
235
236
237
49085
inline MaybeLocal<Uint8Array> New(Environment* env,
238
                                  Local<ArrayBuffer> ab,
239
                                  size_t byte_offset,
240
                                  size_t length) {
241
98170
  CHECK(!env->buffer_prototype_object().IsEmpty());
242
49085
  Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
243
  Maybe<bool> mb =
244
147255
      ui->SetPrototype(env->context(), env->buffer_prototype_object());
245
49085
  if (mb.IsNothing())
246
    return MaybeLocal<Uint8Array>();
247
49085
  return ui;
248
}
249
250
251
4836
MaybeLocal<Object> New(Isolate* isolate,
252
                       Local<String> string,
253
                       enum encoding enc) {
254
4836
  EscapableHandleScope scope(isolate);
255
256
  size_t length;
257
9672
  if (!StringBytes::Size(isolate, string, enc).To(&length))
258
    return Local<Object>();
259
4836
  size_t actual = 0;
260
4836
  char* data = nullptr;
261
262
4836
  if (length > 0) {
263
4836
    data = static_cast<char*>(BufferMalloc(length));
264
265
4836
    if (data == nullptr) {
266
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
267
      return Local<Object>();
268
    }
269
270
4836
    actual = StringBytes::Write(isolate, data, length, string, enc);
271
4836
    CHECK(actual <= length);
272
273
4836
    if (actual == 0) {
274
1
      free(data);
275
1
      data = nullptr;
276
4835
    } else if (actual < length) {
277
      data = node::Realloc(data, actual);
278
    }
279
  }
280
281
  Local<Object> buf;
282
9672
  if (New(isolate, data, actual).ToLocal(&buf))
283
4836
    return scope.Escape(buf);
284
285
  // Object failed to be created. Clean up resources.
286
  free(data);
287
  return Local<Object>();
288
}
289
290
291
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
292
1
  EscapableHandleScope handle_scope(isolate);
293
  Local<Object> obj;
294
1
  Environment* env = Environment::GetCurrent(isolate);
295
1
  if (env == nullptr) {
296
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
297
    return MaybeLocal<Object>();
298
  }
299
2
  if (Buffer::New(env, length).ToLocal(&obj))
300
1
    return handle_scope.Escape(obj);
301
  return Local<Object>();
302
}
303
304
305
3975
MaybeLocal<Object> New(Environment* env, size_t length) {
306
3975
  EscapableHandleScope scope(env->isolate());
307
308
  // V8 currently only allows a maximum Typed Array index of max Smi.
309
3975
  if (length > kMaxLength) {
310
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
311
    return Local<Object>();
312
  }
313
314
  void* data;
315
3975
  if (length > 0) {
316
2946
    data = BufferMalloc(length);
317
2946
    if (data == nullptr) {
318
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
319
      return Local<Object>();
320
    }
321
  } else {
322
1029
    data = nullptr;
323
  }
324
325
  Local<ArrayBuffer> ab =
326
    ArrayBuffer::New(env->isolate(),
327
        data,
328
        length,
329
3975
        ArrayBufferCreationMode::kInternalized);
330
  Local<Object> obj;
331
7950
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
332
3975
    return scope.Escape(obj);
333
  return Local<Object>();
334
}
335
336
337
3362
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
338
3362
  EscapableHandleScope handle_scope(isolate);
339
3362
  Environment* env = Environment::GetCurrent(isolate);
340
3362
  if (env == nullptr) {
341
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
342
1
    return MaybeLocal<Object>();
343
  }
344
  Local<Object> obj;
345
6722
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
346
3361
    return handle_scope.Escape(obj);
347
  return Local<Object>();
348
}
349
350
351
18734
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
352
18734
  EscapableHandleScope scope(env->isolate());
353
354
  // V8 currently only allows a maximum Typed Array index of max Smi.
355
18734
  if (length > kMaxLength) {
356
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
357
    return Local<Object>();
358
  }
359
360
  void* new_data;
361
18734
  if (length > 0) {
362
18596
    CHECK_NOT_NULL(data);
363
18596
    new_data = node::UncheckedMalloc(length);
364
18596
    if (new_data == nullptr) {
365
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
366
      return Local<Object>();
367
    }
368
18596
    memcpy(new_data, data, length);
369
  } else {
370
138
    new_data = nullptr;
371
  }
372
373
  Local<ArrayBuffer> ab =
374
    ArrayBuffer::New(env->isolate(),
375
        new_data,
376
        length,
377
18734
        ArrayBufferCreationMode::kInternalized);
378
  Local<Object> obj;
379
37468
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
380
18734
    return scope.Escape(obj);
381
  return Local<Object>();
382
}
383
384
385
15
MaybeLocal<Object> New(Isolate* isolate,
386
                       char* data,
387
                       size_t length,
388
                       FreeCallback callback,
389
                       void* hint) {
390
15
  EscapableHandleScope handle_scope(isolate);
391
15
  Environment* env = Environment::GetCurrent(isolate);
392
15
  if (env == nullptr) {
393
    callback(data, hint);
394
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
395
    return MaybeLocal<Object>();
396
  }
397
  Local<Object> obj;
398
30
  if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj))
399
15
    return handle_scope.Escape(obj);
400
  return Local<Object>();
401
}
402
403
404
15
MaybeLocal<Object> New(Environment* env,
405
                       char* data,
406
                       size_t length,
407
                       FreeCallback callback,
408
                       void* hint) {
409
15
  EscapableHandleScope scope(env->isolate());
410
411
15
  if (length > kMaxLength) {
412
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
413
    callback(data, hint);
414
    return Local<Object>();
415
  }
416
417
15
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
418
15
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
419
420
15
  CallbackInfo::New(env->isolate(), ab, callback, data, hint);
421
422
15
  if (ui.IsEmpty())
423
    return MaybeLocal<Object>();
424
425
15
  return scope.Escape(ui.ToLocalChecked());
426
}
427
428
429
8892
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
430
8892
  EscapableHandleScope handle_scope(isolate);
431
8892
  Environment* env = Environment::GetCurrent(isolate);
432
8892
  if (env == nullptr) {
433
    free(data);
434
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
435
    return MaybeLocal<Object>();
436
  }
437
  Local<Object> obj;
438
17784
  if (Buffer::New(env, data, length).ToLocal(&obj))
439
8892
    return handle_scope.Escape(obj);
440
  return Local<Object>();
441
}
442
443
444
26361
MaybeLocal<Object> New(Environment* env, char* data, size_t length) {
445
26361
  if (length > 0) {
446
26140
    CHECK_NOT_NULL(data);
447
26140
    CHECK(length <= kMaxLength);
448
  }
449
450
  Local<ArrayBuffer> ab =
451
      ArrayBuffer::New(env->isolate(),
452
                       data,
453
                       length,
454
26361
                       ArrayBufferCreationMode::kInternalized);
455
52722
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
456
}
457
458
namespace {
459
460
4836
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
461
14508
  CHECK(args[0]->IsString());
462
14508
  CHECK(args[1]->IsString());
463
464
  enum encoding enc = ParseEncoding(args.GetIsolate(),
465
                                    args[1].As<String>(),
466
9672
                                    UTF8);
467
  Local<Object> buf;
468
14508
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
469
9672
    args.GetReturnValue().Set(buf);
470
4836
}
471
472
473
template <encoding encoding>
474
130092
void StringSlice(const FunctionCallbackInfo<Value>& args) {
475
130092
  Environment* env = Environment::GetCurrent(args);
476
130092
  Isolate* isolate = env->isolate();
477
478



130301
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
479









1040736
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
480
481



130092
  if (ts_obj_length == 0)
482
402
    return args.GetReturnValue().SetEmptyString();
483
484





















1428801
  SLICE_START_END(env, args[0], args[1], ts_obj_length)
485
486
  Local<Value> error;
487
  MaybeLocal<Value> ret =
488
      StringBytes::Encode(isolate,
489
                          ts_obj_data + start,
490
                          length,
491
                          encoding,
492
129891
                          &error);
493



129891
  if (ret.IsEmpty()) {
494



8
    CHECK(!error.IsEmpty());
495
8
    isolate->ThrowException(error);
496
8
    return;
497
  }
498
259766
  args.GetReturnValue().Set(ret.ToLocalChecked());
499
}
500
501
502
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
503
330092
void Copy(const FunctionCallbackInfo<Value> &args) {
504
330092
  Environment* env = Environment::GetCurrent(args);
505
506
330590
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
507
330092
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
508
660182
  Local<Object> buffer_obj = args[0].As<Object>();
509
660182
  Local<Object> target_obj = args[1].As<Object>();
510

1980546
  SPREAD_BUFFER_ARG(buffer_obj, ts_obj);
511

1980546
  SPREAD_BUFFER_ARG(target_obj, target);
512
513
330091
  size_t target_start = 0;
514
330091
  size_t source_start = 0;
515
330091
  size_t source_end = 0;
516
517

1320362
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
518

1320360
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
519

1320352
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], ts_obj_length,
520
                                          &source_end));
521
522
  // Copy 0 bytes; we're done
523

330088
  if (target_start >= target_length || source_start >= source_end)
524
986
    return args.GetReturnValue().Set(0);
525
526
329595
  if (source_start > ts_obj_length)
527
    return THROW_ERR_OUT_OF_RANGE(
528
1
        env, "The value of \"sourceStart\" is out of range.");
529
530
329594
  if (source_end - source_start > target_length - target_start)
531
6
    source_end = source_start + target_length - target_start;
532
533
  uint32_t to_copy = std::min(
534
659188
      std::min(source_end - source_start, target_length - target_start),
535
988782
      ts_obj_length - source_start);
536
537
329594
  memmove(target_data + target_start, ts_obj_data + source_start, to_copy);
538
659188
  args.GetReturnValue().Set(to_copy);
539
}
540
541
542
805262
void Fill(const FunctionCallbackInfo<Value>& args) {
543
805262
  Environment* env = Environment::GetCurrent(args);
544
805262
  Local<Context> ctx = env->context();
545
546
1610388
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
547

6442096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
548
549
  uint32_t start;
550
2415786
  if (!args[2]->Uint32Value(ctx).To(&start)) return;
551
  uint32_t end;
552
2415786
  if (!args[3]->Uint32Value(ctx).To(&end)) return;
553
805262
  size_t fill_length = end - start;
554
  Local<String> str_obj;
555
  size_t str_length;
556
  enum encoding enc;
557
558
  // OOB Check. Throw the error in JS.
559

805262
  if (start > end || fill_length + start > ts_obj_length)
560
6
    return args.GetReturnValue().Set(-2);
561
562
  // First check if Buffer has been passed.
563
805259
  if (Buffer::HasInstance(args[1])) {
564

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



163564
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
643









1308472
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
644
645



490677
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
646
647
654236
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
648
649
  size_t offset;
650
  size_t max_length;
651
652






654236
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
653



163559
  if (offset > ts_obj_length) {
654
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
655
1
        env, "\"offset\" is outside of buffer bounds");
656
  }
657
658






817790
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
659
                                          &max_length));
660
661
163558
  max_length = std::min(ts_obj_length - offset, max_length);
662
663



163558
  if (max_length == 0)
664
8
    return args.GetReturnValue().Set(0);
665
666
  uint32_t written = StringBytes::Write(env->isolate(),
667
                                        ts_obj_data + offset,
668
                                        max_length,
669
                                        str,
670
                                        encoding,
671
163554
                                        nullptr);
672
327108
  args.GetReturnValue().Set(written);
673
}
674
675
180643
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
676
180643
  Environment* env = Environment::GetCurrent(args);
677
541929
  CHECK(args[0]->IsString());
678
679
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
680
1083858
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
681
180643
}
682
683
// Normalize val to be an integer in the range of [1, -1] since
684
// implementations of memcmp() can vary by platform.
685
204792
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
686
204792
  if (val == 0) {
687
104760
    if (a_length > b_length)
688
6
      return 1;
689
104754
    else if (a_length < b_length)
690
6
      return -1;
691
  } else {
692
100032
    if (val > 0)
693
7
      return 1;
694
    else
695
100025
      return -1;
696
  }
697
104748
  return val;
698
}
699
700
11
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
701
11
  Environment* env = Environment::GetCurrent(args);
702
703
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
704
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
705

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

88
  SPREAD_BUFFER_ARG(args[1], target);
707
708
11
  size_t target_start = 0;
709
11
  size_t source_start = 0;
710
11
  size_t source_end = 0;
711
11
  size_t target_end = 0;
712
713

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

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

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target_length,
716
                                          &target_end));
717

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], ts_obj_length,
718
                                          &source_end));
719
720
11
  if (source_start > ts_obj_length)
721
    return THROW_ERR_OUT_OF_RANGE(
722
        env, "The value of \"sourceStart\" is out of range.");
723
11
  if (target_start > target_length)
724
    return THROW_ERR_OUT_OF_RANGE(
725
        env, "The value of \"targetStart\" is out of range.");
726
727
11
  CHECK_LE(source_start, source_end);
728
11
  CHECK_LE(target_start, target_end);
729
730
  size_t to_cmp =
731
22
      std::min(std::min(source_end - source_start, target_end - target_start),
732
33
               ts_obj_length - source_start);
733
734
  int val = normalizeCompareVal(to_cmp > 0 ?
735
                                  memcmp(ts_obj_data + source_start,
736
                                         target_data + target_start,
737
11
                                         to_cmp) : 0,
738
                                source_end - source_start,
739
22
                                target_end - target_start);
740
741
22
  args.GetReturnValue().Set(val);
742
}
743
744
204782
void Compare(const FunctionCallbackInfo<Value> &args) {
745
204782
  Environment* env = Environment::GetCurrent(args);
746
747
204783
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
748
204781
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
749

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

1638248
  SPREAD_BUFFER_ARG(args[1], obj_b);
751
752
204781
  size_t cmp_length = std::min(obj_a_length, obj_b_length);
753
754
  int val = normalizeCompareVal(cmp_length > 0 ?
755
204720
                                memcmp(obj_a_data, obj_b_data, cmp_length) : 0,
756
409501
                                obj_a_length, obj_b_length);
757
409562
  args.GetReturnValue().Set(val);
758
}
759
760
761
// Computes the offset for starting an indexOf or lastIndexOf search.
762
// Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
763
// or -1 to signal that there is no possible match.
764
2442
int64_t IndexOfOffset(size_t length,
765
                      int64_t offset_i64,
766
                      int64_t needle_length,
767
                      bool is_forward) {
768
2442
  int64_t length_i64 = static_cast<int64_t>(length);
769
2442
  if (offset_i64 < 0) {
770
77
    if (offset_i64 + length_i64 >= 0) {
771
      // Negative offsets count backwards from the end of the buffer.
772
59
      return length_i64 + offset_i64;
773

18
    } else if (is_forward || needle_length == 0) {
774
      // indexOf from before the start of the buffer: search the whole buffer.
775
10
      return 0;
776
    } else {
777
      // lastIndexOf from before the start of the buffer: no match.
778
8
      return -1;
779
    }
780
  } else {
781
2365
    if (offset_i64 + needle_length <= length_i64) {
782
      // Valid positive offset.
783
2277
      return offset_i64;
784
88
    } else if (needle_length == 0) {
785
      // Out of buffer bounds, but empty needle: point to end of buffer.
786
10
      return length_i64;
787
78
    } else if (is_forward) {
788
      // indexOf from past the end of the buffer: no match.
789
15
      return -1;
790
    } else {
791
      // lastIndexOf from past the end of the buffer: search the whole buffer.
792
63
      return length_i64 - 1;
793
    }
794
  }
795
}
796
797
887
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
798
887
  Environment* env = Environment::GetCurrent(args);
799
887
  Isolate* isolate = env->isolate();
800
801
2661
  CHECK(args[1]->IsString());
802
1774
  CHECK(args[2]->IsNumber());
803
1774
  CHECK(args[4]->IsBoolean());
804
805
887
  enum encoding enc = ParseEncoding(isolate, args[3], UTF8);
806
807
920
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
808

7096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
809
810
1774
  Local<String> needle = args[1].As<String>();
811
2661
  int64_t offset_i64 = args[2].As<Integer>()->Value();
812
1774
  bool is_forward = args[4]->IsTrue();
813
814
887
  const char* haystack = ts_obj_data;
815
  // Round down to the nearest multiple of 2 in case of UCS2.
816
  const size_t haystack_length = (enc == UCS2) ?
817
887
      ts_obj_length &~ 1 : ts_obj_length;  // NOLINT(whitespace/operators)
818
819
  size_t needle_length;
820
1774
  if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
821
822
  int64_t opt_offset = IndexOfOffset(haystack_length,
823
                                     offset_i64,
824
                                     needle_length,
825
887
                                     is_forward);
826
827
887
  if (needle_length == 0) {
828
    // Match String#indexOf() and String#lastIndexOf() behavior.
829
24
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
830
8
    return;
831
  }
832
833
879
  if (haystack_length == 0) {
834
    return args.GetReturnValue().Set(-1);
835
  }
836
837
879
  if (opt_offset <= -1) {
838
20
    return args.GetReturnValue().Set(-1);
839
  }
840
869
  size_t offset = static_cast<size_t>(opt_offset);
841
869
  CHECK_LT(offset, haystack_length);
842

1736
  if ((is_forward && needle_length + offset > haystack_length) ||
843
867
      needle_length > haystack_length) {
844
30
    return args.GetReturnValue().Set(-1);
845
  }
846
847
854
  size_t result = haystack_length;
848
849
854
  if (enc == UCS2) {
850
85
    String::Value needle_value(isolate, needle);
851
85
    if (*needle_value == nullptr)
852
      return args.GetReturnValue().Set(-1);
853
854

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

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

1744
  SPREAD_BUFFER_ARG(args[1], buf);
927
654
  int64_t offset_i64 = args[2].As<Integer>()->Value();
928
436
  bool is_forward = args[4]->IsTrue();
929
930
218
  const char* haystack = ts_obj_data;
931
218
  const size_t haystack_length = ts_obj_length;
932
218
  const char* needle = buf_data;
933
218
  const size_t needle_length = buf_length;
934
935
  int64_t opt_offset = IndexOfOffset(haystack_length,
936
                                     offset_i64,
937
                                     needle_length,
938
218
                                     is_forward);
939
940
218
  if (needle_length == 0) {
941
    // Match String#indexOf() and String#lastIndexOf() behavior.
942
36
    args.GetReturnValue().Set(static_cast<double>(opt_offset));
943
12
    return;
944
  }
945
946
206
  if (haystack_length == 0) {
947
    return args.GetReturnValue().Set(-1);
948
  }
949
950
206
  if (opt_offset <= -1) {
951
18
    return args.GetReturnValue().Set(-1);
952
  }
953
197
  size_t offset = static_cast<size_t>(opt_offset);
954
197
  CHECK_LT(offset, haystack_length);
955

392
  if ((is_forward && needle_length + offset > haystack_length) ||
956
195
      needle_length > haystack_length) {
957
14
    return args.GetReturnValue().Set(-1);
958
  }
959
960
190
  size_t result = haystack_length;
961
962
190
  if (enc == UCS2) {
963

58
    if (haystack_length < 2 || needle_length < 2) {
964
4
      return args.GetReturnValue().Set(-1);
965
    }
966
    result = SearchString(
967
        reinterpret_cast<const uint16_t*>(haystack),
968
        haystack_length / 2,
969
        reinterpret_cast<const uint16_t*>(needle),
970
        needle_length / 2,
971
        offset / 2,
972
56
        is_forward);
973
56
    result *= 2;
974
  } else {
975
    result = SearchString(
976
        reinterpret_cast<const uint8_t*>(haystack),
977
        haystack_length,
978
        reinterpret_cast<const uint8_t*>(needle),
979
        needle_length,
980
        offset,
981
132
        is_forward);
982
  }
983
984
  args.GetReturnValue().Set(
985
564
      result == haystack_length ? -1 : static_cast<int>(result));
986
}
987
988
1338
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
989
2676
  CHECK(args[1]->IsUint32());
990
2676
  CHECK(args[2]->IsNumber());
991
2676
  CHECK(args[3]->IsBoolean());
992
993
1343
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
994

10696
  SPREAD_BUFFER_ARG(args[0], ts_obj);
995
996
4011
  uint32_t needle = args[1].As<Uint32>()->Value();
997
4011
  int64_t offset_i64 = args[2].As<Integer>()->Value();
998
2674
  bool is_forward = args[3]->IsTrue();
999
1000
1337
  int64_t opt_offset = IndexOfOffset(ts_obj_length, offset_i64, 1, is_forward);
1001

1337
  if (opt_offset <= -1 || ts_obj_length == 0) {
1002
8
    return args.GetReturnValue().Set(-1);
1003
  }
1004
1333
  size_t offset = static_cast<size_t>(opt_offset);
1005
1333
  CHECK_LT(offset, ts_obj_length);
1006
1007
  const void* ptr;
1008
1333
  if (is_forward) {
1009
1325
    ptr = memchr(ts_obj_data + offset, needle, ts_obj_length - offset);
1010
  } else {
1011
8
    ptr = node::stringsearch::MemrchrFill(ts_obj_data, needle, offset + 1);
1012
  }
1013
1333
  const char* ptr_char = static_cast<const char*>(ptr);
1014
33
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - ts_obj_data)
1015
4032
                                : -1);
1016
}
1017
1018
1019
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1020
2
  Environment* env = Environment::GetCurrent(args);
1021
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1022

16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1023
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1024
4
  args.GetReturnValue().Set(args[0]);
1025
}
1026
1027
1028
2
void Swap32(const FunctionCallbackInfo<Value>& args) {
1029
2
  Environment* env = Environment::GetCurrent(args);
1030
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1031

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

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