GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_util.cc Lines: 238 243 97.9 %
Date: 2021-10-05 04:12:38 Branches: 93 143 65.0 %

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
142953
static void GetOwnNonIndexProperties(
51
    const FunctionCallbackInfo<Value>& args) {
52
142953
  Environment* env = Environment::GetCurrent(args);
53
142953
  Local<Context> context = env->context();
54
55
142953
  CHECK(args[0]->IsObject());
56
142953
  CHECK(args[1]->IsUint32());
57
58
285906
  Local<Object> object = args[0].As<Object>();
59
60
  Local<Array> properties;
61
62
  PropertyFilter filter =
63
285906
    static_cast<PropertyFilter>(args[1].As<Uint32>()->Value());
64
65
142953
  if (!object->GetPropertyNames(
66
        context, KeyCollectionMode::kOwnOnly,
67
        filter,
68
142953
        IndexFilter::kSkipIndices)
69
142953
          .ToLocal(&properties)) {
70
2
    return;
71
  }
72
285902
  args.GetReturnValue().Set(properties);
73
}
74
75
2198
static void GetConstructorName(
76
    const FunctionCallbackInfo<Value>& args) {
77
2198
  CHECK(args[0]->IsObject());
78
79
4396
  Local<Object> object = args[0].As<Object>();
80
2198
  Local<String> name = object->GetConstructorName();
81
82
2198
  args.GetReturnValue().Set(name);
83
2198
}
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
823
static void GetPromiseDetails(const FunctionCallbackInfo<Value>& args) {
98
  // Return undefined if it's not a Promise.
99
823
  if (!args[0]->IsPromise())
100
1
    return;
101
102
822
  auto isolate = args.GetIsolate();
103
104
1644
  Local<Promise> promise = args[0].As<Promise>();
105
106
822
  int state = promise->State();
107
2466
  Local<Value> values[2] = { Integer::New(isolate, state) };
108
822
  size_t number_of_values = 1;
109
822
  if (state != Promise::PromiseState::kPending)
110
624
    values[number_of_values++] = promise->Result();
111
822
  Local<Array> ret = Array::New(isolate, values, number_of_values);
112
1644
  args.GetReturnValue().Set(ret);
113
}
114
115
271205
static void GetProxyDetails(const FunctionCallbackInfo<Value>& args) {
116
  // Return undefined if it's not a proxy.
117
271205
  if (!args[0]->IsProxy())
118
271005
    return;
119
120
400
  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

399
  if (args.Length() == 1 || args[1]->IsTrue()) {
126
    Local<Value> ret[] = {
127
43
      proxy->GetTarget(),
128
43
      proxy->GetHandler()
129
129
    };
130
131
129
    args.GetReturnValue().Set(
132
        Array::New(args.GetIsolate(), ret, arraysize(ret)));
133
  } else {
134
157
    Local<Value> ret = proxy->GetTarget();
135
136
314
    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
4654
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
4654
  CHECK_LT(index, arraysize(methods));
168
4654
  return (env->*methods[index])();
169
}
170
171
177
static void GetHiddenValue(const FunctionCallbackInfo<Value>& args) {
172
177
  Environment* env = Environment::GetCurrent(args);
173
174
177
  CHECK(args[0]->IsObject());
175
177
  CHECK(args[1]->IsUint32());
176
177
354
  Local<Object> obj = args[0].As<Object>();
178
354
  uint32_t index = args[1].As<Uint32>()->Value();
179
177
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
180
  Local<Value> ret;
181
354
  if (obj->GetPrivate(env->context(), private_symbol).ToLocal(&ret))
182
354
    args.GetReturnValue().Set(ret);
183
177
}
184
185
4477
static void SetHiddenValue(const FunctionCallbackInfo<Value>& args) {
186
4477
  Environment* env = Environment::GetCurrent(args);
187
188
4477
  CHECK(args[0]->IsObject());
189
4477
  CHECK(args[1]->IsUint32());
190
191
8954
  Local<Object> obj = args[0].As<Object>();
192
8954
  uint32_t index = args[1].As<Uint32>()->Value();
193
4477
  Local<Private> private_symbol = IndexToPrivateSymbol(env, index);
194
  bool ret;
195

13431
  if (obj->SetPrivate(env->context(), private_symbol, args[2]).To(&ret))
196
8954
    args.GetReturnValue().Set(ret);
197
4477
}
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
1910
  WeakReference(Environment* env, Local<Object> object, Local<Object> target)
213
1910
    : BaseObject(env, object) {
214
1910
    MakeWeak();
215
1910
    target_.Reset(env->isolate(), target);
216
1910
    target_.SetWeak();
217
1910
  }
218
219
1910
  static void New(const FunctionCallbackInfo<Value>& args) {
220
1910
    Environment* env = Environment::GetCurrent(args);
221
1910
    CHECK(args.IsConstructCall());
222
1910
    CHECK(args[0]->IsObject());
223
5730
    new WeakReference(env, args.This(), args[0].As<Object>());
224
1910
  }
225
226
8061
  static void Get(const FunctionCallbackInfo<Value>& args) {
227
8061
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
228
8061
    Isolate* isolate = args.GetIsolate();
229
8061
    if (!weak_ref->target_.IsEmpty())
230
16120
      args.GetReturnValue().Set(weak_ref->target_.Get(isolate));
231
8061
  }
232
233
4029
  static void IncRef(const FunctionCallbackInfo<Value>& args) {
234
4029
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
235
4029
    weak_ref->reference_count_++;
236
4029
    if (weak_ref->target_.IsEmpty()) return;
237
4029
    if (weak_ref->reference_count_ == 1) weak_ref->target_.ClearWeak();
238
  }
239
240
4026
  static void DecRef(const FunctionCallbackInfo<Value>& args) {
241
4026
    WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder());
242
4026
    CHECK_GE(weak_ref->reference_count_, 1);
243
4026
    weak_ref->reference_count_--;
244
4026
    if (weak_ref->target_.IsEmpty()) return;
245
4026
    if (weak_ref->reference_count_ == 0) weak_ref->target_.SetWeak();
246
  }
247
248
4
  SET_MEMORY_INFO_NAME(WeakReference)
249
4
  SET_SELF_SIZE(WeakReference)
250
4
  SET_NO_MEMORY_INFO()
251
252
 private:
253
  Global<Object> target_;
254
  uint64_t reference_count_ = 0;
255
};
256
257
4758
static void GuessHandleType(const FunctionCallbackInfo<Value>& args) {
258
4758
  Environment* env = Environment::GetCurrent(args);
259
  int fd;
260
9516
  if (!args[0]->Int32Value(env->context()).To(&fd)) return;
261
4758
  CHECK_GE(fd, 0);
262
263
4758
  uv_handle_type t = uv_guess_handle(fd);
264
4758
  const char* type = nullptr;
265
266

4758
  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
2410
    case UV_FILE:
277
2410
      type = "FILE";
278
2410
      break;
279
2297
    case UV_NAMED_PIPE:
280
2297
      type = "PIPE";
281
2297
      break;
282
5
    case UV_UNKNOWN_HANDLE:
283
5
      type = "UNKNOWN";
284
5
      break;
285
    default:
286
      ABORT();
287
  }
288
289
9516
  args.GetReturnValue().Set(OneByteString(env->isolate(), type));
290
}
291
292
8
static void IsConstructor(const FunctionCallbackInfo<Value>& args) {
293
8
  CHECK(args[0]->IsFunction());
294

24
  args.GetReturnValue().Set(args[0].As<v8::Function>()->IsConstructor());
295
8
}
296
297
17
static void ToUSVString(const FunctionCallbackInfo<Value>& args) {
298
17
  Environment* env = Environment::GetCurrent(args);
299
17
  CHECK_GE(args.Length(), 2);
300
34
  CHECK(args[0]->IsString());
301
17
  CHECK(args[1]->IsNumber());
302
303
17
  TwoByteValue value(env->isolate(), args[0]);
304
305
17
  int64_t start = args[1]->IntegerValue(env->context()).FromJust();
306
17
  CHECK_GE(start, 0);
307
308
49
  for (size_t i = start; i < value.length(); i++) {
309
32
    char16_t c = value[i];
310
32
    if (!IsUnicodeSurrogate(c)) {
311
13
      continue;
312

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