GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/node_buffer.cc Lines: 475 523 90.8 %
Date: 2019-01-07 12:15:22 Branches: 447 728 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.h"
23
#include "node_buffer.h"
24
#include "node_errors.h"
25
26
#include "env-inl.h"
27
#include "string_bytes.h"
28
#include "string_search.h"
29
#include "util-inl.h"
30
#include "v8-profiler.h"
31
#include "v8.h"
32
33
#include <string.h>
34
#include <limits.h>
35
36
#define MIN(a, b) ((a) < (b) ? (a) : (b))
37
38
#define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
39
  THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
40
41
#define THROW_AND_RETURN_IF_OOB(r)                                          \
42
  do {                                                                      \
43
    if ((r).IsNothing()) return;                                            \
44
    if (!(r).FromJust())                                                    \
45
      return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
46
  } while (0)                                                               \
47
48
#define SLICE_START_END(env, start_arg, end_arg, end_max)                   \
49
  size_t start;                                                             \
50
  size_t end;                                                               \
51
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, start_arg, 0, &start));      \
52
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, end_arg, end_max, &end));    \
53
  if (end < start) end = start;                                             \
54
  THROW_AND_RETURN_IF_OOB(Just(end <= end_max));                            \
55
  size_t length = end - start;
56
57
namespace node {
58
59
namespace {
60
61
5513
inline void* BufferMalloc(size_t length) {
62
5513
  return per_process_opts->zero_fill_all_buffers ?
63
      node::UncheckedCalloc(length) :
64
5513
      node::UncheckedMalloc(length);
65
}
66
67
}  // namespace
68
69
namespace Buffer {
70
71
using v8::ArrayBuffer;
72
using v8::ArrayBufferCreationMode;
73
using v8::ArrayBufferView;
74
using v8::Context;
75
using v8::EscapableHandleScope;
76
using v8::FunctionCallbackInfo;
77
using v8::Integer;
78
using v8::Isolate;
79
using v8::Just;
80
using v8::Local;
81
using v8::Maybe;
82
using v8::MaybeLocal;
83
using v8::Nothing;
84
using v8::Object;
85
using v8::String;
86
using v8::Uint32;
87
using v8::Uint32Array;
88
using v8::Uint8Array;
89
using v8::Value;
90
using v8::WeakCallbackInfo;
91
92
namespace {
93
94
30
class CallbackInfo {
95
 public:
96
  static inline void Free(char* data, void* hint);
97
  static inline CallbackInfo* New(Isolate* isolate,
98
                                  Local<ArrayBuffer> object,
99
                                  FreeCallback callback,
100
                                  char* data,
101
                                  void* hint = 0);
102
 private:
103
  static void WeakCallback(const WeakCallbackInfo<CallbackInfo>&);
104
  inline void WeakCallback(Isolate* isolate);
105
  inline CallbackInfo(Isolate* isolate,
106
                      Local<ArrayBuffer> object,
107
                      FreeCallback callback,
108
                      char* data,
109
                      void* hint);
110
  Persistent<ArrayBuffer> persistent_;
111
  FreeCallback const callback_;
112
  char* const data_;
113
  void* const hint_;
114
  DISALLOW_COPY_AND_ASSIGN(CallbackInfo);
115
};
116
117
118
void CallbackInfo::Free(char* data, void*) {
119
  ::free(data);
120
}
121
122
123
15
CallbackInfo* CallbackInfo::New(Isolate* isolate,
124
                                Local<ArrayBuffer> object,
125
                                FreeCallback callback,
126
                                char* data,
127
                                void* hint) {
128
15
  return new CallbackInfo(isolate, object, callback, data, hint);
129
}
130
131
132
15
CallbackInfo::CallbackInfo(Isolate* isolate,
133
                           Local<ArrayBuffer> object,
134
                           FreeCallback callback,
135
                           char* data,
136
                           void* hint)
137
    : persistent_(isolate, object),
138
      callback_(callback),
139
      data_(data),
140
30
      hint_(hint) {
141
15
  ArrayBuffer::Contents obj_c = object->GetContents();
142
15
  CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
143
15
  if (object->ByteLength() != 0)
144
13
    CHECK_NOT_NULL(data_);
145
146
15
  persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
147
15
  isolate->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
148
15
}
149
150
151
15
void CallbackInfo::WeakCallback(
152
    const WeakCallbackInfo<CallbackInfo>& data) {
153
15
  CallbackInfo* self = data.GetParameter();
154
15
  self->WeakCallback(data.GetIsolate());
155
15
  delete self;
156
15
}
157
158
159
15
void CallbackInfo::WeakCallback(Isolate* isolate) {
160
15
  callback_(data_, hint_);
161
15
  int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
162
  isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
163
15
}
164
165
166
// Parse index for external array data. An empty Maybe indicates
167
// a pending exception. `false` indicates that the index is out-of-bounds.
168
2168628
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
169
                                                   Local<Value> arg,
170
                                                   size_t def,
171
                                                   size_t* ret) {
172
4337256
  if (arg->IsUndefined()) {
173
1124526
    *ret = def;
174
1124526
    return Just(true);
175
  }
176
177
  int64_t tmp_i;
178
3132307
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
179
1
    return Nothing<bool>();
180
181
1044101
  if (tmp_i < 0)
182
4
    return Just(false);
183
184
  // Check that the result fits in a size_t.
185
1044097
  const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
186
  // coverity[pointless_expression]
187
  if (static_cast<uint64_t>(tmp_i) > kSizeMax)
188
    return Just(false);
189
190
1044097
  *ret = static_cast<size_t>(tmp_i);
191
1044097
  return Just(true);
192
}
193
194
}  // anonymous namespace
195
196
// Buffer methods
197
198
2802840
bool HasInstance(Local<Value> val) {
199
2802840
  return val->IsArrayBufferView();
200
}
201
202
203
119492
bool HasInstance(Local<Object> obj) {
204
119492
  return obj->IsArrayBufferView();
205
}
206
207
208
257119
char* Data(Local<Value> val) {
209
257119
  CHECK(val->IsArrayBufferView());
210
257119
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
211
514238
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
212
514238
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
213
}
214
215
216
239953
char* Data(Local<Object> obj) {
217
239953
  CHECK(obj->IsArrayBufferView());
218
239953
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
219
479906
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
220
479906
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
221
}
222
223
224
228334
size_t Length(Local<Value> val) {
225
228334
  CHECK(val->IsArrayBufferView());
226
228334
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
227
228334
  return ui->ByteLength();
228
}
229
230
231
237020
size_t Length(Local<Object> obj) {
232
237020
  CHECK(obj->IsArrayBufferView());
233
237020
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
234
237020
  return ui->ByteLength();
235
}
236
237
238
3829
MaybeLocal<Object> New(Isolate* isolate,
239
                       Local<String> string,
240
                       enum encoding enc) {
241
3829
  EscapableHandleScope scope(isolate);
242
243
  size_t length;
244
7658
  if (!StringBytes::Size(isolate, string, enc).To(&length))
245
    return Local<Object>();
246
3829
  size_t actual = 0;
247
3829
  char* data = nullptr;
248
249
3829
  if (length > 0) {
250
3829
    data = static_cast<char*>(BufferMalloc(length));
251
252
3829
    if (data == nullptr) {
253
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
254
      return Local<Object>();
255
    }
256
257
3829
    actual = StringBytes::Write(isolate, data, length, string, enc);
258
3829
    CHECK(actual <= length);
259
260
3829
    if (actual == 0) {
261
1
      free(data);
262
1
      data = nullptr;
263
3828
    } else if (actual < length) {
264
      data = node::Realloc(data, actual);
265
    }
266
  }
267
268
  Local<Object> buf;
269
7658
  if (New(isolate, data, actual).ToLocal(&buf))
270
3829
    return scope.Escape(buf);
271
272
  // Object failed to be created. Clean up resources.
273
  free(data);
274
  return Local<Object>();
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
2085
MaybeLocal<Object> New(Environment* env, size_t length) {
293
2085
  EscapableHandleScope scope(env->isolate());
294
295
  // V8 currently only allows a maximum Typed Array index of max Smi.
296
2085
  if (length > kMaxLength) {
297
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
298
    return Local<Object>();
299
  }
300
301
  void* data;
302
2085
  if (length > 0) {
303
1684
    data = BufferMalloc(length);
304
1684
    if (data == nullptr) {
305
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
306
      return Local<Object>();
307
    }
308
  } else {
309
401
    data = nullptr;
310
  }
311
312
  Local<ArrayBuffer> ab =
313
    ArrayBuffer::New(env->isolate(),
314
        data,
315
        length,
316
2085
        ArrayBufferCreationMode::kInternalized);
317
  Local<Object> obj;
318
4170
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
319
2085
    return scope.Escape(obj);
320
  return Local<Object>();
321
}
322
323
324
1041
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
325
1041
  EscapableHandleScope handle_scope(isolate);
326
1041
  Environment* env = Environment::GetCurrent(isolate);
327
1041
  if (env == nullptr) {
328
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
329
1
    return MaybeLocal<Object>();
330
  }
331
  Local<Object> obj;
332
2080
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
333
1040
    return handle_scope.Escape(obj);
334
  return Local<Object>();
335
}
336
337
338
16218
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
339
16218
  EscapableHandleScope scope(env->isolate());
340
341
  // V8 currently only allows a maximum Typed Array index of max Smi.
342
16218
  if (length > kMaxLength) {
343
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
344
    return Local<Object>();
345
  }
346
347
  void* new_data;
348
16218
  if (length > 0) {
349
16082
    CHECK_NOT_NULL(data);
350
16082
    new_data = node::UncheckedMalloc(length);
351
16082
    if (new_data == nullptr) {
352
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
353
      return Local<Object>();
354
    }
355
16082
    memcpy(new_data, data, length);
356
  } else {
357
136
    new_data = nullptr;
358
  }
359
360
  Local<ArrayBuffer> ab =
361
    ArrayBuffer::New(env->isolate(),
362
        new_data,
363
        length,
364
16218
        ArrayBufferCreationMode::kInternalized);
365
  Local<Object> obj;
366
32436
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
367
16218
    return scope.Escape(obj);
368
  return Local<Object>();
369
}
370
371
372
15
MaybeLocal<Object> New(Isolate* isolate,
373
                       char* data,
374
                       size_t length,
375
                       FreeCallback callback,
376
                       void* hint) {
377
15
  EscapableHandleScope handle_scope(isolate);
378
15
  Environment* env = Environment::GetCurrent(isolate);
379
15
  if (env == nullptr) {
380
    callback(data, hint);
381
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
382
    return MaybeLocal<Object>();
383
  }
384
  Local<Object> obj;
385
30
  if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj))
386
15
    return handle_scope.Escape(obj);
387
  return Local<Object>();
388
}
389
390
391
15
MaybeLocal<Object> New(Environment* env,
392
                       char* data,
393
                       size_t length,
394
                       FreeCallback callback,
395
                       void* hint) {
396
15
  EscapableHandleScope scope(env->isolate());
397
398
15
  if (length > kMaxLength) {
399
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
400
    callback(data, hint);
401
    return Local<Object>();
402
  }
403
404
15
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
405
  // `Neuter()`ing is required here to prevent materialization of the backing
406
  // store in v8. `nullptr` buffers are not writable, so this is semantically
407
  // correct.
408
15
  if (data == nullptr)
409
1
    ab->Neuter();
410
15
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
411
412
15
  CallbackInfo::New(env->isolate(), ab, callback, data, hint);
413
414
15
  if (ui.IsEmpty())
415
    return MaybeLocal<Object>();
416
417
15
  return scope.Escape(ui.ToLocalChecked());
418
}
419
420
421
3867
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
422
3867
  EscapableHandleScope handle_scope(isolate);
423
3867
  Environment* env = Environment::GetCurrent(isolate);
424
3867
  if (env == nullptr) {
425
    free(data);
426
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
427
    return MaybeLocal<Object>();
428
  }
429
  Local<Object> obj;
430
7734
  if (Buffer::New(env, data, length).ToLocal(&obj))
431
3867
    return handle_scope.Escape(obj);
432
  return Local<Object>();
433
}
434
435
436
5321
MaybeLocal<Object> New(Environment* env, char* data, size_t length) {
437
5321
  if (length > 0) {
438
5104
    CHECK_NOT_NULL(data);
439
5104
    CHECK(length <= kMaxLength);
440
  }
441
442
  Local<ArrayBuffer> ab =
443
      ArrayBuffer::New(env->isolate(),
444
                       data,
445
                       length,
446
5321
                       ArrayBufferCreationMode::kInternalized);
447
10642
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
448
}
449
450
namespace {
451
452
3829
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
453
11487
  CHECK(args[0]->IsString());
454
11487
  CHECK(args[1]->IsString());
455
456
  enum encoding enc = ParseEncoding(args.GetIsolate(),
457
                                    args[1].As<String>(),
458
7658
                                    UTF8);
459
  Local<Object> buf;
460
11487
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
461
7658
    args.GetReturnValue().Set(buf);
462
3829
}
463
464
465
template <encoding encoding>
466
72090
void StringSlice(const FunctionCallbackInfo<Value>& args) {
467
72090
  Environment* env = Environment::GetCurrent(args);
468
72090
  Isolate* isolate = env->isolate();
469
470



72155
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
471









576719
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
472
473



72089
  if (ts_obj_length == 0)
474
114
    return args.GetReturnValue().SetEmptyString();
475
476





















720326
  SLICE_START_END(env, args[0], args[1], ts_obj_length)
477
478
  Local<Value> error;
479
  MaybeLocal<Value> ret =
480
      StringBytes::Encode(isolate,
481
                          ts_obj_data + start,
482
                          length,
483
                          encoding,
484
72032
                          &error);
485



72033
  if (ret.IsEmpty()) {
486



8
    CHECK(!error.IsEmpty());
487
8
    isolate->ThrowException(error);
488
8
    return;
489
  }
490
144050
  args.GetReturnValue().Set(ret.ToLocalChecked());
491
}
492
493
494
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
495
281803
void Copy(const FunctionCallbackInfo<Value> &args) {
496
281803
  Environment* env = Environment::GetCurrent(args);
497
498
283459
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
499
281803
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
500
563604
  Local<Object> buffer_obj = args[0].As<Object>();
501
563604
  Local<Object> target_obj = args[1].As<Object>();
502

1690812
  SPREAD_BUFFER_ARG(buffer_obj, ts_obj);
503

1690812
  SPREAD_BUFFER_ARG(target_obj, target);
504
505
  size_t target_start;
506
  size_t source_start;
507
  size_t source_end;
508
509

1127206
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
510

1127204
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
511

1127196
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], ts_obj_length,
512
                                          &source_end));
513
514
  // Copy 0 bytes; we're done
515

281799
  if (target_start >= target_length || source_start >= source_end)
516
3302
    return args.GetReturnValue().Set(0);
517
518
280148
  if (source_start > ts_obj_length)
519
    return THROW_ERR_OUT_OF_RANGE(
520
1
        env, "The value of \"sourceStart\" is out of range.");
521
522
280147
  if (source_end - source_start > target_length - target_start)
523
4
    source_end = source_start + target_length - target_start;
524
525
280147
  uint32_t to_copy = MIN(MIN(source_end - source_start,
526
                             target_length - target_start),
527
                             ts_obj_length - source_start);
528
529
280147
  memmove(target_data + target_start, ts_obj_data + source_start, to_copy);
530
560294
  args.GetReturnValue().Set(to_copy);
531
}
532
533
534
5227
void Fill(const FunctionCallbackInfo<Value>& args) {
535
5227
  Environment* env = Environment::GetCurrent(args);
536
5227
  Local<Context> ctx = env->context();
537
538
10319
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
539

41816
  SPREAD_BUFFER_ARG(args[0], ts_obj);
540
541
  uint32_t start;
542
15681
  if (!args[2]->Uint32Value(ctx).To(&start)) return;
543
  uint32_t end;
544
15681
  if (!args[3]->Uint32Value(ctx).To(&end)) return;
545
5227
  size_t fill_length = end - start;
546
  Local<String> str_obj;
547
  size_t str_length;
548
  enum encoding enc;
549
550
  // OOB Check. Throw the error in JS.
551

5227
  if (start > end || fill_length + start > ts_obj_length)
552
6
    return args.GetReturnValue().Set(-2);
553
554
  // First check if Buffer has been passed.
555
5224
  if (Buffer::HasInstance(args[1])) {
556

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



47407
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
634









379216
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
635
636



142206
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
637
638
189608
  Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
639
640
  size_t offset;
641
  size_t max_length;
642
643






189608
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
644



47402
  if (offset > ts_obj_length) {
645
    return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
646
1
        env, "\"offset\" is outside of buffer bounds");
647
  }
648
649






237005
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
650
                                          &max_length));
651
652
47401
  max_length = MIN(ts_obj_length - offset, max_length);
653
654



47401
  if (max_length == 0)
655
8
    return args.GetReturnValue().Set(0);
656
657
  uint32_t written = StringBytes::Write(env->isolate(),
658
                                        ts_obj_data + offset,
659
                                        max_length,
660
                                        str,
661
                                        encoding,
662
47397
                                        nullptr);
663
94794
  args.GetReturnValue().Set(written);
664
}
665
666
60466
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
667
60466
  Environment* env = Environment::GetCurrent(args);
668
181401
  CHECK(args[0]->IsString());
669
670
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
671
362802
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
672
60467
}
673
674
// Normalize val to be an integer in the range of [1, -1] since
675
// implementations of memcmp() can vary by platform.
676
1760
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
677
1760
  if (val == 0) {
678
1731
    if (a_length > b_length)
679
6
      return 1;
680
1725
    else if (a_length < b_length)
681
6
      return -1;
682
  } else {
683
29
    if (val > 0)
684
7
      return 1;
685
    else
686
22
      return -1;
687
  }
688
1719
  return val;
689
}
690
691
11
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
692
11
  Environment* env = Environment::GetCurrent(args);
693
694
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
695
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
696

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

88
  SPREAD_BUFFER_ARG(args[1], target);
698
699
  size_t target_start;
700
  size_t source_start;
701
  size_t source_end;
702
  size_t target_end;
703
704

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

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

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target_length,
707
                                          &target_end));
708

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], ts_obj_length,
709
                                          &source_end));
710
711
11
  if (source_start > ts_obj_length)
712
    return THROW_ERR_OUT_OF_RANGE(
713
        env, "The value of \"sourceStart\" is out of range.");
714
11
  if (target_start > target_length)
715
    return THROW_ERR_OUT_OF_RANGE(
716
        env, "The value of \"targetStart\" is out of range.");
717
718
11
  CHECK_LE(source_start, source_end);
719
11
  CHECK_LE(target_start, target_end);
720
721
11
  size_t to_cmp = MIN(MIN(source_end - source_start,
722
                      target_end - target_start),
723
                      ts_obj_length - source_start);
724
725
  int val = normalizeCompareVal(to_cmp > 0 ?
726
                                  memcmp(ts_obj_data + source_start,
727
                                         target_data + target_start,
728
11
                                         to_cmp) : 0,
729
                                source_end - source_start,
730
22
                                target_end - target_start);
731
732
22
  args.GetReturnValue().Set(val);
733
}
734
735
1750
void Compare(const FunctionCallbackInfo<Value> &args) {
736
1750
  Environment* env = Environment::GetCurrent(args);
737
738
1751
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
739
1749
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
740

13992
  SPREAD_BUFFER_ARG(args[0], obj_a);
741

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

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

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

1734
  if ((is_forward && needle_length + offset > haystack_length) ||
834
866
      needle_length > haystack_length) {
835
30
    return args.GetReturnValue().Set(-1);
836
  }
837
838
853
  size_t result = haystack_length;
839
840
853
  if (enc == UCS2) {
841
85
    String::Value needle_value(isolate, needle);
842
85
    if (*needle_value == nullptr)
843
      return args.GetReturnValue().Set(-1);
844
845

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

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

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

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

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

9728
  SPREAD_BUFFER_ARG(args[0], ts_obj);
986
987
3648
  uint32_t needle = args[1].As<Uint32>()->Value();
988
3648
  int64_t offset_i64 = args[2].As<Integer>()->Value();
989
2432
  bool is_forward = args[3]->IsTrue();
990
991
1216
  int64_t opt_offset = IndexOfOffset(ts_obj_length, offset_i64, 1, is_forward);
992

1216
  if (opt_offset <= -1 || ts_obj_length == 0) {
993
8
    return args.GetReturnValue().Set(-1);
994
  }
995
1212
  size_t offset = static_cast<size_t>(opt_offset);
996
1212
  CHECK_LT(offset, ts_obj_length);
997
998
  const void* ptr;
999
1212
  if (is_forward) {
1000
1204
    ptr = memchr(ts_obj_data + offset, needle, ts_obj_length - offset);
1001
  } else {
1002
8
    ptr = node::stringsearch::MemrchrFill(ts_obj_data, needle, offset + 1);
1003
  }
1004
1212
  const char* ptr_char = static_cast<const char*>(ptr);
1005
33
  args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - ts_obj_data)
1006
3669
                                : -1);
1007
}
1008
1009
1010
2
void Swap16(const FunctionCallbackInfo<Value>& args) {
1011
2
  Environment* env = Environment::GetCurrent(args);
1012
4
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1013

16
  SPREAD_BUFFER_ARG(args[0], ts_obj);
1014
2
  SwapBytes16(ts_obj_data, ts_obj_length);
1015
4
  args.GetReturnValue().Set(args[0]);
1016
}
1017
1018
1019
2
void Swap32(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
  SwapBytes32(ts_obj_data, ts_obj_length);
1024
4
  args.GetReturnValue().Set(args[0]);
1025
}
1026
1027
1028
2
void Swap64(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
  SwapBytes64(ts_obj_data, ts_obj_length);
1033
4
  args.GetReturnValue().Set(args[0]);
1034
}
1035
1036
1037
// Encode a single string to a UTF-8 Uint8Array (not Buffer).
1038
// Used in TextEncoder.prototype.encode.
1039
19
static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1040
19
  Environment* env = Environment::GetCurrent(args);
1041
19
  Isolate* isolate = env->isolate();
1042
19
  CHECK_GE(args.Length(), 1);
1043
57
  CHECK(args[0]->IsString());
1044
1045
38
  Local<String> str = args[0].As<String>();
1046
19
  size_t length = str->Utf8Length(isolate);
1047
19
  char* data = node::UncheckedMalloc(length);
1048
  str->WriteUtf8(isolate,
1049
                 data,
1050
                 -1,  // We are certain that `data` is sufficiently large
1051
                 nullptr,
1052
19
                 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1053
  auto array_buf = ArrayBuffer::New(
1054
19
      isolate, data, length, ArrayBufferCreationMode::kInternalized);
1055
19
  auto array = Uint8Array::New(array_buf, 0, length);
1056
38
  args.GetReturnValue().Set(array);
1057
19
}
1058
1059
1060
// pass Buffer object to load prototype methods
1061
3661
void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
1062
3661
  Environment* env = Environment::GetCurrent(args);
1063
1064
7322
  CHECK(args[0]->IsObject());
1065
7322
  Local<Object> proto = args[0].As<Object>();
1066
3661
  env->set_buffer_prototype_object(proto);
1067
1068
3661
  env->SetMethodNoSideEffect(proto, "asciiSlice", StringSlice<ASCII>);
1069
3660
  env->SetMethodNoSideEffect(proto, "base64Slice", StringSlice<BASE64>);
1070
3661
  env->SetMethodNoSideEffect(proto, "latin1Slice", StringSlice<LATIN1>);
1071
3661
  env->SetMethodNoSideEffect(proto, "hexSlice", StringSlice<HEX>);
1072
3661
  env->SetMethodNoSideEffect(proto, "ucs2Slice", StringSlice<UCS2>);
1073
3661
  env->SetMethodNoSideEffect(proto, "utf8Slice", StringSlice<UTF8>);
1074
1075
3661
  env->SetMethod(proto, "asciiWrite", StringWrite<ASCII>);
1076
3661
  env->SetMethod(proto, "base64Write", StringWrite<BASE64>);
1077
3661
  env->SetMethod(proto, "latin1Write", StringWrite<LATIN1>);
1078
3661
  env->SetMethod(proto, "hexWrite", StringWrite<HEX>);
1079
3661
  env->SetMethod(proto, "ucs2Write", StringWrite<UCS2>);
1080
3661
  env->SetMethod(proto, "utf8Write", StringWrite<UTF8>);
1081
1082
3661
  if (auto zero_fill_field = env->isolate_data()->zero_fill_field()) {
1083
7322
    CHECK(args[1]->IsObject());
1084
7322
    auto binding_object = args[1].As<Object>();
1085
    auto array_buffer = ArrayBuffer::New(env->isolate(),
1086
                                         zero_fill_field,
1087
3661
                                         sizeof(*zero_fill_field));
1088
3661
    auto name = FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill");
1089
3661
    auto value = Uint32Array::New(array_buffer, 0, 1);
1090
10983
    CHECK(binding_object->Set(env->context(), name, value).FromJust());
1091
  }
1092
3661
}
1093
1094
1095
3662
void Initialize(Local<Object> target,
1096
                Local<Value> unused,
1097
                Local<Context> context,
1098
                void* priv) {
1099
3662
  Environment* env = Environment::GetCurrent(context);
1100
1101
3662
  env->SetMethod(target, "setupBufferJS", SetupBufferJS);
1102
3662
  env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1103
1104
3662
  env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1105
3662
  env->SetMethod(target, "copy", Copy);
1106
3662
  env->SetMethodNoSideEffect(target, "compare", Compare);
1107
3662
  env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1108
3662
  env->SetMethod(target, "fill", Fill);
1109
3662
  env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1110
3662
  env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1111
3662
  env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1112
1113
3662
  env->SetMethod(target, "swap16", Swap16);
1114
3662
  env->SetMethod(target, "swap32", Swap32);
1115
3662
  env->SetMethod(target, "swap64", Swap64);
1116
1117
3662
  env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1118
1119
  target->Set(env->context(),
1120
              FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1121
18310
              Integer::NewFromUnsigned(env->isolate(), kMaxLength)).FromJust();
1122
1123
  target->Set(env->context(),
1124
              FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1125
18310
              Integer::New(env->isolate(), String::kMaxLength)).FromJust();
1126
3662
}
1127
1128
}  // anonymous namespace
1129
}  // namespace Buffer
1130
}  // namespace node
1131
1132
3596
NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)