GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: util.h Lines: 134 134 100.0 %
Date: 2022-08-02 04:16:51 Branches: 34 46 73.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
#ifndef SRC_UTIL_H_
23
#define SRC_UTIL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "v8.h"
28
29
#include "node.h"
30
31
#include <climits>
32
#include <cstddef>
33
#include <cstdio>
34
#include <cstdlib>
35
#include <cstring>
36
37
#include <array>
38
#include <limits>
39
#include <memory>
40
#include <string>
41
#include <string_view>
42
#include <type_traits>
43
#include <set>
44
#include <unordered_map>
45
#include <utility>
46
#include <vector>
47
48
#ifdef __GNUC__
49
#define MUST_USE_RESULT __attribute__((warn_unused_result))
50
#else
51
#define MUST_USE_RESULT
52
#endif
53
54
namespace node {
55
56
// Maybe remove kPathSeparator when cpp17 is ready
57
#ifdef _WIN32
58
    constexpr char kPathSeparator = '\\';
59
/* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
60
#define PATH_MAX_BYTES (MAX_PATH * 4)
61
#else
62
    constexpr char kPathSeparator = '/';
63
#define PATH_MAX_BYTES (PATH_MAX)
64
#endif
65
66
// These should be used in our code as opposed to the native
67
// versions as they abstract out some platform and or
68
// compiler version specific functionality
69
// malloc(0) and realloc(ptr, 0) have implementation-defined behavior in
70
// that the standard allows them to either return a unique pointer or a
71
// nullptr for zero-sized allocation requests.  Normalize by always using
72
// a nullptr.
73
template <typename T>
74
inline T* UncheckedRealloc(T* pointer, size_t n);
75
template <typename T>
76
inline T* UncheckedMalloc(size_t n);
77
template <typename T>
78
inline T* UncheckedCalloc(size_t n);
79
80
// Same things, but aborts immediately instead of returning nullptr when
81
// no memory is available.
82
template <typename T>
83
inline T* Realloc(T* pointer, size_t n);
84
template <typename T>
85
inline T* Malloc(size_t n);
86
template <typename T>
87
inline T* Calloc(size_t n);
88
89
inline char* Malloc(size_t n);
90
inline char* Calloc(size_t n);
91
inline char* UncheckedMalloc(size_t n);
92
inline char* UncheckedCalloc(size_t n);
93
94
template <typename T>
95
inline T MultiplyWithOverflowCheck(T a, T b);
96
97
namespace per_process {
98
// Tells whether the per-process V8::Initialize() is called and
99
// if it is safe to call v8::Isolate::TryGetCurrent().
100
extern bool v8_initialized;
101
}  // namespace per_process
102
103
// Used by the allocation functions when allocation fails.
104
// Thin wrapper around v8::Isolate::LowMemoryNotification() that checks
105
// whether V8 is initialized.
106
void LowMemoryNotification();
107
108
// The reason that Assert() takes a struct argument instead of individual
109
// const char*s is to ease instruction cache pressure in calls from CHECK.
110
struct AssertionInfo {
111
  const char* file_line;  // filename:line
112
  const char* message;
113
  const char* function;
114
};
115
[[noreturn]] void NODE_EXTERN_PRIVATE Assert(const AssertionInfo& info);
116
[[noreturn]] void NODE_EXTERN_PRIVATE Abort();
117
void DumpBacktrace(FILE* fp);
118
119
// Windows 8+ does not like abort() in Release mode
120
#ifdef _WIN32
121
#define ABORT_NO_BACKTRACE() _exit(134)
122
#else
123
#define ABORT_NO_BACKTRACE() abort()
124
#endif
125
126
#define ABORT() node::Abort()
127
128
#define ERROR_AND_ABORT(expr)                                                 \
129
  do {                                                                        \
130
    /* Make sure that this struct does not end up in inline code, but      */ \
131
    /* rather in a read-only data section when modifying this code.        */ \
132
    static const node::AssertionInfo args = {                                 \
133
      __FILE__ ":" STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME           \
134
    };                                                                        \
135
    node::Assert(args);                                                       \
136
  } while (0)
137
138
#ifdef __GNUC__
139
#define LIKELY(expr) __builtin_expect(!!(expr), 1)
140
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
141
#define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__
142
#else
143
#define LIKELY(expr) expr
144
#define UNLIKELY(expr) expr
145
#define PRETTY_FUNCTION_NAME ""
146
#endif
147
148
#define STRINGIFY_(x) #x
149
#define STRINGIFY(x) STRINGIFY_(x)
150
151
#define CHECK(expr)                                                           \
152
  do {                                                                        \
153
    if (UNLIKELY(!(expr))) {                                                  \
154
      ERROR_AND_ABORT(expr);                                                  \
155
    }                                                                         \
156
  } while (0)
157
158
#define CHECK_EQ(a, b) CHECK((a) == (b))
159
#define CHECK_GE(a, b) CHECK((a) >= (b))
160
#define CHECK_GT(a, b) CHECK((a) > (b))
161
#define CHECK_LE(a, b) CHECK((a) <= (b))
162
#define CHECK_LT(a, b) CHECK((a) < (b))
163
#define CHECK_NE(a, b) CHECK((a) != (b))
164
#define CHECK_NULL(val) CHECK((val) == nullptr)
165
#define CHECK_NOT_NULL(val) CHECK((val) != nullptr)
166
#define CHECK_IMPLIES(a, b) CHECK(!(a) || (b))
167
168
#ifdef DEBUG
169
  #define DCHECK(expr) CHECK(expr)
170
  #define DCHECK_EQ(a, b) CHECK((a) == (b))
171
  #define DCHECK_GE(a, b) CHECK((a) >= (b))
172
  #define DCHECK_GT(a, b) CHECK((a) > (b))
173
  #define DCHECK_LE(a, b) CHECK((a) <= (b))
174
  #define DCHECK_LT(a, b) CHECK((a) < (b))
175
  #define DCHECK_NE(a, b) CHECK((a) != (b))
176
  #define DCHECK_NULL(val) CHECK((val) == nullptr)
177
  #define DCHECK_NOT_NULL(val) CHECK((val) != nullptr)
178
  #define DCHECK_IMPLIES(a, b) CHECK(!(a) || (b))
179
#else
180
  #define DCHECK(expr)
181
  #define DCHECK_EQ(a, b)
182
  #define DCHECK_GE(a, b)
183
  #define DCHECK_GT(a, b)
184
  #define DCHECK_LE(a, b)
185
  #define DCHECK_LT(a, b)
186
  #define DCHECK_NE(a, b)
187
  #define DCHECK_NULL(val)
188
  #define DCHECK_NOT_NULL(val)
189
  #define DCHECK_IMPLIES(a, b)
190
#endif
191
192
193
#define UNREACHABLE(...)                                                      \
194
  ERROR_AND_ABORT("Unreachable code reached" __VA_OPT__(": ") __VA_ARGS__)
195
196
// ECMA262 20.1.2.6 Number.MAX_SAFE_INTEGER (2^53-1)
197
constexpr int64_t kMaxSafeJsInteger = 9007199254740991;
198
199
inline bool IsSafeJsInt(v8::Local<v8::Value> v);
200
201
// TAILQ-style intrusive list node.
202
template <typename T>
203
class ListNode;
204
205
// TAILQ-style intrusive list head.
206
template <typename T, ListNode<T> (T::*M)>
207
class ListHead;
208
209
template <typename T>
210
class ListNode {
211
 public:
212
  inline ListNode();
213
  inline ~ListNode();
214
  inline void Remove();
215
  inline bool IsEmpty() const;
216
217
  ListNode(const ListNode&) = delete;
218
  ListNode& operator=(const ListNode&) = delete;
219
220
 private:
221
  template <typename U, ListNode<U> (U::*M)> friend class ListHead;
222
  friend int GenDebugSymbols();
223
  ListNode* prev_;
224
  ListNode* next_;
225
};
226
227
template <typename T, ListNode<T> (T::*M)>
228
class ListHead {
229
 public:
230
  class Iterator {
231
   public:
232
    inline T* operator*() const;
233
    inline const Iterator& operator++();
234
    inline bool operator!=(const Iterator& that) const;
235
236
   private:
237
    friend class ListHead;
238
    inline explicit Iterator(ListNode<T>* node);
239
    ListNode<T>* node_;
240
  };
241
242
26385
  inline ListHead() = default;
243
  inline ~ListHead();
244
  inline void PushBack(T* element);
245
  inline void PushFront(T* element);
246
  inline bool IsEmpty() const;
247
  inline T* PopFront();
248
  inline Iterator begin() const;
249
  inline Iterator end() const;
250
251
  ListHead(const ListHead&) = delete;
252
  ListHead& operator=(const ListHead&) = delete;
253
254
 private:
255
  friend int GenDebugSymbols();
256
  ListNode<T> head_;
257
};
258
259
// The helper is for doing safe downcasts from base types to derived types.
260
template <typename Inner, typename Outer>
261
class ContainerOfHelper {
262
 public:
263
  inline ContainerOfHelper(Inner Outer::*field, Inner* pointer);
264
  template <typename TypeName>
265
  inline operator TypeName*() const;
266
 private:
267
  Outer* const pointer_;
268
};
269
270
// Calculate the address of the outer (i.e. embedding) struct from
271
// the interior pointer to a data member.
272
template <typename Inner, typename Outer>
273
constexpr ContainerOfHelper<Inner, Outer> ContainerOf(Inner Outer::*field,
274
                                                      Inner* pointer);
275
276
class KVStore {
277
 public:
278
6855
  KVStore() = default;
279
12660
  virtual ~KVStore() = default;
280
  KVStore(const KVStore&) = delete;
281
  KVStore& operator=(const KVStore&) = delete;
282
  KVStore(KVStore&&) = delete;
283
  KVStore& operator=(KVStore&&) = delete;
284
285
  virtual v8::MaybeLocal<v8::String> Get(v8::Isolate* isolate,
286
                                         v8::Local<v8::String> key) const = 0;
287
  virtual v8::Maybe<std::string> Get(const char* key) const = 0;
288
  virtual void Set(v8::Isolate* isolate,
289
                   v8::Local<v8::String> key,
290
                   v8::Local<v8::String> value) = 0;
291
  virtual int32_t Query(v8::Isolate* isolate,
292
                        v8::Local<v8::String> key) const = 0;
293
  virtual int32_t Query(const char* key) const = 0;
294
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
295
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
296
297
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
298
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
299
                                           v8::Local<v8::Object> entries);
300
301
  static std::shared_ptr<KVStore> CreateMapKVStore();
302
};
303
304
// Convenience wrapper around v8::String::NewFromOneByte().
305
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
306
                                           const char* data,
307
                                           int length = -1);
308
309
// For the people that compile with -funsigned-char.
310
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
311
                                           const signed char* data,
312
                                           int length = -1);
313
314
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
315
                                           const unsigned char* data,
316
                                           int length = -1);
317
318
// Used to be a macro, hence the uppercase name.
319
template <int N>
320
7234065
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
321
    v8::Isolate* isolate,
322
    const char(&data)[N]) {
323
7234065
  return OneByteString(isolate, data, N - 1);
324
}
325
326
template <std::size_t N>
327
624
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
328
    v8::Isolate* isolate,
329
    const std::array<char, N>& arr) {
330
624
  return OneByteString(isolate, arr.data(), N - 1);
331
}
332
333
334
335
// Swaps bytes in place. nbytes is the number of bytes to swap and must be a
336
// multiple of the word size (checked by function).
337
inline void SwapBytes16(char* data, size_t nbytes);
338
inline void SwapBytes32(char* data, size_t nbytes);
339
inline void SwapBytes64(char* data, size_t nbytes);
340
341
// tolower() is locale-sensitive.  Use ToLower() instead.
342
inline char ToLower(char c);
343
inline std::string ToLower(const std::string& in);
344
345
// toupper() is locale-sensitive.  Use ToUpper() instead.
346
inline char ToUpper(char c);
347
inline std::string ToUpper(const std::string& in);
348
349
// strcasecmp() is locale-sensitive.  Use StringEqualNoCase() instead.
350
inline bool StringEqualNoCase(const char* a, const char* b);
351
352
// strncasecmp() is locale-sensitive.  Use StringEqualNoCaseN() instead.
353
inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length);
354
355
template <typename T, size_t N>
356
11811128
constexpr size_t arraysize(const T (&)[N]) {
357
11811128
  return N;
358
}
359
360
template <typename T, size_t N>
361
constexpr size_t strsize(const T (&)[N]) {
362
  return N - 1;
363
}
364
365
// Allocates an array of member type T. For up to kStackStorageSize items,
366
// the stack is used, otherwise malloc().
367
template <typename T, size_t kStackStorageSize = 1024>
368
class MaybeStackBuffer {
369
 public:
370
5827
  const T* out() const {
371
5827
    return buf_;
372
  }
373
374
6490843
  T* out() {
375
6490843
    return buf_;
376
  }
377
378
  // operator* for compatibility with `v8::String::(Utf8)Value`
379
9777685
  T* operator*() {
380
9777685
    return buf_;
381
  }
382
383
32508
  const T* operator*() const {
384
32508
    return buf_;
385
  }
386
387
4794952
  T& operator[](size_t index) {
388
4794952
    CHECK_LT(index, length());
389
4794952
    return buf_[index];
390
  }
391
392
11704
  const T& operator[](size_t index) const {
393
11704
    CHECK_LT(index, length());
394
11704
    return buf_[index];
395
  }
396
397
13419417
  size_t length() const {
398
13419417
    return length_;
399
  }
400
401
  // Current maximum capacity of the buffer with which SetLength() can be used
402
  // without first calling AllocateSufficientStorage().
403
20275074
  size_t capacity() const {
404
20275074
    return capacity_;
405
  }
406
407
  // Make sure enough space for `storage` entries is available.
408
  // This method can be called multiple times throughout the lifetime of the
409
  // buffer, but once this has been called Invalidate() cannot be used.
410
  // Content of the buffer in the range [0, length()) is preserved.
411
7225215
  void AllocateSufficientStorage(size_t storage) {
412
7225215
    CHECK(!IsInvalidated());
413
7225215
    if (storage > capacity()) {
414
285111
      bool was_allocated = IsAllocated();
415
285111
      T* allocated_ptr = was_allocated ? buf_ : nullptr;
416
285111
      buf_ = Realloc(allocated_ptr, storage);
417
285111
      capacity_ = storage;
418

285111
      if (!was_allocated && length_ > 0)
419
4
        memcpy(buf_, buf_st_, length_ * sizeof(buf_[0]));
420
    }
421
422
7225215
    length_ = storage;
423
7225215
  }
424
425
6387799
  void SetLength(size_t length) {
426
    // capacity() returns how much memory is actually available.
427
6387799
    CHECK_LE(length, capacity());
428
6387799
    length_ = length;
429
6387799
  }
430
431
9477692
  void SetLengthAndZeroTerminate(size_t length) {
432
    // capacity() returns how much memory is actually available.
433
9477692
    CHECK_LE(length + 1, capacity());
434
9477692
    SetLength(length);
435
436
    // T() is 0 for integer types, nullptr for pointers, etc.
437
9477692
    buf_[length] = T();
438
9477692
  }
439
440
  // Make dereferencing this object return nullptr.
441
  // This method can be called multiple times throughout the lifetime of the
442
  // buffer, but once this has been called AllocateSufficientStorage() cannot
443
  // be used.
444
2
  void Invalidate() {
445
2
    CHECK(!IsAllocated());
446
2
    capacity_ = 0;
447
2
    length_ = 0;
448
2
    buf_ = nullptr;
449
2
  }
450
451
  // If the buffer is stored in the heap rather than on the stack.
452
9264564
  bool IsAllocated() const {
453

9264564
    return !IsInvalidated() && buf_ != buf_st_;
454
  }
455
456
  // If Invalidate() has been called.
457
16549272
  bool IsInvalidated() const {
458
16549272
    return buf_ == nullptr;
459
  }
460
461
  // Release ownership of the malloc'd buffer.
462
  // Note: This does not free the buffer.
463
684
  void Release() {
464
684
    CHECK(IsAllocated());
465
684
    buf_ = buf_st_;
466
684
    length_ = 0;
467
684
    capacity_ = arraysize(buf_st_);
468
684
  }
469
470
8868578
  MaybeStackBuffer()
471
158192706
      : length_(0), capacity_(arraysize(buf_st_)), buf_(buf_st_) {
472
    // Default to a zero-length, null-terminated buffer.
473
8868578
    buf_[0] = T();
474
8868578
  }
475
476
868347
  explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() {
477
868347
    AllocateSufficientStorage(storage);
478
868347
  }
479
480
8969773
  ~MaybeStackBuffer() {
481
8969773
    if (IsAllocated())
482
284422
      free(buf_);
483
8969773
  }
484
485
 private:
486
  size_t length_;
487
  // capacity of the malloc'ed buf_
488
  size_t capacity_;
489
  T* buf_;
490
  T buf_st_[kStackStorageSize];
491
};
492
493
// Provides access to an ArrayBufferView's storage, either the original,
494
// or for small data, a copy of it. This object's lifetime is bound to the
495
// original ArrayBufferView's lifetime.
496
template <typename T, size_t kStackStorageSize = 64>
497
class ArrayBufferViewContents {
498
 public:
499
1234
  ArrayBufferViewContents() = default;
500
501
  explicit inline ArrayBufferViewContents(v8::Local<v8::Value> value);
502
  explicit inline ArrayBufferViewContents(v8::Local<v8::Object> value);
503
  explicit inline ArrayBufferViewContents(v8::Local<v8::ArrayBufferView> abv);
504
  inline void Read(v8::Local<v8::ArrayBufferView> abv);
505
506
185145
  inline const T* data() const { return data_; }
507
471081
  inline size_t length() const { return length_; }
508
509
 private:
510
  T stack_storage_[kStackStorageSize];
511
  T* data_ = nullptr;
512
  size_t length_ = 0;
513
};
514
515
class Utf8Value : public MaybeStackBuffer<char> {
516
 public:
517
  explicit Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value);
518
519
1013
  inline std::string ToString() const { return std::string(out(), length()); }
520
521
4814
  inline bool operator==(const char* a) const {
522
4814
    return strcmp(out(), a) == 0;
523
  }
524
};
525
526
class TwoByteValue : public MaybeStackBuffer<uint16_t> {
527
 public:
528
  explicit TwoByteValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
529
};
530
531
class BufferValue : public MaybeStackBuffer<char> {
532
 public:
533
  explicit BufferValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
534
535
  inline std::string ToString() const { return std::string(out(), length()); }
536
};
537
538
#define SPREAD_BUFFER_ARG(val, name)                                          \
539
  CHECK((val)->IsArrayBufferView());                                          \
540
  v8::Local<v8::ArrayBufferView> name = (val).As<v8::ArrayBufferView>();      \
541
  std::shared_ptr<v8::BackingStore> name##_bs =                               \
542
      name->Buffer()->GetBackingStore();                                      \
543
  const size_t name##_offset = name->ByteOffset();                            \
544
  const size_t name##_length = name->ByteLength();                            \
545
  char* const name##_data =                                                   \
546
      static_cast<char*>(name##_bs->Data()) + name##_offset;                  \
547
  if (name##_length > 0)                                                      \
548
    CHECK_NE(name##_data, nullptr);
549
550
// Use this when a variable or parameter is unused in order to explicitly
551
// silence a compiler warning about that.
552
5407934
template <typename T> inline void USE(T&&) {}
553
554
template <typename Fn>
555
struct OnScopeLeaveImpl {
556
  Fn fn_;
557
  bool active_;
558
559
3326899
  explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {}
560
1678088
  ~OnScopeLeaveImpl() { if (active_) fn_(); }
561
562
  OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete;
563
  OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete;
564
  OnScopeLeaveImpl(OnScopeLeaveImpl&& other)
565
    : fn_(std::move(other.fn_)), active_(other.active_) {
566
    other.active_ = false;
567
  }
568
  OnScopeLeaveImpl& operator=(OnScopeLeaveImpl&& other) {
569
    if (this == &other) return *this;
570
    this->~OnScopeLeave();
571
    new (this)OnScopeLeaveImpl(std::move(other));
572
    return *this;
573
  }
574
};
575
576
// Run a function when exiting the current scope. Used like this:
577
// auto on_scope_leave = OnScopeLeave([&] {
578
//   // ... run some code ...
579
// });
580
template <typename Fn>
581
3326899
inline MUST_USE_RESULT OnScopeLeaveImpl<Fn> OnScopeLeave(Fn&& fn) {
582
3326899
  return OnScopeLeaveImpl<Fn>{std::move(fn)};
583
}
584
585
// Simple RAII wrapper for contiguous data that uses malloc()/free().
586
template <typename T>
587
struct MallocedBuffer {
588
  T* data;
589
  size_t size;
590
591
  T* release() {
592
    T* ret = data;
593
    data = nullptr;
594
    return ret;
595
  }
596
597
  void Truncate(size_t new_size) {
598
    CHECK(new_size <= size);
599
    size = new_size;
600
  }
601
602
  void Realloc(size_t new_size) {
603
    Truncate(new_size);
604
    data = UncheckedRealloc(data, new_size);
605
  }
606
607
64068
  inline bool is_empty() const { return data == nullptr; }
608
609
103451
  MallocedBuffer() : data(nullptr), size(0) {}
610
23
  explicit MallocedBuffer(size_t size) : data(Malloc<T>(size)), size(size) {}
611
64082
  MallocedBuffer(T* data, size_t size) : data(data), size(size) {}
612
167495
  MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) {
613
167495
    other.data = nullptr;
614
167495
  }
615
64096
  MallocedBuffer& operator=(MallocedBuffer&& other) {
616
64096
    this->~MallocedBuffer();
617
64096
    return *new(this) MallocedBuffer(std::move(other));
618
  }
619
334992
  ~MallocedBuffer() {
620
334992
    free(data);
621
334992
  }
622
  MallocedBuffer(const MallocedBuffer&) = delete;
623
  MallocedBuffer& operator=(const MallocedBuffer&) = delete;
624
};
625
626
template <typename T>
627
class NonCopyableMaybe {
628
 public:
629
4063
  NonCopyableMaybe() : empty_(true) {}
630
3809
  explicit NonCopyableMaybe(T&& value)
631
      : empty_(false),
632
7618
        value_(std::move(value)) {}
633
634
7558
  bool IsEmpty() const {
635
7558
    return empty_;
636
  }
637
638
1460
  const T* get() const {
639
1460
    return empty_ ? nullptr : &value_;
640
  }
641
642
24
  const T* operator->() const {
643
24
    CHECK(!empty_);
644
24
    return &value_;
645
  }
646
647
3714
  T&& Release() {
648
3714
    CHECK_EQ(empty_, false);
649
3714
    empty_ = true;
650
3714
    return std::move(value_);
651
  }
652
653
 private:
654
  bool empty_;
655
  T value_;
656
};
657
658
// Test whether some value can be called with ().
659
template <typename T, typename = void>
660
struct is_callable : std::is_function<T> { };
661
662
template <typename T>
663
struct is_callable<T, typename std::enable_if<
664
    std::is_same<decltype(void(&T::operator())), void>::value
665
    >::type> : std::true_type { };
666
667
template <typename T, void (*function)(T*)>
668
struct FunctionDeleter {
669
185895
  void operator()(T* pointer) const { function(pointer); }
670
  typedef std::unique_ptr<T, FunctionDeleter> Pointer;
671
};
672
673
template <typename T, void (*function)(T*)>
674
using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer;
675
676
std::vector<std::string> SplitString(const std::string& in,
677
                                     char delim,
678
                                     bool skipEmpty = true);
679
680
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
681
                                           std::string_view str,
682
                                           v8::Isolate* isolate = nullptr);
683
template <typename T, typename test_for_number =
684
    typename std::enable_if<std::numeric_limits<T>::is_specialized, bool>::type>
685
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
686
                                           const T& number,
687
                                           v8::Isolate* isolate = nullptr);
688
template <typename T>
689
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
690
                                           const std::vector<T>& vec,
691
                                           v8::Isolate* isolate = nullptr);
692
template <typename T>
693
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
694
                                           const std::set<T>& set,
695
                                           v8::Isolate* isolate = nullptr);
696
template <typename T, typename U>
697
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
698
                                           const std::unordered_map<T, U>& map,
699
                                           v8::Isolate* isolate = nullptr);
700
701
// These macros expects a `Isolate* isolate` and a `Local<Context> context`
702
// to be in the scope.
703
#define READONLY_PROPERTY(obj, name, value)                                    \
704
  do {                                                                         \
705
    obj->DefineOwnProperty(                                                    \
706
           context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \
707
        .Check();                                                              \
708
  } while (0)
709
710
#define READONLY_DONT_ENUM_PROPERTY(obj, name, var)                            \
711
  do {                                                                         \
712
    obj->DefineOwnProperty(                                                    \
713
           context,                                                            \
714
           OneByteString(isolate, name),                                       \
715
           var,                                                                \
716
           static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum))    \
717
        .Check();                                                              \
718
  } while (0)
719
720
#define READONLY_FALSE_PROPERTY(obj, name)                                     \
721
  READONLY_PROPERTY(obj, name, v8::False(isolate))
722
723
#define READONLY_TRUE_PROPERTY(obj, name)                                      \
724
  READONLY_PROPERTY(obj, name, v8::True(isolate))
725
726
#define READONLY_STRING_PROPERTY(obj, name, str)                               \
727
  READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked())
728
729
// Variation on NODE_DEFINE_CONSTANT that sets a String value.
730
#define NODE_DEFINE_STRING_CONSTANT(target, name, constant)                    \
731
  do {                                                                         \
732
    v8::Isolate* isolate = target->GetIsolate();                               \
733
    v8::Local<v8::String> constant_name =                                      \
734
        v8::String::NewFromUtf8(isolate, name).ToLocalChecked();               \
735
    v8::Local<v8::String> constant_value =                                     \
736
        v8::String::NewFromUtf8(isolate, constant).ToLocalChecked();           \
737
    v8::PropertyAttribute constant_attributes =                                \
738
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);     \
739
    target                                                                     \
740
        ->DefineOwnProperty(isolate->GetCurrentContext(),                      \
741
                            constant_name,                                     \
742
                            constant_value,                                    \
743
                            constant_attributes)                               \
744
        .Check();                                                              \
745
  } while (0)
746
747
enum Endianness {
748
  kLittleEndian,  // _Not_ LITTLE_ENDIAN, clashes with endian.h.
749
  kBigEndian
750
};
751
752
8174
inline enum Endianness GetEndianness() {
753
  // Constant-folded by the compiler.
754
  const union {
755
    uint8_t u8[2];
756
    uint16_t u16;
757
8174
  } u = {{1, 0}};
758
8174
  return u.u16 == 1 ? kLittleEndian : kBigEndian;
759
}
760
761
1
inline bool IsLittleEndian() {
762
1
  return GetEndianness() == kLittleEndian;
763
}
764
765
8173
inline bool IsBigEndian() {
766
8173
  return GetEndianness() == kBigEndian;
767
}
768
769
// Round up a to the next highest multiple of b.
770
template <typename T>
771
160167
constexpr T RoundUp(T a, T b) {
772
160167
  return a % b != 0 ? a + b - (a % b) : a;
773
}
774
775
// Align ptr to an `alignment`-bytes boundary.
776
template <typename T, typename U>
777
26171
constexpr T* AlignUp(T* ptr, U alignment) {
778
  return reinterpret_cast<T*>(
779
26171
      RoundUp(reinterpret_cast<uintptr_t>(ptr), alignment));
780
}
781
782
class SlicedArguments : public MaybeStackBuffer<v8::Local<v8::Value>> {
783
 public:
784
  inline explicit SlicedArguments(
785
      const v8::FunctionCallbackInfo<v8::Value>& args, size_t start = 0);
786
};
787
788
// Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra
789
// optimization for strong persistent handles.
790
class PersistentToLocal {
791
 public:
792
  // If persistent.IsWeak() == false, then do not call persistent.Reset()
793
  // while the returned Local<T> is still in scope, it will destroy the
794
  // reference to the object.
795
  template <class TypeName>
796
6846183
  static inline v8::Local<TypeName> Default(
797
      v8::Isolate* isolate,
798
      const v8::PersistentBase<TypeName>& persistent) {
799
6846183
    if (persistent.IsWeak()) {
800
4500528
      return PersistentToLocal::Weak(isolate, persistent);
801
    } else {
802
2345655
      return PersistentToLocal::Strong(persistent);
803
    }
804
  }
805
806
  // Unchecked conversion from a non-weak Persistent<T> to Local<T>,
807
  // use with care!
808
  //
809
  // Do not call persistent.Reset() while the returned Local<T> is still in
810
  // scope, it will destroy the reference to the object.
811
  template <class TypeName>
812
35496713
  static inline v8::Local<TypeName> Strong(
813
      const v8::PersistentBase<TypeName>& persistent) {
814
    DCHECK(!persistent.IsWeak());
815
    return *reinterpret_cast<v8::Local<TypeName>*>(
816
35496713
        const_cast<v8::PersistentBase<TypeName>*>(&persistent));
817
  }
818
819
  template <class TypeName>
820
2377511
  static inline v8::Local<TypeName> Weak(
821
      v8::Isolate* isolate,
822
      const v8::PersistentBase<TypeName>& persistent) {
823
2377511
    return v8::Local<TypeName>::New(isolate, persistent);
824
  }
825
};
826
827
// Can be used as a key for std::unordered_map when lookup performance is more
828
// important than size and the keys are statically used to avoid redundant hash
829
// computations.
830
class FastStringKey {
831
 public:
832
  constexpr explicit FastStringKey(const char* name);
833
834
  struct Hash {
835
    constexpr size_t operator()(const FastStringKey& key) const;
836
  };
837
  constexpr bool operator==(const FastStringKey& other) const;
838
839
  constexpr const char* c_str() const;
840
841
 private:
842
  static constexpr size_t HashImpl(const char* str);
843
844
  const char* name_;
845
  size_t cached_hash_;
846
};
847
848
// Like std::static_pointer_cast but for unique_ptr with the default deleter.
849
template <typename T, typename U>
850
11272
std::unique_ptr<T> static_unique_pointer_cast(std::unique_ptr<U>&& ptr) {
851
11272
  return std::unique_ptr<T>(static_cast<T*>(ptr.release()));
852
}
853
854
#define MAYBE_FIELD_PTR(ptr, field) ptr == nullptr ? nullptr : &(ptr->field)
855
856
// Returns a non-zero code if it fails to open or read the file,
857
// aborts if it fails to close the file.
858
int ReadFileSync(std::string* result, const char* path);
859
860
v8::Local<v8::FunctionTemplate> NewFunctionTemplate(
861
    v8::Isolate* isolate,
862
    v8::FunctionCallback callback,
863
    v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(),
864
    v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow,
865
    v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect,
866
    const v8::CFunction* c_function = nullptr);
867
868
// Convenience methods for NewFunctionTemplate().
869
void SetMethod(v8::Local<v8::Context> context,
870
               v8::Local<v8::Object> that,
871
               const char* name,
872
               v8::FunctionCallback callback);
873
874
void SetFastMethod(v8::Local<v8::Context> context,
875
                   v8::Local<v8::Object> that,
876
                   const char* name,
877
                   v8::FunctionCallback slow_callback,
878
                   const v8::CFunction* c_function);
879
880
void SetProtoMethod(v8::Isolate* isolate,
881
                    v8::Local<v8::FunctionTemplate> that,
882
                    const char* name,
883
                    v8::FunctionCallback callback);
884
885
void SetInstanceMethod(v8::Isolate* isolate,
886
                       v8::Local<v8::FunctionTemplate> that,
887
                       const char* name,
888
                       v8::FunctionCallback callback);
889
890
// Safe variants denote the function has no side effects.
891
void SetMethodNoSideEffect(v8::Local<v8::Context> context,
892
                           v8::Local<v8::Object> that,
893
                           const char* name,
894
                           v8::FunctionCallback callback);
895
void SetProtoMethodNoSideEffect(v8::Isolate* isolate,
896
                                v8::Local<v8::FunctionTemplate> that,
897
                                const char* name,
898
                                v8::FunctionCallback callback);
899
900
enum class SetConstructorFunctionFlag {
901
  NONE,
902
  SET_CLASS_NAME,
903
};
904
905
void SetConstructorFunction(v8::Local<v8::Context> context,
906
                            v8::Local<v8::Object> that,
907
                            const char* name,
908
                            v8::Local<v8::FunctionTemplate> tmpl,
909
                            SetConstructorFunctionFlag flag =
910
                                SetConstructorFunctionFlag::SET_CLASS_NAME);
911
912
void SetConstructorFunction(v8::Local<v8::Context> context,
913
                            v8::Local<v8::Object> that,
914
                            v8::Local<v8::String> name,
915
                            v8::Local<v8::FunctionTemplate> tmpl,
916
                            SetConstructorFunctionFlag flag =
917
                                SetConstructorFunctionFlag::SET_CLASS_NAME);
918
919
}  // namespace node
920
921
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
922
923
#endif  // SRC_UTIL_H_