GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_util.cc Lines: 233 238 97.9 %
Date: 2022-08-06 04:16:36 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
144613
static void GetOwnNonIndexProperties(
51
    const FunctionCallbackInfo<Value>& args) {
52
144613
  Environment* env = Environment::GetCurrent(args);
53
144613
  Local<Context> context = env->context();
54
55
144613
  CHECK(args[0]->IsObject());
56
144613
  CHECK(args[1]->IsUint32());
57
58
289226
  Local<Object> object = args[0].As<Object>();
59
60
  Local<Array> properties;
61
62
  PropertyFilter filter =
63
289226
    static_cast<PropertyFilter>(args[1].As<Uint32>()->Value());
64
65
144613
  if (!object->GetPropertyNames(
66
        context, KeyCollectionMode::kOwnOnly,
67
        filter,
68
144613
        IndexFilter::kSkipIndices)
69
144613
          .ToLocal(&properties)) {
70
2
    return;
71
  }
72
289222
  args.GetReturnValue().Set(properties);
73
}
74
75
2262
static void GetConstructorName(
76
    const FunctionCallbackInfo<Value>& args) {
77
2262
  CHECK(args[0]->IsObject());
78
79
4524
  Local<Object> object = args[0].As<Object>();
80
2262
  Local<String> name = object->GetConstructorName();
81
82
2262
  args.GetReturnValue().Set(name);
83
2262
}
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
1219
static void GetPromiseDetails(const FunctionCallbackInfo<Value>& args) {
98
  // Return undefined if it's not a Promise.
99
1219
  if (!args[0]->IsPromise())
100
1
    return;
101
102
1218
  auto isolate = args.GetIsolate();
103
104
2436
  Local<Promise> promise = args[0].As<Promise>();
105
106
1218
  int state = promise->State();
107
3654
  Local<Value> values[2] = { Integer::New(isolate, state) };
108
1218
  size_t number_of_values = 1;
109
1218
  if (state != Promise::PromiseState::kPending)
110
1014
    values[number_of_values++] = promise->Result();
111
1218
  Local<Array> ret = Array::New(isolate, values, number_of_values);
112
2436
  args.GetReturnValue().Set(ret);
113
}
114
115
276250
static void GetProxyDetails(const FunctionCallbackInfo<Value>& args) {
116
  // Return undefined if it's not a proxy.
117
276250
  if (!args[0]->IsProxy())
118
276132
    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
5710
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
5710
  CHECK_LT(index, arraysize(methods));
168
5710
  return (env->*methods[index])();
169
}
170
171
962
static void GetHiddenValue(const FunctionCallbackInfo<Value>& args) {
172
962
  Environment* env = Environment::GetCurrent(args);
173
174
962
  CHECK(args[0]->IsObject());
175
962
  CHECK(args[1]->IsUint32());
176
177
1924
  Local<Object> obj = args[0].As<Object>();
178
2886
  uint32_t index = args[1].As<Uint32>()->Value();
179
962
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
180
  Local<Value> ret;
181
1924
  if (obj->GetPrivate(env->context(), private_symbol).ToLocal(&ret))
182
1924
    args.GetReturnValue().Set(ret);
183
962
}
184
185
4748
static void SetHiddenValue(const FunctionCallbackInfo<Value>& args) {
186
4748
  Environment* env = Environment::GetCurrent(args);
187
188
4748
  CHECK(args[0]->IsObject());
189
4748
  CHECK(args[1]->IsUint32());
190
191
9496
  Local<Object> obj = args[0].As<Object>();
192
9496
  uint32_t index = args[1].As<Uint32>()->Value();
193
4748
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
194
  bool ret;
195

14244
  if (obj->SetPrivate(env->context(), private_symbol, args[2]).To(&ret))
196
9496
    args.GetReturnValue().Set(ret);
197
4748
}
198
199
10
static void Sleep(const FunctionCallbackInfo<Value>& args) {
200
10
  CHECK(args[0]->IsUint32());
201
20
  uint32_t msec = args[0].As<Uint32>()->Value();
202
10
  uv_sleep(msec);
203
10
}
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
11684
  WeakReference(Environment* env, Local<Object> object, Local<Object> target)
213
11684
    : BaseObject(env, object) {
214
11684
    MakeWeak();
215
11684
    target_.Reset(env->isolate(), target);
216
11684
    target_.SetWeak();
217
11684
  }
218
219
11684
  static void New(const FunctionCallbackInfo<Value>& args) {
220
11684
    Environment* env = Environment::GetCurrent(args);
221
11684
    CHECK(args.IsConstructCall());
222
11684
    CHECK(args[0]->IsObject());
223
35052
    new WeakReference(env, args.This(), args[0].As<Object>());
224
11684
  }
225
226
10625
  static void Get(const FunctionCallbackInfo<Value>& args) {
227
10625
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
228
10625
    Isolate* isolate = args.GetIsolate();
229
10625
    if (!weak_ref->target_.IsEmpty())
230
21248
      args.GetReturnValue().Set(weak_ref->target_.Get(isolate));
231
10625
  }
232
233
5308
  static void IncRef(const FunctionCallbackInfo<Value>& args) {
234
5308
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
235
5308
    weak_ref->reference_count_++;
236
5308
    if (weak_ref->target_.IsEmpty()) return;
237
5308
    if (weak_ref->reference_count_ == 1) weak_ref->target_.ClearWeak();
238
  }
239
240
5303
  static void DecRef(const FunctionCallbackInfo<Value>& args) {
241
5303
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
242
5303
    CHECK_GE(weak_ref->reference_count_, 1);
243
5303
    weak_ref->reference_count_--;
244
5303
    if (weak_ref->target_.IsEmpty()) return;
245
5303
    if (weak_ref->reference_count_ == 0) weak_ref->target_.SetWeak();
246
  }
247
248
34
  SET_MEMORY_INFO_NAME(WeakReference)
249
34
  SET_SELF_SIZE(WeakReference)
250
34
  SET_NO_MEMORY_INFO()
251
252
 private:
253
  Global<Object> target_;
254
  uint64_t reference_count_ = 0;
255
};
256
257
5537
static void GuessHandleType(const FunctionCallbackInfo<Value>& args) {
258
5537
  Environment* env = Environment::GetCurrent(args);
259
  int fd;
260
11074
  if (!args[0]->Int32Value(env->context()).To(&fd)) return;
261
5537
  CHECK_GE(fd, 0);
262
263
5537
  uv_handle_type t = uv_guess_handle(fd);
264
5537
  const char* type = nullptr;
265
266

5537
  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
2595
    case UV_FILE:
277
2595
      type = "FILE";
278
2595
      break;
279
2891
    case UV_NAMED_PIPE:
280
2891
      type = "PIPE";
281
2891
      break;
282
5
    case UV_UNKNOWN_HANDLE:
283
5
      type = "UNKNOWN";
284
5
      break;
285
    default:
286
      ABORT();
287
  }
288
289
11074
  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
5320
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
327
5320
  registry->Register(GetHiddenValue);
328
5320
  registry->Register(SetHiddenValue);
329
5320
  registry->Register(GetPromiseDetails);
330
5320
  registry->Register(GetProxyDetails);
331
5320
  registry->Register(PreviewEntries);
332
5320
  registry->Register(GetOwnNonIndexProperties);
333
5320
  registry->Register(GetConstructorName);
334
5320
  registry->Register(GetExternalValue);
335
5320
  registry->Register(Sleep);
336
5320
  registry->Register(ArrayBufferViewHasBuffer);
337
5320
  registry->Register(WeakReference::New);
338
5320
  registry->Register(WeakReference::Get);
339
5320
  registry->Register(WeakReference::IncRef);
340
5320
  registry->Register(WeakReference::DecRef);
341
5320
  registry->Register(GuessHandleType);
342
5320
  registry->Register(ToUSVString);
343
5320
}
344
345
781
void Initialize(Local<Object> target,
346
                Local<Value> unused,
347
                Local<Context> context,
348
                void* priv) {
349
781
  Environment* env = Environment::GetCurrent(context);
350
781
  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
781
    uint32_t index = 0;
358
21868
    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
3124
  V(kPending);
368
3124
  V(kFulfilled);
369
2343
  V(kRejected);
370
#undef V
371
372
781
  SetMethodNoSideEffect(context, target, "getHiddenValue", GetHiddenValue);
373
781
  SetMethod(context, target, "setHiddenValue", SetHiddenValue);
374
781
  SetMethodNoSideEffect(
375
      context, target, "getPromiseDetails", GetPromiseDetails);
376
781
  SetMethodNoSideEffect(context, target, "getProxyDetails", GetProxyDetails);
377
781
  SetMethodNoSideEffect(context, target, "previewEntries", PreviewEntries);
378
781
  SetMethodNoSideEffect(
379
      context, target, "getOwnNonIndexProperties", GetOwnNonIndexProperties);
380
781
  SetMethodNoSideEffect(
381
      context, target, "getConstructorName", GetConstructorName);
382
781
  SetMethodNoSideEffect(context, target, "getExternalValue", GetExternalValue);
383
781
  SetMethod(context, target, "sleep", Sleep);
384
385
781
  SetMethod(
386
      context, target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer);
387
781
  Local<Object> constants = Object::New(env->isolate());
388
2343
  NODE_DEFINE_CONSTANT(constants, ALL_PROPERTIES);
389
2343
  NODE_DEFINE_CONSTANT(constants, ONLY_WRITABLE);
390
2343
  NODE_DEFINE_CONSTANT(constants, ONLY_ENUMERABLE);
391
2343
  NODE_DEFINE_CONSTANT(constants, ONLY_CONFIGURABLE);
392
2343
  NODE_DEFINE_CONSTANT(constants, SKIP_STRINGS);
393
2343
  NODE_DEFINE_CONSTANT(constants, SKIP_SYMBOLS);
394
781
  target->Set(context,
395
              FIXED_ONE_BYTE_STRING(env->isolate(), "propertyFilter"),
396
1562
              constants).Check();
397
398
  Local<String> should_abort_on_uncaught_toggle =
399
781
      FIXED_ONE_BYTE_STRING(env->isolate(), "shouldAbortOnUncaughtToggle");
400
2343
  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
781
      NewFunctionTemplate(isolate, WeakReference::New);
408
1562
  weak_ref->InstanceTemplate()->SetInternalFieldCount(
409
      WeakReference::kInternalFieldCount);
410
781
  weak_ref->Inherit(BaseObject::GetConstructorTemplate(env));
411
781
  SetProtoMethod(isolate, weak_ref, "get", WeakReference::Get);
412
781
  SetProtoMethod(isolate, weak_ref, "incRef", WeakReference::IncRef);
413
781
  SetProtoMethod(isolate, weak_ref, "decRef", WeakReference::DecRef);
414
781
  SetConstructorFunction(context, target, "WeakReference", weak_ref);
415
416
781
  SetMethod(context, target, "guessHandleType", GuessHandleType);
417
418
781
  SetMethodNoSideEffect(context, target, "toUSVString", ToUSVString);
419
781
}
420
421
}  // namespace util
422
}  // namespace node
423
424
5392
NODE_MODULE_CONTEXT_AWARE_INTERNAL(util, node::util::Initialize)
425
5320
NODE_MODULE_EXTERNAL_REFERENCE(util, node::util::RegisterExternalReferences)