GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: util.h Lines: 134 134 100.0 %
Date: 2022-08-05 04:16:08 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
26449
  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
6872
  KVStore() = default;
279
12504
  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
7308907
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
321
    v8::Isolate* isolate,
322
    const char(&data)[N]) {
323
7308907
  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
11957361
constexpr size_t arraysize(const T (&)[N]) {
357
11957361
  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
5847
  const T* out() const {
371
5847
    return buf_;
372
  }
373
374
6498310
  T* out() {
375
6498310
    return buf_;
376
  }
377
378
  // operator* for compatibility with `v8::String::(Utf8)Value`
379
9792726
  T* operator*() {
380
9792726
    return buf_;
381
  }
382
383
32421
  const T* operator*() const {
384
32421
    return buf_;
385
  }
386
387
4804346
  T& operator[](size_t index) {
388
4804346
    CHECK_LT(index, length());
389
4804346
    return buf_[index];
390
  }
391
392
11703
  const T& operator[](size_t index) const {
393
11703
    CHECK_LT(index, length());
394
11703
    return buf_[index];
395
  }
396
397
13480391
  size_t length() const {
398
13480391
    return length_;
399
  }
400
401
  // Current maximum capacity of the buffer with which SetLength() can be used
402
  // without first calling AllocateSufficientStorage().
403
20302264
  size_t capacity() const {
404
20302264
    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
7234548
  void AllocateSufficientStorage(size_t storage) {
412
7234548
    CHECK(!IsInvalidated());
413
7234548
    if (storage > capacity()) {
414
286053
      bool was_allocated = IsAllocated();
415
286053
      T* allocated_ptr = was_allocated ? buf_ : nullptr;
416
286053
      buf_ = Realloc(allocated_ptr, storage);
417
286053
      capacity_ = storage;
418

286053
      if (!was_allocated && length_ > 0)
419
4
        memcpy(buf_, buf_st_, length_ * sizeof(buf_[0]));
420
    }
421
422
7234548
    length_ = storage;
423
7234548
  }
424
425
6396308
  void SetLength(size_t length) {
426
    // capacity() returns how much memory is actually available.
427
6396308
    CHECK_LE(length, capacity());
428
6396308
    length_ = length;
429
6396308
  }
430
431
9490754
  void SetLengthAndZeroTerminate(size_t length) {
432
    // capacity() returns how much memory is actually available.
433
9490754
    CHECK_LE(length + 1, capacity());
434
9490754
    SetLength(length);
435
436
    // T() is 0 for integer types, nullptr for pointers, etc.
437
9490754
    buf_[length] = T();
438
9490754
  }
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
9279133
  bool IsAllocated() const {
453

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