GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: util.cc Lines: 164 198 82.8 %
Date: 2022-08-16 04:20:39 Branches: 31 54 57.4 %

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
#include "util.h"  // NOLINT(build/include_inline)
23
#include "util-inl.h"
24
25
#include "debug_utils-inl.h"
26
#include "env-inl.h"
27
#include "node_buffer.h"
28
#include "node_errors.h"
29
#include "node_internals.h"
30
#include "string_bytes.h"
31
#include "uv.h"
32
33
#ifdef _WIN32
34
#include <io.h>  // _S_IREAD _S_IWRITE
35
#include <time.h>
36
#ifndef S_IRUSR
37
#define S_IRUSR _S_IREAD
38
#endif  // S_IRUSR
39
#ifndef S_IWUSR
40
#define S_IWUSR _S_IWRITE
41
#endif  // S_IWUSR
42
#else
43
#include <sys/time.h>
44
#include <sys/types.h>
45
#endif
46
47
#include <atomic>
48
#include <cstdio>
49
#include <cstring>
50
#include <iomanip>
51
#include <sstream>
52
53
static std::atomic_int seq = {0};  // Sequence number for diagnostic filenames.
54
55
namespace node {
56
57
using v8::ArrayBufferView;
58
using v8::Isolate;
59
using v8::Local;
60
using v8::String;
61
using v8::Value;
62
63
template <typename T>
64
3237053
static void MakeUtf8String(Isolate* isolate,
65
                           Local<Value> value,
66
                           MaybeStackBuffer<T>* target) {
67
  Local<String> string;
68
6474106
  if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return;
69
70
  size_t storage;
71
6474106
  if (!StringBytes::StorageSize(isolate, string, UTF8).To(&storage)) return;
72
3237053
  storage += 1;
73
3237053
  target->AllocateSufficientStorage(storage);
74
3237053
  const int flags =
75
      String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8;
76
3237053
  const int length =
77
      string->WriteUtf8(isolate, target->out(), storage, nullptr, flags);
78
3237053
  target->SetLengthAndZeroTerminate(length);
79
}
80
81
3015685
Utf8Value::Utf8Value(Isolate* isolate, Local<Value> value) {
82
3015685
  if (value.IsEmpty())
83
1857
    return;
84
85
3013828
  MakeUtf8String(isolate, value, this);
86
}
87
88
89
1197352
TwoByteValue::TwoByteValue(Isolate* isolate, Local<Value> value) {
90
1197352
  if (value.IsEmpty()) {
91
    return;
92
  }
93
94
  Local<String> string;
95
2394704
  if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return;
96
97
  // Allocate enough space to include the null terminator
98
1197352
  const size_t storage = string->Length() + 1;
99
1197352
  AllocateSufficientStorage(storage);
100
101
1197352
  const int flags = String::NO_NULL_TERMINATION;
102
1197352
  const int length = string->Write(isolate, out(), 0, storage, flags);
103
1197352
  SetLengthAndZeroTerminate(length);
104
}
105
106
230762
BufferValue::BufferValue(Isolate* isolate, Local<Value> value) {
107
  // Slightly different take on Utf8Value. If value is a String,
108
  // it will return a Utf8 encoded string. If value is a Buffer,
109
  // it will copy the data out of the Buffer as is.
110
230762
  if (value.IsEmpty()) {
111
    // Dereferencing this object will return nullptr.
112
    Invalidate();
113
    return;
114
  }
115
116
461524
  if (value->IsString()) {
117
223225
    MakeUtf8String(isolate, value, this);
118
7537
  } else if (value->IsArrayBufferView()) {
119
7537
    const size_t len = value.As<ArrayBufferView>()->ByteLength();
120
    // Leave place for the terminating '\0' byte.
121
7537
    AllocateSufficientStorage(len + 1);
122
7537
    value.As<ArrayBufferView>()->CopyContents(out(), len);
123
7537
    SetLengthAndZeroTerminate(len);
124
  } else {
125
    Invalidate();
126
  }
127
}
128
129
void LowMemoryNotification() {
130
  if (per_process::v8_initialized) {
131
    auto isolate = Isolate::TryGetCurrent();
132
    if (isolate != nullptr) {
133
      isolate->LowMemoryNotification();
134
    }
135
  }
136
}
137
138
5554
std::string GetProcessTitle(const char* default_title) {
139
16662
  std::string buf(16, '\0');
140
141
  for (;;) {
142
15069
    const int rc = uv_get_process_title(&buf[0], buf.size());
143
144
15069
    if (rc == 0)
145
5514
      break;
146
147
    // If uv_setup_args() was not called, `uv_get_process_title()` will always
148
    // return `UV_ENOBUFS`, no matter the input size. Guard against a possible
149
    // infinite loop by limiting the buffer size.
150

9555
    if (rc != UV_ENOBUFS || buf.size() >= 1024 * 1024)
151
40
      return default_title;
152
153
9515
    buf.resize(2 * buf.size());
154
9515
  }
155
156
  // Strip excess trailing nul bytes. Using strlen() here is safe,
157
  // uv_get_process_title() always zero-terminates the result.
158
5514
  buf.resize(strlen(&buf[0]));
159
160
5514
  return buf;
161
}
162
163
5392
std::string GetHumanReadableProcessName() {
164
5392
  return SPrintF("%s[%d]", GetProcessTitle("Node.js"), uv_os_getpid());
165
}
166
167
15111
std::vector<std::string> SplitString(const std::string& in,
168
                                     char delim,
169
                                     bool skipEmpty) {
170
15111
  std::vector<std::string> out;
171
15111
  if (in.empty())
172
2
    return out;
173
30218
  std::istringstream in_stream(in);
174
45830
  while (in_stream.good()) {
175
30721
    std::string item;
176
30721
    std::getline(in_stream, item, delim);
177

30721
    if (item.empty() && skipEmpty) continue;
178
30721
    out.emplace_back(std::move(item));
179
  }
180
15109
  return out;
181
}
182
183
void ThrowErrStringTooLong(Isolate* isolate) {
184
  isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
185
}
186
187
12146
double GetCurrentTimeInMicroseconds() {
188
12146
  constexpr double kMicrosecondsPerSecond = 1e6;
189
  uv_timeval64_t tv;
190
12146
  CHECK_EQ(0, uv_gettimeofday(&tv));
191
12146
  return kMicrosecondsPerSecond * tv.tv_sec + tv.tv_usec;
192
}
193
194
6069
int WriteFileSync(const char* path, uv_buf_t buf) {
195
  uv_fs_t req;
196
6069
  int fd = uv_fs_open(nullptr,
197
                      &req,
198
                      path,
199
                      O_WRONLY | O_CREAT | O_TRUNC,
200
                      S_IWUSR | S_IRUSR,
201
                      nullptr);
202
6069
  uv_fs_req_cleanup(&req);
203
6069
  if (fd < 0) {
204
2
    return fd;
205
  }
206
207
6067
  int err = uv_fs_write(nullptr, &req, fd, &buf, 1, 0, nullptr);
208
6067
  uv_fs_req_cleanup(&req);
209
6067
  if (err < 0) {
210
    return err;
211
  }
212
213
6067
  err = uv_fs_close(nullptr, &req, fd, nullptr);
214
6067
  uv_fs_req_cleanup(&req);
215
6067
  return err;
216
}
217
218
6069
int WriteFileSync(v8::Isolate* isolate,
219
                  const char* path,
220
                  v8::Local<v8::String> string) {
221
12138
  node::Utf8Value utf8(isolate, string);
222
6069
  uv_buf_t buf = uv_buf_init(utf8.out(), utf8.length());
223
6069
  return WriteFileSync(path, buf);
224
}
225
226
int ReadFileSync(std::string* result, const char* path) {
227
  uv_fs_t req;
228
  auto defer_req_cleanup = OnScopeLeave([&req]() {
229
    uv_fs_req_cleanup(&req);
230
  });
231
232
  uv_file file = uv_fs_open(nullptr, &req, path, O_RDONLY, 0, nullptr);
233
  if (req.result < 0) {
234
    // req will be cleaned up by scope leave.
235
    return req.result;
236
  }
237
  uv_fs_req_cleanup(&req);
238
239
  auto defer_close = OnScopeLeave([file]() {
240
    uv_fs_t close_req;
241
    CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr));
242
    uv_fs_req_cleanup(&close_req);
243
  });
244
245
  *result = std::string("");
246
  char buffer[4096];
247
  uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
248
249
  while (true) {
250
    const int r =
251
        uv_fs_read(nullptr, &req, file, &buf, 1, result->length(), nullptr);
252
    if (req.result < 0) {
253
      // req will be cleaned up by scope leave.
254
      return req.result;
255
    }
256
    uv_fs_req_cleanup(&req);
257
    if (r <= 0) {
258
      break;
259
    }
260
    result->append(buf.base, r);
261
  }
262
  return 0;
263
}
264
265
59
void DiagnosticFilename::LocalTime(TIME_TYPE* tm_struct) {
266
#ifdef _WIN32
267
  GetLocalTime(tm_struct);
268
#else  // UNIX, OSX
269
  struct timeval time_val;
270
59
  gettimeofday(&time_val, nullptr);
271
59
  localtime_r(&time_val.tv_sec, tm_struct);
272
#endif
273
59
}
274
275
// Defined in node_internals.h
276
34
std::string DiagnosticFilename::MakeFilename(
277
    uint64_t thread_id,
278
    const char* prefix,
279
    const char* ext) {
280
68
  std::ostringstream oss;
281
  TIME_TYPE tm_struct;
282
34
  LocalTime(&tm_struct);
283
34
  oss << prefix;
284
#ifdef _WIN32
285
  oss << "." << std::setfill('0') << std::setw(4) << tm_struct.wYear;
286
  oss << std::setfill('0') << std::setw(2) << tm_struct.wMonth;
287
  oss << std::setfill('0') << std::setw(2) << tm_struct.wDay;
288
  oss << "." << std::setfill('0') << std::setw(2) << tm_struct.wHour;
289
  oss << std::setfill('0') << std::setw(2) << tm_struct.wMinute;
290
  oss << std::setfill('0') << std::setw(2) << tm_struct.wSecond;
291
#else  // UNIX, OSX
292
  oss << "."
293
            << std::setfill('0')
294
34
            << std::setw(4)
295
34
            << tm_struct.tm_year + 1900;
296
  oss << std::setfill('0')
297
34
            << std::setw(2)
298
34
            << tm_struct.tm_mon + 1;
299
  oss << std::setfill('0')
300
34
            << std::setw(2)
301
34
            << tm_struct.tm_mday;
302
  oss << "."
303
            << std::setfill('0')
304
34
            << std::setw(2)
305
34
            << tm_struct.tm_hour;
306
  oss << std::setfill('0')
307
34
            << std::setw(2)
308
34
            << tm_struct.tm_min;
309
  oss << std::setfill('0')
310
34
            << std::setw(2)
311
34
            << tm_struct.tm_sec;
312
#endif
313
34
  oss << "." << uv_os_getpid();
314
34
  oss << "." << thread_id;
315
34
  oss << "." << std::setfill('0') << std::setw(3) << ++seq;
316
34
  oss << "." << ext;
317
34
  return oss.str();
318
}
319
320
1119321
Local<v8::FunctionTemplate> NewFunctionTemplate(
321
    v8::Isolate* isolate,
322
    v8::FunctionCallback callback,
323
    Local<v8::Signature> signature,
324
    v8::ConstructorBehavior behavior,
325
    v8::SideEffectType side_effect_type,
326
    const v8::CFunction* c_function) {
327
  return v8::FunctionTemplate::New(isolate,
328
                                   callback,
329
                                   Local<v8::Value>(),
330
                                   signature,
331
                                   0,
332
                                   behavior,
333
                                   side_effect_type,
334
1119321
                                   c_function);
335
}
336
337
271177
void SetMethod(Local<v8::Context> context,
338
               Local<v8::Object> that,
339
               const char* name,
340
               v8::FunctionCallback callback) {
341
271177
  Isolate* isolate = context->GetIsolate();
342
  Local<v8::Function> function =
343
271177
      NewFunctionTemplate(isolate,
344
                          callback,
345
                          Local<v8::Signature>(),
346
                          v8::ConstructorBehavior::kThrow,
347
271177
                          v8::SideEffectType::kHasSideEffect)
348
271177
          ->GetFunction(context)
349
271177
          .ToLocalChecked();
350
  // kInternalized strings are created in the old space.
351
271177
  const v8::NewStringType type = v8::NewStringType::kInternalized;
352
  Local<v8::String> name_string =
353
542354
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
354
542354
  that->Set(context, name_string, function).Check();
355
271177
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
356
271177
}
357
358
1540
void SetFastMethod(Local<v8::Context> context,
359
                   Local<v8::Object> that,
360
                   const char* name,
361
                   v8::FunctionCallback slow_callback,
362
                   const v8::CFunction* c_function) {
363
1540
  Isolate* isolate = context->GetIsolate();
364
  Local<v8::Function> function =
365
1540
      NewFunctionTemplate(isolate,
366
                          slow_callback,
367
                          Local<v8::Signature>(),
368
                          v8::ConstructorBehavior::kThrow,
369
                          v8::SideEffectType::kHasNoSideEffect,
370
1540
                          c_function)
371
1540
          ->GetFunction(context)
372
1540
          .ToLocalChecked();
373
1540
  const v8::NewStringType type = v8::NewStringType::kInternalized;
374
  Local<v8::String> name_string =
375
3080
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
376
1540
  that->Set(context, name_string, function).Check();
377
1540
}
378
379
69156
void SetMethodNoSideEffect(Local<v8::Context> context,
380
                           Local<v8::Object> that,
381
                           const char* name,
382
                           v8::FunctionCallback callback) {
383
69156
  Isolate* isolate = context->GetIsolate();
384
  Local<v8::Function> function =
385
69156
      NewFunctionTemplate(isolate,
386
                          callback,
387
                          Local<v8::Signature>(),
388
                          v8::ConstructorBehavior::kThrow,
389
69156
                          v8::SideEffectType::kHasNoSideEffect)
390
69156
          ->GetFunction(context)
391
69156
          .ToLocalChecked();
392
  // kInternalized strings are created in the old space.
393
69156
  const v8::NewStringType type = v8::NewStringType::kInternalized;
394
  Local<v8::String> name_string =
395
138312
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
396
138312
  that->Set(context, name_string, function).Check();
397
69156
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
398
69156
}
399
400
542791
void SetProtoMethod(v8::Isolate* isolate,
401
                    Local<v8::FunctionTemplate> that,
402
                    const char* name,
403
                    v8::FunctionCallback callback) {
404
542791
  Local<v8::Signature> signature = v8::Signature::New(isolate, that);
405
  Local<v8::FunctionTemplate> t =
406
      NewFunctionTemplate(isolate,
407
                          callback,
408
                          signature,
409
                          v8::ConstructorBehavior::kThrow,
410
542791
                          v8::SideEffectType::kHasSideEffect);
411
  // kInternalized strings are created in the old space.
412
542791
  const v8::NewStringType type = v8::NewStringType::kInternalized;
413
  Local<v8::String> name_string =
414
1085582
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
415
1085582
  that->PrototypeTemplate()->Set(name_string, t);
416
542791
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
417
542791
}
418
419
75600
void SetProtoMethodNoSideEffect(v8::Isolate* isolate,
420
                                Local<v8::FunctionTemplate> that,
421
                                const char* name,
422
                                v8::FunctionCallback callback) {
423
75600
  Local<v8::Signature> signature = v8::Signature::New(isolate, that);
424
  Local<v8::FunctionTemplate> t =
425
      NewFunctionTemplate(isolate,
426
                          callback,
427
                          signature,
428
                          v8::ConstructorBehavior::kThrow,
429
75600
                          v8::SideEffectType::kHasNoSideEffect);
430
  // kInternalized strings are created in the old space.
431
75600
  const v8::NewStringType type = v8::NewStringType::kInternalized;
432
  Local<v8::String> name_string =
433
151200
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
434
151200
  that->PrototypeTemplate()->Set(name_string, t);
435
75600
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
436
75600
}
437
438
33
void SetInstanceMethod(v8::Isolate* isolate,
439
                       Local<v8::FunctionTemplate> that,
440
                       const char* name,
441
                       v8::FunctionCallback callback) {
442
33
  Local<v8::Signature> signature = v8::Signature::New(isolate, that);
443
  Local<v8::FunctionTemplate> t =
444
      NewFunctionTemplate(isolate,
445
                          callback,
446
                          signature,
447
                          v8::ConstructorBehavior::kThrow,
448
33
                          v8::SideEffectType::kHasSideEffect);
449
  // kInternalized strings are created in the old space.
450
33
  const v8::NewStringType type = v8::NewStringType::kInternalized;
451
  Local<v8::String> name_string =
452
66
      v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
453
66
  that->InstanceTemplate()->Set(name_string, t);
454
33
  t->SetClassName(name_string);
455
33
}
456
457
102333
void SetConstructorFunction(Local<v8::Context> context,
458
                            Local<v8::Object> that,
459
                            const char* name,
460
                            Local<v8::FunctionTemplate> tmpl,
461
                            SetConstructorFunctionFlag flag) {
462
102333
  Isolate* isolate = context->GetIsolate();
463
102333
  SetConstructorFunction(
464
      context, that, OneByteString(isolate, name), tmpl, flag);
465
102333
}
466
467
106183
void SetConstructorFunction(Local<v8::Context> context,
468
                            Local<v8::Object> that,
469
                            Local<v8::String> name,
470
                            Local<v8::FunctionTemplate> tmpl,
471
                            SetConstructorFunctionFlag flag) {
472
106183
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
473
93283
    tmpl->SetClassName(name);
474
212366
  that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check();
475
106183
}
476
477
}  // namespace node