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: 478 526 90.9 %
Date: 2019-02-13 22:28:58 Branches: 436 716 60.9 %

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
8294
inline void* BufferMalloc(size_t length) {
61
8294
  return per_process::cli_options->zero_fill_all_buffers ?
62
             node::UncheckedCalloc(length) :
63
8294
             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
4691785
inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
168
                                                   Local<Value> arg,
169
                                                   size_t def,
170
                                                   size_t* ret) {
171
9383570
  if (arg->IsUndefined()) {
172
1249026
    *ret = def;
173
1249026
    return Just(true);
174
  }
175
176
  int64_t tmp_i;
177
10328277
  if (!arg->IntegerValue(env->context()).To(&tmp_i))
178
1
    return Nothing<bool>();
179
180
3442758
  if (tmp_i < 0)
181
4
    return Just(false);
182
183
  // Check that the result fits in a size_t.
184
3442754
  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
3442754
  *ret = static_cast<size_t>(tmp_i);
190
3442754
  return Just(true);
191
}
192
193
}  // anonymous namespace
194
195
// Buffer methods
196
197
8939310
bool HasInstance(Local<Value> val) {
198
8939310
  return val->IsArrayBufferView();
199
}
200
201
202
677999
bool HasInstance(Local<Object> obj) {
203
677999
  return obj->IsArrayBufferView();
204
}
205
206
207
802631
char* Data(Local<Value> val) {
208
802631
  CHECK(val->IsArrayBufferView());
209
802631
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
210
1605262
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
211
1605262
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
212
}
213
214
215
780621
char* Data(Local<Object> obj) {
216
780621
  CHECK(obj->IsArrayBufferView());
217
780621
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
218
1561242
  ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
219
1561242
  return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
220
}
221
222
223
768142
size_t Length(Local<Value> val) {
224
768142
  CHECK(val->IsArrayBufferView());
225
768142
  Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
226
768142
  return ui->ByteLength();
227
}
228
229
230
775064
size_t Length(Local<Object> obj) {
231
775064
  CHECK(obj->IsArrayBufferView());
232
775064
  Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
233
775064
  return ui->ByteLength();
234
}
235
236
237
4551
MaybeLocal<Object> New(Isolate* isolate,
238
                       Local<String> string,
239
                       enum encoding enc) {
240
4551
  EscapableHandleScope scope(isolate);
241
242
  size_t length;
243
9102
  if (!StringBytes::Size(isolate, string, enc).To(&length))
244
    return Local<Object>();
245
4551
  size_t actual = 0;
246
4551
  char* data = nullptr;
247
248
4551
  if (length > 0) {
249
4551
    data = static_cast<char*>(BufferMalloc(length));
250
251
4551
    if (data == nullptr) {
252
      THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
253
      return Local<Object>();
254
    }
255
256
4551
    actual = StringBytes::Write(isolate, data, length, string, enc);
257
4551
    CHECK(actual <= length);
258
259
4551
    if (actual == 0) {
260
1
      free(data);
261
1
      data = nullptr;
262
4550
    } else if (actual < length) {
263
      data = node::Realloc(data, actual);
264
    }
265
  }
266
267
  Local<Object> buf;
268
9102
  if (New(isolate, data, actual).ToLocal(&buf))
269
4551
    return scope.Escape(buf);
270
271
  // Object failed to be created. Clean up resources.
272
  free(data);
273
  return Local<Object>();
274
}
275
276
277
1
MaybeLocal<Object> New(Isolate* isolate, size_t length) {
278
1
  EscapableHandleScope handle_scope(isolate);
279
  Local<Object> obj;
280
1
  Environment* env = Environment::GetCurrent(isolate);
281
1
  if (env == nullptr) {
282
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
283
    return MaybeLocal<Object>();
284
  }
285
2
  if (Buffer::New(env, length).ToLocal(&obj))
286
1
    return handle_scope.Escape(obj);
287
  return Local<Object>();
288
}
289
290
291
5557
MaybeLocal<Object> New(Environment* env, size_t length) {
292
5557
  EscapableHandleScope scope(env->isolate());
293
294
  // V8 currently only allows a maximum Typed Array index of max Smi.
295
5557
  if (length > kMaxLength) {
296
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
297
    return Local<Object>();
298
  }
299
300
  void* data;
301
5557
  if (length > 0) {
302
3743
    data = BufferMalloc(length);
303
3743
    if (data == nullptr) {
304
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
305
      return Local<Object>();
306
    }
307
  } else {
308
1814
    data = nullptr;
309
  }
310
311
  Local<ArrayBuffer> ab =
312
    ArrayBuffer::New(env->isolate(),
313
        data,
314
        length,
315
5557
        ArrayBufferCreationMode::kInternalized);
316
  Local<Object> obj;
317
11114
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
318
5557
    return scope.Escape(obj);
319
  return Local<Object>();
320
}
321
322
323
3348
MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
324
3348
  EscapableHandleScope handle_scope(isolate);
325
3348
  Environment* env = Environment::GetCurrent(isolate);
326
3348
  if (env == nullptr) {
327
1
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
328
1
    return MaybeLocal<Object>();
329
  }
330
  Local<Object> obj;
331
6694
  if (Buffer::Copy(env, data, length).ToLocal(&obj))
332
3347
    return handle_scope.Escape(obj);
333
  return Local<Object>();
334
}
335
336
337
18712
MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
338
18712
  EscapableHandleScope scope(env->isolate());
339
340
  // V8 currently only allows a maximum Typed Array index of max Smi.
341
18712
  if (length > kMaxLength) {
342
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
343
    return Local<Object>();
344
  }
345
346
  void* new_data;
347
18712
  if (length > 0) {
348
18574
    CHECK_NOT_NULL(data);
349
18574
    new_data = node::UncheckedMalloc(length);
350
18574
    if (new_data == nullptr) {
351
      THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
352
      return Local<Object>();
353
    }
354
18574
    memcpy(new_data, data, length);
355
  } else {
356
138
    new_data = nullptr;
357
  }
358
359
  Local<ArrayBuffer> ab =
360
    ArrayBuffer::New(env->isolate(),
361
        new_data,
362
        length,
363
18712
        ArrayBufferCreationMode::kInternalized);
364
  Local<Object> obj;
365
37424
  if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
366
18712
    return scope.Escape(obj);
367
  return Local<Object>();
368
}
369
370
371
15
MaybeLocal<Object> New(Isolate* isolate,
372
                       char* data,
373
                       size_t length,
374
                       FreeCallback callback,
375
                       void* hint) {
376
15
  EscapableHandleScope handle_scope(isolate);
377
15
  Environment* env = Environment::GetCurrent(isolate);
378
15
  if (env == nullptr) {
379
    callback(data, hint);
380
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
381
    return MaybeLocal<Object>();
382
  }
383
  Local<Object> obj;
384
30
  if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj))
385
15
    return handle_scope.Escape(obj);
386
  return Local<Object>();
387
}
388
389
390
15
MaybeLocal<Object> New(Environment* env,
391
                       char* data,
392
                       size_t length,
393
                       FreeCallback callback,
394
                       void* hint) {
395
15
  EscapableHandleScope scope(env->isolate());
396
397
15
  if (length > kMaxLength) {
398
    env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
399
    callback(data, hint);
400
    return Local<Object>();
401
  }
402
403
15
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
404
15
  MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
405
406
15
  CallbackInfo::New(env->isolate(), ab, callback, data, hint);
407
408
15
  if (ui.IsEmpty())
409
    return MaybeLocal<Object>();
410
411
15
  return scope.Escape(ui.ToLocalChecked());
412
}
413
414
415
8607
MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
416
8607
  EscapableHandleScope handle_scope(isolate);
417
8607
  Environment* env = Environment::GetCurrent(isolate);
418
8607
  if (env == nullptr) {
419
    free(data);
420
    THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
421
    return MaybeLocal<Object>();
422
  }
423
  Local<Object> obj;
424
17214
  if (Buffer::New(env, data, length).ToLocal(&obj))
425
8607
    return handle_scope.Escape(obj);
426
  return Local<Object>();
427
}
428
429
430
26003
MaybeLocal<Object> New(Environment* env, char* data, size_t length) {
431
26003
  if (length > 0) {
432
25782
    CHECK_NOT_NULL(data);
433
25782
    CHECK(length <= kMaxLength);
434
  }
435
436
  Local<ArrayBuffer> ab =
437
      ArrayBuffer::New(env->isolate(),
438
                       data,
439
                       length,
440
26003
                       ArrayBufferCreationMode::kInternalized);
441
52006
  return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
442
}
443
444
namespace {
445
446
4551
void CreateFromString(const FunctionCallbackInfo<Value>& args) {
447
13653
  CHECK(args[0]->IsString());
448
13653
  CHECK(args[1]->IsString());
449
450
  enum encoding enc = ParseEncoding(args.GetIsolate(),
451
                                    args[1].As<String>(),
452
9102
                                    UTF8);
453
  Local<Object> buf;
454
13653
  if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
455
9102
    args.GetReturnValue().Set(buf);
456
4551
}
457
458
459
template <encoding encoding>
460
514956
void StringSlice(const FunctionCallbackInfo<Value>& args) {
461
514956
  Environment* env = Environment::GetCurrent(args);
462
514956
  Isolate* isolate = env->isolate();
463
464



515465
  THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
465









4119648
  SPREAD_BUFFER_ARG(args.This(), ts_obj);
466
467



514956
  if (ts_obj_length == 0)
468
1002
    return args.GetReturnValue().SetEmptyString();
469
470





















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



514455
  if (ret.IsEmpty()) {
480



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

1981716
  SPREAD_BUFFER_ARG(buffer_obj, ts_obj);
497

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

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

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

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

330283
  if (target_start >= target_length || source_start >= source_end)
510
1050
    return args.GetReturnValue().Set(0);
511
512
329758
  if (source_start > ts_obj_length)
513
    return THROW_ERR_OUT_OF_RANGE(
514
1
        env, "The value of \"sourceStart\" is out of range.");
515
516
329757
  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
659514
      std::min(source_end - source_start, target_length - target_start),
521
989271
      ts_obj_length - source_start);
522
523
329757
  memmove(target_data + target_start, ts_obj_data + source_start, to_copy);
524
659514
  args.GetReturnValue().Set(to_copy);
525
}
526
527
528
805262
void Fill(const FunctionCallbackInfo<Value>& args) {
529
805262
  Environment* env = Environment::GetCurrent(args);
530
805262
  Local<Context> ctx = env->context();
531
532
1610388
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
533

6442096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
534
535
  uint32_t start;
536
2415786
  if (!args[2]->Uint32Value(ctx).To(&start)) return;
537
  uint32_t end;
538
2415786
  if (!args[3]->Uint32Value(ctx).To(&end)) return;
539
805262
  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

805262
  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
805259
  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
2415753
  if (!args[1]->IsString()) {
559
    uint32_t val;
560
2415306
    if (!args[1]->Uint32Value(ctx).To(&val)) return;
561
805102
    int value = val & 255;
562
805102
    memset(ts_obj_data + start, value, fill_length);
563
805102
    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
163043
void StringWrite(const FunctionCallbackInfo<Value>& args) {
626
163043
  Environment* env = Environment::GetCurrent(args);
627
628



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









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



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






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



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






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



163042
  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
163038
                                        nullptr);
658
326076
  args.GetReturnValue().Set(written);
659
}
660
661
179960
void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
662
179960
  Environment* env = Environment::GetCurrent(args);
663
539880
  CHECK(args[0]->IsString());
664
665
  // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
666
1079760
  args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
667
179960
}
668
669
// Normalize val to be an integer in the range of [1, -1] since
670
// implementations of memcmp() can vary by platform.
671
204785
static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
672
204785
  if (val == 0) {
673
104753
    if (a_length > b_length)
674
6
      return 1;
675
104747
    else if (a_length < b_length)
676
6
      return -1;
677
  } else {
678
100032
    if (val > 0)
679
7
      return 1;
680
    else
681
100025
      return -1;
682
  }
683
104741
  return val;
684
}
685
686
11
void CompareOffset(const FunctionCallbackInfo<Value> &args) {
687
11
  Environment* env = Environment::GetCurrent(args);
688
689
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
690
11
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
691

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

88
  SPREAD_BUFFER_ARG(args[1], target);
693
694
11
  size_t target_start = 0;
695
11
  size_t source_start = 0;
696
11
  size_t source_end = 0;
697
11
  size_t target_end = 0;
698
699

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

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

44
  THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target_length,
702
                                          &target_end));
703

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

1638192
  SPREAD_BUFFER_ARG(args[0], obj_a);
736

1638192
  SPREAD_BUFFER_ARG(args[1], obj_b);
737
738
204774
  size_t cmp_length = std::min(obj_a_length, obj_b_length);
739
740
  int val = normalizeCompareVal(cmp_length > 0 ?
741
204713
                                memcmp(obj_a_data, obj_b_data, cmp_length) : 0,
742
409487
                                obj_a_length, obj_b_length);
743
409548
  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
2382
int64_t IndexOfOffset(size_t length,
751
                      int64_t offset_i64,
752
                      int64_t needle_length,
753
                      bool is_forward) {
754
2382
  int64_t length_i64 = static_cast<int64_t>(length);
755
2382
  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
2305
    if (offset_i64 + needle_length <= length_i64) {
768
      // Valid positive offset.
769
2217
      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
887
void IndexOfString(const FunctionCallbackInfo<Value>& args) {
784
887
  Environment* env = Environment::GetCurrent(args);
785
887
  Isolate* isolate = env->isolate();
786
787
2661
  CHECK(args[1]->IsString());
788
1774
  CHECK(args[2]->IsNumber());
789
1774
  CHECK(args[4]->IsBoolean());
790
791
887
  enum encoding enc = ParseEncoding(isolate, args[3], UTF8);
792
793
920
  THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
794

7096
  SPREAD_BUFFER_ARG(args[0], ts_obj);
795
796
1774
  Local<String> needle = args[1].As<String>();
797
2661
  int64_t offset_i64 = args[2].As<Integer>()->Value();
798
1774
  bool is_forward = args[4]->IsTrue();
799
800
887
  const char* haystack = ts_obj_data;
801
  // Round down to the nearest multiple of 2 in case of UCS2.
802
  const size_t haystack_length = (enc == UCS2) ?
803
887
      ts_obj_length &~ 1 : ts_obj_length;  // NOLINT(whitespace/operators)
804
805
  size_t needle_length;
806
1774
  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
887
                                     is_forward);
812
813
887
  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
879
  if (haystack_length == 0) {
820
    return args.GetReturnValue().Set(-1);
821
  }
822
823
879
  if (opt_offset <= -1) {
824
20
    return args.GetReturnValue().Set(-1);
825
  }
826
869
  size_t offset = static_cast<size_t>(opt_offset);
827
869
  CHECK_LT(offset, haystack_length);
828

1736
  if ((is_forward && needle_length + offset > haystack_length) ||
829
867
      needle_length > haystack_length) {
830
30
    return args.GetReturnValue().Set(-1);
831
  }
832
833
854
  size_t result = haystack_length;
834
835
854
  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
769
  } else if (enc == UTF8) {
869
757
    String::Utf8Value needle_value(isolate, needle);
870
757
    if (*needle_value == nullptr)
871
      return args.GetReturnValue().Set(-1);
872
873
    result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
874
                          haystack_length,
875
757
                          reinterpret_cast<const uint8_t*>(*needle_value),
876
                          needle_length,
877
                          offset,
878
1514
                          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
2562
      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

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

1744
  SPREAD_BUFFER_ARG(args[1], buf);
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 = ts_obj_data;
917
218
  const size_t haystack_length = ts_obj_length;
918
218
  const char* needle = buf_data;
919
218
  const size_t needle_length = buf_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
1278
void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
975
2556
  CHECK(args[1]->IsUint32());
976
2556
  CHECK(args[2]->IsNumber());
977
2556
  CHECK(args[3]->IsBoolean());
978
979
1283
  THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
980

10216
  SPREAD_BUFFER_ARG(args[0], ts_obj);
981
982
3831
  uint32_t needle = args[1].As<Uint32>()->Value();
983
3831
  int64_t offset_i64 = args[2].As<Integer>()->Value();
984
2554
  bool is_forward = args[3]->IsTrue();
985
986
1277
  int64_t opt_offset = IndexOfOffset(ts_obj_length, offset_i64, 1, is_forward);
987

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

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

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

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