GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: util-inl.h Lines: 217 233 93.1 %
Date: 2021-09-24 04:12:43 Branches: 85 120 70.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
#ifndef SRC_UTIL_INL_H_
23
#define SRC_UTIL_INL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include <cmath>
28
#include <cstring>
29
#include <locale>
30
#include "util.h"
31
32
// These are defined by <sys/byteorder.h> or <netinet/in.h> on some systems.
33
// To avoid warnings, undefine them before redefining them.
34
#ifdef BSWAP_2
35
# undef BSWAP_2
36
#endif
37
#ifdef BSWAP_4
38
# undef BSWAP_4
39
#endif
40
#ifdef BSWAP_8
41
# undef BSWAP_8
42
#endif
43
44
#if defined(_MSC_VER)
45
#include <intrin.h>
46
#define BSWAP_2(x) _byteswap_ushort(x)
47
#define BSWAP_4(x) _byteswap_ulong(x)
48
#define BSWAP_8(x) _byteswap_uint64(x)
49
#else
50
#define BSWAP_2(x) ((x) << 8) | ((x) >> 8)
51
#define BSWAP_4(x)                                                            \
52
  (((x) & 0xFF) << 24) |                                                      \
53
  (((x) & 0xFF00) << 8) |                                                     \
54
  (((x) >> 8) & 0xFF00) |                                                     \
55
  (((x) >> 24) & 0xFF)
56
#define BSWAP_8(x)                                                            \
57
  (((x) & 0xFF00000000000000ull) >> 56) |                                     \
58
  (((x) & 0x00FF000000000000ull) >> 40) |                                     \
59
  (((x) & 0x0000FF0000000000ull) >> 24) |                                     \
60
  (((x) & 0x000000FF00000000ull) >> 8) |                                      \
61
  (((x) & 0x00000000FF000000ull) << 8) |                                      \
62
  (((x) & 0x0000000000FF0000ull) << 24) |                                     \
63
  (((x) & 0x000000000000FF00ull) << 40) |                                     \
64
  (((x) & 0x00000000000000FFull) << 56)
65
#endif
66
67
namespace node {
68
69
template <typename T>
70
201055
ListNode<T>::ListNode() : prev_(this), next_(this) {}
71
72
template <typename T>
73
198324
ListNode<T>::~ListNode() {
74
198324
  Remove();
75
198324
}
76
77
template <typename T>
78
310082
void ListNode<T>::Remove() {
79
310082
  prev_->next_ = next_;
80
310082
  next_->prev_ = prev_;
81
310082
  prev_ = this;
82
310082
  next_ = this;
83
310082
}
84
85
template <typename T>
86
42329
bool ListNode<T>::IsEmpty() const {
87
42329
  return prev_ == this;
88
}
89
90
template <typename T, ListNode<T> (T::*M)>
91
79456
ListHead<T, M>::Iterator::Iterator(ListNode<T>* node) : node_(node) {}
92
93
template <typename T, ListNode<T> (T::*M)>
94
5661
T* ListHead<T, M>::Iterator::operator*() const {
95
5661
  return ContainerOf(M, node_);
96
}
97
98
template <typename T, ListNode<T> (T::*M)>
99
const typename ListHead<T, M>::Iterator&
100
5661
ListHead<T, M>::Iterator::operator++() {
101
5661
  node_ = node_->next_;
102
5661
  return *this;
103
}
104
105
template <typename T, ListNode<T> (T::*M)>
106
45387
bool ListHead<T, M>::Iterator::operator!=(const Iterator& that) const {
107
45387
  return node_ != that.node_;
108
}
109
110
template <typename T, ListNode<T> (T::*M)>
111
19909
ListHead<T, M>::~ListHead() {
112
19909
  while (IsEmpty() == false)
113
    head_.next_->Remove();
114
19909
}
115
116
template <typename T, ListNode<T> (T::*M)>
117
131804
void ListHead<T, M>::PushBack(T* element) {
118
131804
  ListNode<T>* that = &(element->*M);
119
131804
  head_.prev_->next_ = that;
120
131804
  that->prev_ = head_.prev_;
121
131804
  that->next_ = &head_;
122
131804
  head_.prev_ = that;
123
131804
}
124
125
template <typename T, ListNode<T> (T::*M)>
126
void ListHead<T, M>::PushFront(T* element) {
127
  ListNode<T>* that = &(element->*M);
128
  head_.next_->prev_ = that;
129
  that->prev_ = &head_;
130
  that->next_ = head_.next_;
131
  head_.next_ = that;
132
}
133
134
template <typename T, ListNode<T> (T::*M)>
135
42325
bool ListHead<T, M>::IsEmpty() const {
136
42325
  return head_.IsEmpty();
137
}
138
139
template <typename T, ListNode<T> (T::*M)>
140
2
T* ListHead<T, M>::PopFront() {
141
2
  if (IsEmpty())
142
    return nullptr;
143
2
  ListNode<T>* node = head_.next_;
144
2
  node->Remove();
145
2
  return ContainerOf(M, node);
146
}
147
148
template <typename T, ListNode<T> (T::*M)>
149
39726
typename ListHead<T, M>::Iterator ListHead<T, M>::begin() const {
150
39726
  return Iterator(head_.next_);
151
}
152
153
template <typename T, ListNode<T> (T::*M)>
154
39730
typename ListHead<T, M>::Iterator ListHead<T, M>::end() const {
155
39730
  return Iterator(const_cast<ListNode<T>*>(&head_));
156
}
157
158
template <typename Inner, typename Outer>
159
2684562
constexpr uintptr_t OffsetOf(Inner Outer::*field) {
160
2684562
  return reinterpret_cast<uintptr_t>(&(static_cast<Outer*>(nullptr)->*field));
161
}
162
163
template <typename Inner, typename Outer>
164
2625618
ContainerOfHelper<Inner, Outer>::ContainerOfHelper(Inner Outer::*field,
165
                                                   Inner* pointer)
166
    : pointer_(
167
        reinterpret_cast<Outer*>(
168
2625618
            reinterpret_cast<uintptr_t>(pointer) - OffsetOf(field))) {}
169
170
template <typename Inner, typename Outer>
171
template <typename TypeName>
172
2625618
ContainerOfHelper<Inner, Outer>::operator TypeName*() const {
173
2625618
  return static_cast<TypeName*>(pointer_);
174
}
175
176
template <typename Inner, typename Outer>
177
2619371
constexpr ContainerOfHelper<Inner, Outer> ContainerOf(Inner Outer::*field,
178
                                                      Inner* pointer) {
179
2619371
  return ContainerOfHelper<Inner, Outer>(field, pointer);
180
}
181
182
3765872
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
183
                                           const char* data,
184
                                           int length) {
185
3765872
  return v8::String::NewFromOneByte(isolate,
186
                                    reinterpret_cast<const uint8_t*>(data),
187
                                    v8::NewStringType::kNormal,
188
3765872
                                    length).ToLocalChecked();
189
}
190
191
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
192
                                           const signed char* data,
193
                                           int length) {
194
  return v8::String::NewFromOneByte(isolate,
195
                                    reinterpret_cast<const uint8_t*>(data),
196
                                    v8::NewStringType::kNormal,
197
                                    length).ToLocalChecked();
198
}
199
200
109
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
201
                                           const unsigned char* data,
202
                                           int length) {
203
109
  return v8::String::NewFromOneByte(
204
109
             isolate, data, v8::NewStringType::kNormal, length)
205
109
      .ToLocalChecked();
206
}
207
208
2
void SwapBytes16(char* data, size_t nbytes) {
209
2
  CHECK_EQ(nbytes % 2, 0);
210
211
#if defined(_MSC_VER)
212
  if (AlignUp(data, sizeof(uint16_t)) == data) {
213
    // MSVC has no strict aliasing, and is able to highly optimize this case.
214
    uint16_t* data16 = reinterpret_cast<uint16_t*>(data);
215
    size_t len16 = nbytes / sizeof(*data16);
216
    for (size_t i = 0; i < len16; i++) {
217
      data16[i] = BSWAP_2(data16[i]);
218
    }
219
    return;
220
  }
221
#endif
222
223
  uint16_t temp;
224
1537
  for (size_t i = 0; i < nbytes; i += sizeof(temp)) {
225
1535
    memcpy(&temp, &data[i], sizeof(temp));
226
1535
    temp = BSWAP_2(temp);
227
1535
    memcpy(&data[i], &temp, sizeof(temp));
228
  }
229
2
}
230
231
2
void SwapBytes32(char* data, size_t nbytes) {
232
2
  CHECK_EQ(nbytes % 4, 0);
233
234
#if defined(_MSC_VER)
235
  // MSVC has no strict aliasing, and is able to highly optimize this case.
236
  if (AlignUp(data, sizeof(uint32_t)) == data) {
237
    uint32_t* data32 = reinterpret_cast<uint32_t*>(data);
238
    size_t len32 = nbytes / sizeof(*data32);
239
    for (size_t i = 0; i < len32; i++) {
240
      data32[i] = BSWAP_4(data32[i]);
241
    }
242
    return;
243
  }
244
#endif
245
246
  uint32_t temp;
247
769
  for (size_t i = 0; i < nbytes; i += sizeof(temp)) {
248
767
    memcpy(&temp, &data[i], sizeof(temp));
249
767
    temp = BSWAP_4(temp);
250
767
    memcpy(&data[i], &temp, sizeof(temp));
251
  }
252
2
}
253
254
2
void SwapBytes64(char* data, size_t nbytes) {
255
2
  CHECK_EQ(nbytes % 8, 0);
256
257
#if defined(_MSC_VER)
258
  if (AlignUp(data, sizeof(uint64_t)) == data) {
259
    // MSVC has no strict aliasing, and is able to highly optimize this case.
260
    uint64_t* data64 = reinterpret_cast<uint64_t*>(data);
261
    size_t len64 = nbytes / sizeof(*data64);
262
    for (size_t i = 0; i < len64; i++) {
263
      data64[i] = BSWAP_8(data64[i]);
264
    }
265
    return;
266
  }
267
#endif
268
269
  uint64_t temp;
270
513
  for (size_t i = 0; i < nbytes; i += sizeof(temp)) {
271
511
    memcpy(&temp, &data[i], sizeof(temp));
272
511
    temp = BSWAP_8(temp);
273
511
    memcpy(&data[i], &temp, sizeof(temp));
274
  }
275
2
}
276
277
54431
char ToLower(char c) {
278
54431
  return std::tolower(c, std::locale::classic());
279
}
280
281
3942
std::string ToLower(const std::string& in) {
282
3942
  std::string out(in.size(), 0);
283
51302
  for (size_t i = 0; i < in.size(); ++i)
284
47360
    out[i] = ToLower(in[i]);
285
3942
  return out;
286
}
287
288
13081
char ToUpper(char c) {
289
13081
  return std::toupper(c, std::locale::classic());
290
}
291
292
2
std::string ToUpper(const std::string& in) {
293
2
  std::string out(in.size(), 0);
294
5
  for (size_t i = 0; i < in.size(); ++i)
295
3
    out[i] = ToUpper(in[i]);
296
2
  return out;
297
}
298
299
1210
bool StringEqualNoCase(const char* a, const char* b) {
300
1210
  while (ToLower(*a) == ToLower(*b++)) {
301
1119
    if (*a++ == '\0')
302
95
      return true;
303
  }
304
91
  return false;
305
}
306
307
609
bool StringEqualNoCaseN(const char* a, const char* b, size_t length) {
308
2505
  for (size_t i = 0; i < length; i++) {
309
2324
    if (ToLower(a[i]) != ToLower(b[i]))
310
427
      return false;
311
1897
    if (a[i] == '\0')
312
1
      return true;
313
  }
314
181
  return true;
315
}
316
317
template <typename T>
318
815525
inline T MultiplyWithOverflowCheck(T a, T b) {
319
815525
  auto ret = a * b;
320
815525
  if (a != 0)
321
815522
    CHECK_EQ(b, ret / a);
322
323
815525
  return ret;
324
}
325
326
// These should be used in our code as opposed to the native
327
// versions as they abstract out some platform and or
328
// compiler version specific functionality.
329
// malloc(0) and realloc(ptr, 0) have implementation-defined behavior in
330
// that the standard allows them to either return a unique pointer or a
331
// nullptr for zero-sized allocation requests.  Normalize by always using
332
// a nullptr.
333
template <typename T>
334
699646
T* UncheckedRealloc(T* pointer, size_t n) {
335
699646
  size_t full_size = MultiplyWithOverflowCheck(sizeof(T), n);
336
337
699646
  if (full_size == 0) {
338
102917
    free(pointer);
339
102917
    return nullptr;
340
  }
341
342
596729
  void* allocated = realloc(pointer, full_size);
343
344
596729
  if (UNLIKELY(allocated == nullptr)) {
345
    // Tell V8 that memory is low and retry.
346
    LowMemoryNotification();
347
    allocated = realloc(pointer, full_size);
348
  }
349
350
596729
  return static_cast<T*>(allocated);
351
}
352
353
// As per spec realloc behaves like malloc if passed nullptr.
354
template <typename T>
355
298411
inline T* UncheckedMalloc(size_t n) {
356
298411
  if (n == 0) n = 1;
357
298411
  return UncheckedRealloc<T>(nullptr, n);
358
}
359
360
template <typename T>
361
56023
inline T* UncheckedCalloc(size_t n) {
362
56023
  if (n == 0) n = 1;
363
56023
  MultiplyWithOverflowCheck(sizeof(T), n);
364
56023
  return static_cast<T*>(calloc(n, sizeof(T)));
365
}
366
367
template <typename T>
368
135350
inline T* Realloc(T* pointer, size_t n) {
369
135350
  T* ret = UncheckedRealloc(pointer, n);
370

135350
  CHECK_IMPLIES(n > 0, ret != nullptr);
371
135350
  return ret;
372
}
373
374
template <typename T>
375
104
inline T* Malloc(size_t n) {
376
104
  T* ret = UncheckedMalloc<T>(n);
377

104
  CHECK_IMPLIES(n > 0, ret != nullptr);
378
104
  return ret;
379
}
380
381
template <typename T>
382
54
inline T* Calloc(size_t n) {
383
54
  T* ret = UncheckedCalloc<T>(n);
384

54
  CHECK_IMPLIES(n > 0, ret != nullptr);
385
54
  return ret;
386
}
387
388
// Shortcuts for char*.
389
4
inline char* Malloc(size_t n) { return Malloc<char>(n); }
390
2
inline char* Calloc(size_t n) { return Calloc<char>(n); }
391
298289
inline char* UncheckedMalloc(size_t n) { return UncheckedMalloc<char>(n); }
392
55967
inline char* UncheckedCalloc(size_t n) { return UncheckedCalloc<char>(n); }
393
394
// This is a helper in the .cc file so including util-inl.h doesn't include more
395
// headers than we really need to.
396
void ThrowErrStringTooLong(v8::Isolate* isolate);
397
398
2846929
v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
399
                                    const std::string& str,
400
                                    v8::Isolate* isolate) {
401
4406117
  if (isolate == nullptr) isolate = context->GetIsolate();
402
2846929
  if (UNLIKELY(str.size() >= static_cast<size_t>(v8::String::kMaxLength))) {
403
    // V8 only has a TODO comment about adding an exception when the maximum
404
    // string size is exceeded.
405
    ThrowErrStringTooLong(isolate);
406
    return v8::MaybeLocal<v8::Value>();
407
  }
408
409
2846929
  return v8::String::NewFromUtf8(
410
2846929
             isolate, str.data(), v8::NewStringType::kNormal, str.size())
411
2846929
      .FromMaybe(v8::Local<v8::String>());
412
}
413
414
template <typename T>
415
277656
v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
416
                                    const std::vector<T>& vec,
417
                                    v8::Isolate* isolate) {
418
435544
  if (isolate == nullptr) isolate = context->GetIsolate();
419
277656
  v8::EscapableHandleScope handle_scope(isolate);
420
421
555312
  MaybeStackBuffer<v8::Local<v8::Value>, 128> arr(vec.size());
422
277656
  arr.SetLength(vec.size());
423
1445631
  for (size_t i = 0; i < vec.size(); ++i) {
424
2335950
    if (!ToV8Value(context, vec[i], isolate).ToLocal(&arr[i]))
425
      return v8::MaybeLocal<v8::Value>();
426
  }
427
428
555312
  return handle_scope.Escape(v8::Array::New(isolate, arr.out(), arr.length()));
429
}
430
431
template <typename T, typename U>
432
5444
v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
433
                                    const std::unordered_map<T, U>& map,
434
                                    v8::Isolate* isolate) {
435
10888
  if (isolate == nullptr) isolate = context->GetIsolate();
436
5444
  v8::EscapableHandleScope handle_scope(isolate);
437
438
5444
  v8::Local<v8::Map> ret = v8::Map::New(isolate);
439
125212
  for (const auto& item : map) {
440
    v8::Local<v8::Value> first, second;
441
119768
    if (!ToV8Value(context, item.first, isolate).ToLocal(&first) ||
442

359304
        !ToV8Value(context, item.second, isolate).ToLocal(&second) ||
443

359304
        ret->Set(context, first, second).IsEmpty()) {
444
      return v8::MaybeLocal<v8::Value>();
445
    }
446
  }
447
448
5444
  return handle_scope.Escape(ret);
449
}
450
451
template <typename T, typename >
452
2
v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
453
                                    const T& number,
454
                                    v8::Isolate* isolate) {
455
2
  if (isolate == nullptr) isolate = context->GetIsolate();
456
457
  using Limits = std::numeric_limits<T>;
458
  // Choose Uint32, Int32, or Double depending on range checks.
459
  // These checks should all collapse at compile time.
460
2
  if (static_cast<uint32_t>(Limits::max()) <=
461
4
          std::numeric_limits<uint32_t>::max() &&
462
2
      static_cast<uint32_t>(Limits::min()) >=
463

6
          std::numeric_limits<uint32_t>::min() && Limits::is_exact) {
464
4
    return v8::Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(number));
465
  }
466
467
  if (static_cast<int32_t>(Limits::max()) <=
468
          std::numeric_limits<int32_t>::max() &&
469
      static_cast<int32_t>(Limits::min()) >=
470
          std::numeric_limits<int32_t>::min() && Limits::is_exact) {
471
    return v8::Integer::New(isolate, static_cast<int32_t>(number));
472
  }
473
474
  return v8::Number::New(isolate, static_cast<double>(number));
475
}
476
477
44464
SlicedArguments::SlicedArguments(
478
44464
    const v8::FunctionCallbackInfo<v8::Value>& args, size_t start) {
479
44464
  const size_t length = static_cast<size_t>(args.Length());
480
44464
  if (start >= length) return;
481
44446
  const size_t size = length - start;
482
483
44446
  AllocateSufficientStorage(size);
484
101452
  for (size_t i = 0; i < size; ++i)
485
114012
    (*this)[i] = args[i + start];
486
}
487
488
template <typename T, size_t S>
489
15122
ArrayBufferViewContents<T, S>::ArrayBufferViewContents(
490
15122
    v8::Local<v8::Value> value) {
491
15122
  CHECK(value->IsArrayBufferView());
492
15122
  Read(value.As<v8::ArrayBufferView>());
493
15122
}
494
495
template <typename T, size_t S>
496
122218
ArrayBufferViewContents<T, S>::ArrayBufferViewContents(
497
122218
    v8::Local<v8::Object> value) {
498
122218
  CHECK(value->IsArrayBufferView());
499
122218
  Read(value.As<v8::ArrayBufferView>());
500
122218
}
501
502
template <typename T, size_t S>
503
26682
ArrayBufferViewContents<T, S>::ArrayBufferViewContents(
504
26682
    v8::Local<v8::ArrayBufferView> abv) {
505
26682
  Read(abv);
506
26682
}
507
508
template <typename T, size_t S>
509
164223
void ArrayBufferViewContents<T, S>::Read(v8::Local<v8::ArrayBufferView> abv) {
510
  static_assert(sizeof(T) == 1, "Only supports one-byte data at the moment");
511
164223
  length_ = abv->ByteLength();
512

250080
  if (length_ > sizeof(stack_storage_) || abv->HasBuffer()) {
513
490089
    data_ = static_cast<T*>(abv->Buffer()->GetBackingStore()->Data()) +
514
163363
        abv->ByteOffset();
515
  } else {
516
860
    abv->CopyContents(stack_storage_, sizeof(stack_storage_));
517
860
    data_ = stack_storage_;
518
  }
519
164223
}
520
521
// ECMA262 20.1.2.5
522
367766
inline bool IsSafeJsInt(v8::Local<v8::Value> v) {
523
367766
  if (!v->IsNumber()) return false;
524
187659
  double v_d = v.As<v8::Number>()->Value();
525
187659
  if (std::isnan(v_d)) return false;
526
187659
  if (std::isinf(v_d)) return false;
527
187659
  if (std::trunc(v_d) != v_d) return false;  // not int
528
187659
  if (std::abs(v_d) <= static_cast<double>(kMaxSafeJsInteger)) return true;
529
  return false;
530
}
531
532
constexpr size_t FastStringKey::HashImpl(const char* str) {
533
  // Low-quality hash (djb2), but just fine for current use cases.
534
  size_t h = 5381;
535
  while (*str != '\0') {
536
    h = h * 33 + *(str++);  // NOLINT(readability/pointer_notation)
537
  }
538
  return h;
539
}
540
541
756640
constexpr size_t FastStringKey::Hash::operator()(
542
    const FastStringKey& key) const {
543
756640
  return key.cached_hash_;
544
}
545
546
739239
constexpr bool FastStringKey::operator==(const FastStringKey& other) const {
547
739239
  const char* p1 = name_;
548
739239
  const char* p2 = other.name_;
549
739239
  if (p1 == p2) return true;
550
108
  do {
551
126
    if (*(p1++) != *(p2++)) return false;
552
108
  } while (*p1 != '\0');
553
  return *p2 == '\0';
554
}
555
556
constexpr FastStringKey::FastStringKey(const char* name)
557
  : name_(name), cached_hash_(HashImpl(name)) {}
558
559
14592
constexpr const char* FastStringKey::c_str() const {
560
14592
  return name_;
561
}
562
563
}  // namespace node
564
565
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
566
567
#endif  // SRC_UTIL_INL_H_