GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_util.cc Lines: 233 238 97.9 %
Date: 2022-08-02 04:16:51 Branches: 88 135 65.2 %

Line Branch Exec Source
1
#include "base_object-inl.h"
2
#include "node_errors.h"
3
#include "node_external_reference.h"
4
#include "util-inl.h"
5
6
namespace node {
7
namespace util {
8
9
using v8::ALL_PROPERTIES;
10
using v8::Array;
11
using v8::ArrayBufferView;
12
using v8::BigInt;
13
using v8::Boolean;
14
using v8::Context;
15
using v8::External;
16
using v8::FunctionCallbackInfo;
17
using v8::FunctionTemplate;
18
using v8::Global;
19
using v8::IndexFilter;
20
using v8::Integer;
21
using v8::Isolate;
22
using v8::KeyCollectionMode;
23
using v8::Local;
24
using v8::Object;
25
using v8::ONLY_CONFIGURABLE;
26
using v8::ONLY_ENUMERABLE;
27
using v8::ONLY_WRITABLE;
28
using v8::Private;
29
using v8::Promise;
30
using v8::PropertyFilter;
31
using v8::Proxy;
32
using v8::SKIP_STRINGS;
33
using v8::SKIP_SYMBOLS;
34
using v8::String;
35
using v8::Uint32;
36
using v8::Value;
37
38
// Used in ToUSVString().
39
constexpr char16_t kUnicodeReplacementCharacter = 0xFFFD;
40
41
// If a UTF-16 character is a low/trailing surrogate.
42
3
CHAR_TEST(16, IsUnicodeTrail, (ch & 0xFC00) == 0xDC00)
43
44
// If a UTF-16 character is a surrogate.
45
32
CHAR_TEST(16, IsUnicodeSurrogate, (ch & 0xF800) == 0xD800)
46
47
// If a UTF-16 surrogate is a low/trailing one.
48
19
CHAR_TEST(16, IsUnicodeSurrogateTrail, (ch & 0x400) != 0)
49
50
143544
static void GetOwnNonIndexProperties(
51
    const FunctionCallbackInfo<Value>& args) {
52
143544
  Environment* env = Environment::GetCurrent(args);
53
143544
  Local<Context> context = env->context();
54
55
143544
  CHECK(args[0]->IsObject());
56
143544
  CHECK(args[1]->IsUint32());
57
58
287088
  Local<Object> object = args[0].As<Object>();
59
60
  Local<Array> properties;
61
62
  PropertyFilter filter =
63
287088
    static_cast<PropertyFilter>(args[1].As<Uint32>()->Value());
64
65
143544
  if (!object->GetPropertyNames(
66
        context, KeyCollectionMode::kOwnOnly,
67
        filter,
68
143544
        IndexFilter::kSkipIndices)
69
143544
          .ToLocal(&properties)) {
70
2
    return;
71
  }
72
287084
  args.GetReturnValue().Set(properties);
73
}
74
75
2259
static void GetConstructorName(
76
    const FunctionCallbackInfo<Value>& args) {
77
2259
  CHECK(args[0]->IsObject());
78
79
4518
  Local<Object> object = args[0].As<Object>();
80
2259
  Local<String> name = object->GetConstructorName();
81
82
2259
  args.GetReturnValue().Set(name);
83
2259
}
84
85
44
static void GetExternalValue(
86
    const FunctionCallbackInfo<Value>& args) {
87
44
  CHECK(args[0]->IsExternal());
88
44
  Isolate* isolate = args.GetIsolate();
89
88
  Local<External> external = args[0].As<External>();
90
91
44
  void* ptr = external->Value();
92
44
  uint64_t value = reinterpret_cast<uint64_t>(ptr);
93
44
  Local<BigInt> ret = BigInt::NewFromUnsigned(isolate, value);
94
44
  args.GetReturnValue().Set(ret);
95
44
}
96
97
1244
static void GetPromiseDetails(const FunctionCallbackInfo<Value>& args) {
98
  // Return undefined if it's not a Promise.
99
1244
  if (!args[0]->IsPromise())
100
1
    return;
101
102
1243
  auto isolate = args.GetIsolate();
103
104
2486
  Local<Promise> promise = args[0].As<Promise>();
105
106
1243
  int state = promise->State();
107
3729
  Local<Value> values[2] = { Integer::New(isolate, state) };
108
1243
  size_t number_of_values = 1;
109
1243
  if (state != Promise::PromiseState::kPending)
110
1039
    values[number_of_values++] = promise->Result();
111
1243
  Local<Array> ret = Array::New(isolate, values, number_of_values);
112
2486
  args.GetReturnValue().Set(ret);
113
}
114
115
276243
static void GetProxyDetails(const FunctionCallbackInfo<Value>& args) {
116
  // Return undefined if it's not a proxy.
117
276243
  if (!args[0]->IsProxy())
118
276125
    return;
119
120
236
  Local<Proxy> proxy = args[0].As<Proxy>();
121
122
  // TODO(BridgeAR): Remove the length check as soon as we prohibit access to
123
  // the util binding layer. It's accessed in the wild and `esm` would break in
124
  // case the check is removed.
125

235
  if (args.Length() == 1 || args[1]->IsTrue()) {
126
    Local<Value> ret[] = {
127
46
      proxy->GetTarget(),
128
46
      proxy->GetHandler()
129
138
    };
130
131
138
    args.GetReturnValue().Set(
132
        Array::New(args.GetIsolate(), ret, arraysize(ret)));
133
  } else {
134
72
    Local<Value> ret = proxy->GetTarget();
135
136
144
    args.GetReturnValue().Set(ret);
137
  }
138
}
139
140
124
static void PreviewEntries(const FunctionCallbackInfo<Value>& args) {
141
124
  if (!args[0]->IsObject())
142
    return;
143
144
124
  Environment* env = Environment::GetCurrent(args);
145
  bool is_key_value;
146
  Local<Array> entries;
147
372
  if (!args[0].As<Object>()->PreviewEntries(&is_key_value).ToLocal(&entries))
148
    return;
149
  // Fast path for WeakMap and WeakSet.
150
124
  if (args.Length() == 1)
151
16
    return args.GetReturnValue().Set(entries);
152
153
  Local<Value> ret[] = {
154
    entries,
155
    Boolean::New(env->isolate(), is_key_value)
156
232
  };
157
116
  return args.GetReturnValue().Set(
158
116
      Array::New(env->isolate(), ret, arraysize(ret)));
159
}
160
161
6743
inline Local<Private> IndexToPrivateSymbol(Environment* env, uint32_t index) {
162
#define V(name, _) &Environment::name,
163
  static Local<Private> (Environment::*const methods[])() const = {
164
    PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
165
  };
166
#undef V
167
6743
  CHECK_LT(index, arraysize(methods));
168
6743
  return (env->*methods[index])();
169
}
170
171
1482
static void GetHiddenValue(const FunctionCallbackInfo<Value>& args) {
172
1482
  Environment* env = Environment::GetCurrent(args);
173
174
1482
  CHECK(args[0]->IsObject());
175
1482
  CHECK(args[1]->IsUint32());
176
177
2964
  Local<Object> obj = args[0].As<Object>();
178
4446
  uint32_t index = args[1].As<Uint32>()->Value();
179
1482
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
180
  Local<Value> ret;
181
2964
  if (obj->GetPrivate(env->context(), private_symbol).ToLocal(&ret))
182
2964
    args.GetReturnValue().Set(ret);
183
1482
}
184
185
5261
static void SetHiddenValue(const FunctionCallbackInfo<Value>& args) {
186
5261
  Environment* env = Environment::GetCurrent(args);
187
188
5261
  CHECK(args[0]->IsObject());
189
5261
  CHECK(args[1]->IsUint32());
190
191
10522
  Local<Object> obj = args[0].As<Object>();
192
10522
  uint32_t index = args[1].As<Uint32>()->Value();
193
5261
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
194
  bool ret;
195

15783
  if (obj->SetPrivate(env->context(), private_symbol, args[2]).To(&ret))
196
10522
    args.GetReturnValue().Set(ret);
197
5261
}
198
199
9
static void Sleep(const FunctionCallbackInfo<Value>& args) {
200
9
  CHECK(args[0]->IsUint32());
201
18
  uint32_t msec = args[0].As<Uint32>()->Value();
202
9
  uv_sleep(msec);
203
9
}
204
205
56
void ArrayBufferViewHasBuffer(const FunctionCallbackInfo<Value>& args) {
206
56
  CHECK(args[0]->IsArrayBufferView());
207

168
  args.GetReturnValue().Set(args[0].As<ArrayBufferView>()->HasBuffer());
208
56
}
209
210
class WeakReference : public BaseObject {
211
 public:
212
23991
  WeakReference(Environment* env, Local<Object> object, Local<Object> target)
213
23991
    : BaseObject(env, object) {
214
23991
    MakeWeak();
215
23991
    target_.Reset(env->isolate(), target);
216
23991
    target_.SetWeak();
217
23991
  }
218
219
23991
  static void New(const FunctionCallbackInfo<Value>& args) {
220
23991
    Environment* env = Environment::GetCurrent(args);
221
23991
    CHECK(args.IsConstructCall());
222
23991
    CHECK(args[0]->IsObject());
223
71973
    new WeakReference(env, args.This(), args[0].As<Object>());
224
23991
  }
225
226
10725
  static void Get(const FunctionCallbackInfo<Value>& args) {
227
10725
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
228
10725
    Isolate* isolate = args.GetIsolate();
229
10725
    if (!weak_ref->target_.IsEmpty())
230
21448
      args.GetReturnValue().Set(weak_ref->target_.Get(isolate));
231
10725
  }
232
233
5358
  static void IncRef(const FunctionCallbackInfo<Value>& args) {
234
5358
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
235
5358
    weak_ref->reference_count_++;
236
5358
    if (weak_ref->target_.IsEmpty()) return;
237
5358
    if (weak_ref->reference_count_ == 1) weak_ref->target_.ClearWeak();
238
  }
239
240
5353
  static void DecRef(const FunctionCallbackInfo<Value>& args) {
241
5353
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
242
5353
    CHECK_GE(weak_ref->reference_count_, 1);
243
5353
    weak_ref->reference_count_--;
244
5353
    if (weak_ref->target_.IsEmpty()) return;
245
5353
    if (weak_ref->reference_count_ == 0) weak_ref->target_.SetWeak();
246
  }
247
248
78
  SET_MEMORY_INFO_NAME(WeakReference)
249
78
  SET_SELF_SIZE(WeakReference)
250
78
  SET_NO_MEMORY_INFO()
251
252
 private:
253
  Global<Object> target_;
254
  uint64_t reference_count_ = 0;
255
};
256
257
5500
static void GuessHandleType(const FunctionCallbackInfo<Value>& args) {
258
5500
  Environment* env = Environment::GetCurrent(args);
259
  int fd;
260
11000
  if (!args[0]->Int32Value(env->context()).To(&fd)) return;
261
5500
  CHECK_GE(fd, 0);
262
263
5500
  uv_handle_type t = uv_guess_handle(fd);
264
5500
  const char* type = nullptr;
265
266

5500
  switch (t) {
267
4
    case UV_TCP:
268
4
      type = "TCP";
269
4
      break;
270
36
    case UV_TTY:
271
36
      type = "TTY";
272
36
      break;
273
6
    case UV_UDP:
274
6
      type = "UDP";
275
6
      break;
276
2571
    case UV_FILE:
277
2571
      type = "FILE";
278
2571
      break;
279
2878
    case UV_NAMED_PIPE:
280
2878
      type = "PIPE";
281
2878
      break;
282
5
    case UV_UNKNOWN_HANDLE:
283
5
      type = "UNKNOWN";
284
5
      break;
285
    default:
286
      ABORT();
287
  }
288
289
11000
  args.GetReturnValue().Set(OneByteString(env->isolate(), type));
290
}
291
292
17
static void ToUSVString(const FunctionCallbackInfo<Value>& args) {
293
17
  Environment* env = Environment::GetCurrent(args);
294
17
  CHECK_GE(args.Length(), 2);
295
34
  CHECK(args[0]->IsString());
296
17
  CHECK(args[1]->IsNumber());
297
298
17
  TwoByteValue value(env->isolate(), args[0]);
299
300
17
  int64_t start = args[1]->IntegerValue(env->context()).FromJust();
301
17
  CHECK_GE(start, 0);
302
303
49
  for (size_t i = start; i < value.length(); i++) {
304
32
    char16_t c = value[i];
305
32
    if (!IsUnicodeSurrogate(c)) {
306
13
      continue;
307

19
    } else if (IsUnicodeSurrogateTrail(c) || i == value.length() - 1) {
308
16
      value[i] = kUnicodeReplacementCharacter;
309
    } else {
310
3
      char16_t d = value[i + 1];
311
3
      if (IsUnicodeTrail(d)) {
312
        i++;
313
      } else {
314
3
        value[i] = kUnicodeReplacementCharacter;
315
      }
316
    }
317
  }
318
319
51
  args.GetReturnValue().Set(
320
17
      String::NewFromTwoByte(env->isolate(),
321
17
                             *value,
322
                             v8::NewStringType::kNormal,
323
17
                             value.length()).ToLocalChecked());
324
17
}
325
326
5300
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
327
5300
  registry->Register(GetHiddenValue);
328
5300
  registry->Register(SetHiddenValue);
329
5300
  registry->Register(GetPromiseDetails);
330
5300
  registry->Register(GetProxyDetails);
331
5300
  registry->Register(PreviewEntries);
332
5300
  registry->Register(GetOwnNonIndexProperties);
333
5300
  registry->Register(GetConstructorName);
334
5300
  registry->Register(GetExternalValue);
335
5300
  registry->Register(Sleep);
336
5300
  registry->Register(ArrayBufferViewHasBuffer);
337
5300
  registry->Register(WeakReference::New);
338
5300
  registry->Register(WeakReference::Get);
339
5300
  registry->Register(WeakReference::IncRef);
340
5300
  registry->Register(WeakReference::DecRef);
341
5300
  registry->Register(GuessHandleType);
342
5300
  registry->Register(ToUSVString);
343
5300
}
344
345
1303
void Initialize(Local<Object> target,
346
                Local<Value> unused,
347
                Local<Context> context,
348
                void* priv) {
349
1303
  Environment* env = Environment::GetCurrent(context);
350
1303
  Isolate* isolate = env->isolate();
351
352
#define V(name, _)                                                            \
353
  target->Set(context,                                                        \
354
              FIXED_ONE_BYTE_STRING(env->isolate(), #name),                   \
355
              Integer::NewFromUnsigned(env->isolate(), index++)).Check();
356
  {
357
1303
    uint32_t index = 0;
358
36484
    PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
359
  }
360
#undef V
361
362
#define V(name)                                                               \
363
  target->Set(context,                                                        \
364
              FIXED_ONE_BYTE_STRING(env->isolate(), #name),                   \
365
              Integer::New(env->isolate(), Promise::PromiseState::name))      \
366
    .FromJust()
367
5212
  V(kPending);
368
5212
  V(kFulfilled);
369
3909
  V(kRejected);
370
#undef V
371
372
1303
  SetMethodNoSideEffect(context, target, "getHiddenValue", GetHiddenValue);
373
1303
  SetMethod(context, target, "setHiddenValue", SetHiddenValue);
374
1303
  SetMethodNoSideEffect(
375
      context, target, "getPromiseDetails", GetPromiseDetails);
376
1303
  SetMethodNoSideEffect(context, target, "getProxyDetails", GetProxyDetails);
377
1303
  SetMethodNoSideEffect(context, target, "previewEntries", PreviewEntries);
378
1303
  SetMethodNoSideEffect(
379
      context, target, "getOwnNonIndexProperties", GetOwnNonIndexProperties);
380
1303
  SetMethodNoSideEffect(
381
      context, target, "getConstructorName", GetConstructorName);
382
1303
  SetMethodNoSideEffect(context, target, "getExternalValue", GetExternalValue);
383
1303
  SetMethod(context, target, "sleep", Sleep);
384
385
1303
  SetMethod(
386
      context, target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer);
387
1303
  Local<Object> constants = Object::New(env->isolate());
388
3909
  NODE_DEFINE_CONSTANT(constants, ALL_PROPERTIES);
389
3909
  NODE_DEFINE_CONSTANT(constants, ONLY_WRITABLE);
390
3909
  NODE_DEFINE_CONSTANT(constants, ONLY_ENUMERABLE);
391
3909
  NODE_DEFINE_CONSTANT(constants, ONLY_CONFIGURABLE);
392
3909
  NODE_DEFINE_CONSTANT(constants, SKIP_STRINGS);
393
3909
  NODE_DEFINE_CONSTANT(constants, SKIP_SYMBOLS);
394
1303
  target->Set(context,
395
              FIXED_ONE_BYTE_STRING(env->isolate(), "propertyFilter"),
396
2606
              constants).Check();
397
398
  Local<String> should_abort_on_uncaught_toggle =
399
1303
      FIXED_ONE_BYTE_STRING(env->isolate(), "shouldAbortOnUncaughtToggle");
400
3909
  CHECK(target
401
            ->Set(context,
402
                  should_abort_on_uncaught_toggle,
403
                  env->should_abort_on_uncaught_toggle().GetJSArray())
404
            .FromJust());
405
406
  Local<FunctionTemplate> weak_ref =
407
1303
      NewFunctionTemplate(isolate, WeakReference::New);
408
2606
  weak_ref->InstanceTemplate()->SetInternalFieldCount(
409
      WeakReference::kInternalFieldCount);
410
1303
  weak_ref->Inherit(BaseObject::GetConstructorTemplate(env));
411
1303
  SetProtoMethod(isolate, weak_ref, "get", WeakReference::Get);
412
1303
  SetProtoMethod(isolate, weak_ref, "incRef", WeakReference::IncRef);
413
1303
  SetProtoMethod(isolate, weak_ref, "decRef", WeakReference::DecRef);
414
1303
  SetConstructorFunction(context, target, "WeakReference", weak_ref);
415
416
1303
  SetMethod(context, target, "guessHandleType", GuessHandleType);
417
418
1303
  SetMethodNoSideEffect(context, target, "toUSVString", ToUSVString);
419
1303
}
420
421
}  // namespace util
422
}  // namespace node
423
424
5368
NODE_MODULE_CONTEXT_AWARE_INTERNAL(util, node::util::Initialize)
425
5300
NODE_MODULE_EXTERNAL_REFERENCE(util, node::util::RegisterExternalReferences)