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 "node_util.h"
31 #include "string_bytes.h"
32 #include "uv.h"
33
34 #ifdef _WIN32
35 #include <io.h> // _S_IREAD _S_IWRITE
36 #include <time.h>
37 #ifndef S_IRUSR
38 #define S_IRUSR _S_IREAD
39 #endif // S_IRUSR
40 #ifndef S_IWUSR
41 #define S_IWUSR _S_IWRITE
42 #endif // S_IWUSR
43 #else
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #endif
47
48 #include <atomic>
49 #include <cstdio>
50 #include <cstring>
51 #include <iomanip>
52 #include <sstream>
53
54 static std::atomic_int seq = {0}; // Sequence number for diagnostic filenames.
55
56 namespace node {
57
58 using v8::ArrayBufferView;
59 using v8::Isolate;
60 using v8::Local;
61 using v8::String;
62 using v8::Value;
63
64 template <typename T>
MakeUtf8String(Isolate * isolate,Local<Value> value,MaybeStackBuffer<T> * target)65 static void MakeUtf8String(Isolate* isolate,
66 Local<Value> value,
67 MaybeStackBuffer<T>* target) {
68 Local<String> string;
69 if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return;
70
71 size_t storage;
72 if (!StringBytes::StorageSize(isolate, string, UTF8).To(&storage)) return;
73 storage += 1;
74 target->AllocateSufficientStorage(storage);
75 const int flags =
76 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8;
77 const int length =
78 string->WriteUtf8(isolate, target->out(), storage, nullptr, flags);
79 target->SetLengthAndZeroTerminate(length);
80 }
81
Utf8Value(Isolate * isolate,Local<Value> value)82 Utf8Value::Utf8Value(Isolate* isolate, Local<Value> value) {
83 if (value.IsEmpty())
84 return;
85
86 MakeUtf8String(isolate, value, this);
87 }
88
89
TwoByteValue(Isolate * isolate,Local<Value> value)90 TwoByteValue::TwoByteValue(Isolate* isolate, Local<Value> value) {
91 if (value.IsEmpty()) {
92 return;
93 }
94
95 Local<String> string;
96 if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return;
97
98 // Allocate enough space to include the null terminator
99 const size_t storage = string->Length() + 1;
100 AllocateSufficientStorage(storage);
101
102 const int flags = String::NO_NULL_TERMINATION;
103 const int length = string->Write(isolate, out(), 0, storage, flags);
104 SetLengthAndZeroTerminate(length);
105 }
106
BufferValue(Isolate * isolate,Local<Value> value)107 BufferValue::BufferValue(Isolate* isolate, Local<Value> value) {
108 // Slightly different take on Utf8Value. If value is a String,
109 // it will return a Utf8 encoded string. If value is a Buffer,
110 // it will copy the data out of the Buffer as is.
111 if (value.IsEmpty()) {
112 // Dereferencing this object will return nullptr.
113 Invalidate();
114 return;
115 }
116
117 if (value->IsString()) {
118 MakeUtf8String(isolate, value, this);
119 } else if (value->IsArrayBufferView()) {
120 const size_t len = value.As<ArrayBufferView>()->ByteLength();
121 // Leave place for the terminating '\0' byte.
122 AllocateSufficientStorage(len + 1);
123 value.As<ArrayBufferView>()->CopyContents(out(), len);
124 SetLengthAndZeroTerminate(len);
125 } else {
126 Invalidate();
127 }
128 }
129
LowMemoryNotification()130 void LowMemoryNotification() {
131 if (per_process::v8_initialized) {
132 auto isolate = Isolate::TryGetCurrent();
133 if (isolate != nullptr) {
134 isolate->LowMemoryNotification();
135 }
136 }
137 }
138
GetProcessTitle(const char * default_title)139 std::string GetProcessTitle(const char* default_title) {
140 std::string buf(16, '\0');
141
142 for (;;) {
143 const int rc = uv_get_process_title(buf.data(), buf.size());
144
145 if (rc == 0)
146 break;
147
148 // If uv_setup_args() was not called, `uv_get_process_title()` will always
149 // return `UV_ENOBUFS`, no matter the input size. Guard against a possible
150 // infinite loop by limiting the buffer size.
151 if (rc != UV_ENOBUFS || buf.size() >= 1024 * 1024)
152 return default_title;
153
154 buf.resize(2 * buf.size());
155 }
156
157 // Strip excess trailing nul bytes. Using strlen() here is safe,
158 // uv_get_process_title() always zero-terminates the result.
159 buf.resize(strlen(buf.data()));
160
161 return buf;
162 }
163
GetHumanReadableProcessName()164 std::string GetHumanReadableProcessName() {
165 return SPrintF("%s[%d]", GetProcessTitle("Node.js"), uv_os_getpid());
166 }
167
SplitString(const std::string_view in,const std::string_view delim)168 std::vector<std::string_view> SplitString(const std::string_view in,
169 const std::string_view delim) {
170 std::vector<std::string_view> out;
171
172 for (auto first = in.data(), second = in.data(), last = first + in.size();
173 second != last && first != last;
174 first = second + 1) {
175 second =
176 std::find_first_of(first, last, std::cbegin(delim), std::cend(delim));
177
178 if (first != second) {
179 out.emplace_back(first, second - first);
180 }
181 }
182
183 return out;
184 }
185
ThrowErrStringTooLong(Isolate * isolate)186 void ThrowErrStringTooLong(Isolate* isolate) {
187 isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
188 }
189
GetCurrentTimeInMicroseconds()190 double GetCurrentTimeInMicroseconds() {
191 constexpr double kMicrosecondsPerSecond = 1e6;
192 uv_timeval64_t tv;
193 CHECK_EQ(0, uv_gettimeofday(&tv));
194 return kMicrosecondsPerSecond * tv.tv_sec + tv.tv_usec;
195 }
196
WriteFileSync(const char * path,uv_buf_t buf)197 int WriteFileSync(const char* path, uv_buf_t buf) {
198 uv_fs_t req;
199 int fd = uv_fs_open(nullptr,
200 &req,
201 path,
202 O_WRONLY | O_CREAT | O_TRUNC,
203 S_IWUSR | S_IRUSR,
204 nullptr);
205 uv_fs_req_cleanup(&req);
206 if (fd < 0) {
207 return fd;
208 }
209
210 int err = uv_fs_write(nullptr, &req, fd, &buf, 1, 0, nullptr);
211 uv_fs_req_cleanup(&req);
212 if (err < 0) {
213 return err;
214 }
215
216 err = uv_fs_close(nullptr, &req, fd, nullptr);
217 uv_fs_req_cleanup(&req);
218 return err;
219 }
220
WriteFileSync(v8::Isolate * isolate,const char * path,v8::Local<v8::String> string)221 int WriteFileSync(v8::Isolate* isolate,
222 const char* path,
223 v8::Local<v8::String> string) {
224 node::Utf8Value utf8(isolate, string);
225 uv_buf_t buf = uv_buf_init(utf8.out(), utf8.length());
226 return WriteFileSync(path, buf);
227 }
228
ReadFileSync(std::string * result,const char * path)229 int ReadFileSync(std::string* result, const char* path) {
230 uv_fs_t req;
231 auto defer_req_cleanup = OnScopeLeave([&req]() {
232 uv_fs_req_cleanup(&req);
233 });
234
235 uv_file file = uv_fs_open(nullptr, &req, path, O_RDONLY, 0, nullptr);
236 if (req.result < 0) {
237 // req will be cleaned up by scope leave.
238 return req.result;
239 }
240 uv_fs_req_cleanup(&req);
241
242 auto defer_close = OnScopeLeave([file]() {
243 uv_fs_t close_req;
244 CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr));
245 uv_fs_req_cleanup(&close_req);
246 });
247
248 *result = std::string("");
249 char buffer[4096];
250 uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
251
252 while (true) {
253 const int r =
254 uv_fs_read(nullptr, &req, file, &buf, 1, result->length(), nullptr);
255 if (req.result < 0) {
256 // req will be cleaned up by scope leave.
257 return req.result;
258 }
259 uv_fs_req_cleanup(&req);
260 if (r <= 0) {
261 break;
262 }
263 result->append(buf.base, r);
264 }
265 return 0;
266 }
267
LocalTime(TIME_TYPE * tm_struct)268 void DiagnosticFilename::LocalTime(TIME_TYPE* tm_struct) {
269 #ifdef _WIN32
270 GetLocalTime(tm_struct);
271 #else // UNIX, OSX
272 struct timeval time_val;
273 gettimeofday(&time_val, nullptr);
274 localtime_r(&time_val.tv_sec, tm_struct);
275 #endif
276 }
277
278 // Defined in node_internals.h
MakeFilename(uint64_t thread_id,const char * prefix,const char * ext)279 std::string DiagnosticFilename::MakeFilename(
280 uint64_t thread_id,
281 const char* prefix,
282 const char* ext) {
283 std::ostringstream oss;
284 TIME_TYPE tm_struct;
285 LocalTime(&tm_struct);
286 oss << prefix;
287 #ifdef _WIN32
288 oss << "." << std::setfill('0') << std::setw(4) << tm_struct.wYear;
289 oss << std::setfill('0') << std::setw(2) << tm_struct.wMonth;
290 oss << std::setfill('0') << std::setw(2) << tm_struct.wDay;
291 oss << "." << std::setfill('0') << std::setw(2) << tm_struct.wHour;
292 oss << std::setfill('0') << std::setw(2) << tm_struct.wMinute;
293 oss << std::setfill('0') << std::setw(2) << tm_struct.wSecond;
294 #else // UNIX, OSX
295 oss << "."
296 << std::setfill('0')
297 << std::setw(4)
298 << tm_struct.tm_year + 1900;
299 oss << std::setfill('0')
300 << std::setw(2)
301 << tm_struct.tm_mon + 1;
302 oss << std::setfill('0')
303 << std::setw(2)
304 << tm_struct.tm_mday;
305 oss << "."
306 << std::setfill('0')
307 << std::setw(2)
308 << tm_struct.tm_hour;
309 oss << std::setfill('0')
310 << std::setw(2)
311 << tm_struct.tm_min;
312 oss << std::setfill('0')
313 << std::setw(2)
314 << tm_struct.tm_sec;
315 #endif
316 oss << "." << uv_os_getpid();
317 oss << "." << thread_id;
318 oss << "." << std::setfill('0') << std::setw(3) << ++seq;
319 oss << "." << ext;
320 return oss.str();
321 }
322
NewFunctionTemplate(v8::Isolate * isolate,v8::FunctionCallback callback,Local<v8::Signature> signature,v8::ConstructorBehavior behavior,v8::SideEffectType side_effect_type,const v8::CFunction * c_function)323 Local<v8::FunctionTemplate> NewFunctionTemplate(
324 v8::Isolate* isolate,
325 v8::FunctionCallback callback,
326 Local<v8::Signature> signature,
327 v8::ConstructorBehavior behavior,
328 v8::SideEffectType side_effect_type,
329 const v8::CFunction* c_function) {
330 return v8::FunctionTemplate::New(isolate,
331 callback,
332 Local<v8::Value>(),
333 signature,
334 0,
335 behavior,
336 side_effect_type,
337 c_function);
338 }
339
SetMethod(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback callback)340 void SetMethod(Local<v8::Context> context,
341 Local<v8::Object> that,
342 const char* name,
343 v8::FunctionCallback callback) {
344 Isolate* isolate = context->GetIsolate();
345 Local<v8::Function> function =
346 NewFunctionTemplate(isolate,
347 callback,
348 Local<v8::Signature>(),
349 v8::ConstructorBehavior::kThrow,
350 v8::SideEffectType::kHasSideEffect)
351 ->GetFunction(context)
352 .ToLocalChecked();
353 // kInternalized strings are created in the old space.
354 const v8::NewStringType type = v8::NewStringType::kInternalized;
355 Local<v8::String> name_string =
356 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
357 that->Set(context, name_string, function).Check();
358 function->SetName(name_string); // NODE_SET_METHOD() compatibility.
359 }
360
SetMethod(v8::Isolate * isolate,v8::Local<v8::Template> that,const char * name,v8::FunctionCallback callback)361 void SetMethod(v8::Isolate* isolate,
362 v8::Local<v8::Template> that,
363 const char* name,
364 v8::FunctionCallback callback) {
365 Local<v8::FunctionTemplate> t =
366 NewFunctionTemplate(isolate,
367 callback,
368 Local<v8::Signature>(),
369 v8::ConstructorBehavior::kThrow,
370 v8::SideEffectType::kHasSideEffect);
371 // kInternalized strings are created in the old space.
372 const v8::NewStringType type = v8::NewStringType::kInternalized;
373 Local<v8::String> name_string =
374 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
375 that->Set(name_string, t);
376 }
377
SetFastMethod(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback slow_callback,const v8::CFunction * c_function)378 void SetFastMethod(Local<v8::Context> context,
379 Local<v8::Object> that,
380 const char* name,
381 v8::FunctionCallback slow_callback,
382 const v8::CFunction* c_function) {
383 Isolate* isolate = context->GetIsolate();
384 Local<v8::Function> function =
385 NewFunctionTemplate(isolate,
386 slow_callback,
387 Local<v8::Signature>(),
388 v8::ConstructorBehavior::kThrow,
389 v8::SideEffectType::kHasSideEffect,
390 c_function)
391 ->GetFunction(context)
392 .ToLocalChecked();
393 const v8::NewStringType type = v8::NewStringType::kInternalized;
394 Local<v8::String> name_string =
395 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
396 that->Set(context, name_string, function).Check();
397 }
398
SetFastMethodNoSideEffect(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback slow_callback,const v8::CFunction * c_function)399 void SetFastMethodNoSideEffect(Local<v8::Context> context,
400 Local<v8::Object> that,
401 const char* name,
402 v8::FunctionCallback slow_callback,
403 const v8::CFunction* c_function) {
404 Isolate* isolate = context->GetIsolate();
405 Local<v8::Function> function =
406 NewFunctionTemplate(isolate,
407 slow_callback,
408 Local<v8::Signature>(),
409 v8::ConstructorBehavior::kThrow,
410 v8::SideEffectType::kHasNoSideEffect,
411 c_function)
412 ->GetFunction(context)
413 .ToLocalChecked();
414 const v8::NewStringType type = v8::NewStringType::kInternalized;
415 Local<v8::String> name_string =
416 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
417 that->Set(context, name_string, function).Check();
418 }
419
SetMethodNoSideEffect(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback callback)420 void SetMethodNoSideEffect(Local<v8::Context> context,
421 Local<v8::Object> that,
422 const char* name,
423 v8::FunctionCallback callback) {
424 Isolate* isolate = context->GetIsolate();
425 Local<v8::Function> function =
426 NewFunctionTemplate(isolate,
427 callback,
428 Local<v8::Signature>(),
429 v8::ConstructorBehavior::kThrow,
430 v8::SideEffectType::kHasNoSideEffect)
431 ->GetFunction(context)
432 .ToLocalChecked();
433 // kInternalized strings are created in the old space.
434 const v8::NewStringType type = v8::NewStringType::kInternalized;
435 Local<v8::String> name_string =
436 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
437 that->Set(context, name_string, function).Check();
438 function->SetName(name_string); // NODE_SET_METHOD() compatibility.
439 }
440
SetProtoMethod(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)441 void SetProtoMethod(v8::Isolate* isolate,
442 Local<v8::FunctionTemplate> that,
443 const char* name,
444 v8::FunctionCallback callback) {
445 Local<v8::Signature> signature = v8::Signature::New(isolate, that);
446 Local<v8::FunctionTemplate> t =
447 NewFunctionTemplate(isolate,
448 callback,
449 signature,
450 v8::ConstructorBehavior::kThrow,
451 v8::SideEffectType::kHasSideEffect);
452 // kInternalized strings are created in the old space.
453 const v8::NewStringType type = v8::NewStringType::kInternalized;
454 Local<v8::String> name_string =
455 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
456 that->PrototypeTemplate()->Set(name_string, t);
457 t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility.
458 }
459
SetProtoMethodNoSideEffect(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)460 void SetProtoMethodNoSideEffect(v8::Isolate* isolate,
461 Local<v8::FunctionTemplate> that,
462 const char* name,
463 v8::FunctionCallback callback) {
464 Local<v8::Signature> signature = v8::Signature::New(isolate, that);
465 Local<v8::FunctionTemplate> t =
466 NewFunctionTemplate(isolate,
467 callback,
468 signature,
469 v8::ConstructorBehavior::kThrow,
470 v8::SideEffectType::kHasNoSideEffect);
471 // kInternalized strings are created in the old space.
472 const v8::NewStringType type = v8::NewStringType::kInternalized;
473 Local<v8::String> name_string =
474 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
475 that->PrototypeTemplate()->Set(name_string, t);
476 t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility.
477 }
478
SetInstanceMethod(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)479 void SetInstanceMethod(v8::Isolate* isolate,
480 Local<v8::FunctionTemplate> that,
481 const char* name,
482 v8::FunctionCallback callback) {
483 Local<v8::Signature> signature = v8::Signature::New(isolate, that);
484 Local<v8::FunctionTemplate> t =
485 NewFunctionTemplate(isolate,
486 callback,
487 signature,
488 v8::ConstructorBehavior::kThrow,
489 v8::SideEffectType::kHasSideEffect);
490 // kInternalized strings are created in the old space.
491 const v8::NewStringType type = v8::NewStringType::kInternalized;
492 Local<v8::String> name_string =
493 v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
494 that->InstanceTemplate()->Set(name_string, t);
495 t->SetClassName(name_string);
496 }
497
SetConstructorFunction(Local<v8::Context> context,Local<v8::Object> that,const char * name,Local<v8::FunctionTemplate> tmpl,SetConstructorFunctionFlag flag)498 void SetConstructorFunction(Local<v8::Context> context,
499 Local<v8::Object> that,
500 const char* name,
501 Local<v8::FunctionTemplate> tmpl,
502 SetConstructorFunctionFlag flag) {
503 Isolate* isolate = context->GetIsolate();
504 SetConstructorFunction(
505 context, that, OneByteString(isolate, name), tmpl, flag);
506 }
507
SetConstructorFunction(Local<v8::Context> context,Local<v8::Object> that,Local<v8::String> name,Local<v8::FunctionTemplate> tmpl,SetConstructorFunctionFlag flag)508 void SetConstructorFunction(Local<v8::Context> context,
509 Local<v8::Object> that,
510 Local<v8::String> name,
511 Local<v8::FunctionTemplate> tmpl,
512 SetConstructorFunctionFlag flag) {
513 if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
514 tmpl->SetClassName(name);
515 that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check();
516 }
517
518 namespace {
519
520 class NonOwningExternalOneByteResource
521 : public v8::String::ExternalOneByteStringResource {
522 public:
NonOwningExternalOneByteResource(const UnionBytes & source)523 explicit NonOwningExternalOneByteResource(const UnionBytes& source)
524 : source_(source) {}
525 ~NonOwningExternalOneByteResource() override = default;
526
data() const527 const char* data() const override {
528 return reinterpret_cast<const char*>(source_.one_bytes_data());
529 }
length() const530 size_t length() const override { return source_.length(); }
531
532 NonOwningExternalOneByteResource(const NonOwningExternalOneByteResource&) =
533 delete;
534 NonOwningExternalOneByteResource& operator=(
535 const NonOwningExternalOneByteResource&) = delete;
536
537 private:
538 const UnionBytes source_;
539 };
540
541 class NonOwningExternalTwoByteResource
542 : public v8::String::ExternalStringResource {
543 public:
NonOwningExternalTwoByteResource(const UnionBytes & source)544 explicit NonOwningExternalTwoByteResource(const UnionBytes& source)
545 : source_(source) {}
546 ~NonOwningExternalTwoByteResource() override = default;
547
data() const548 const uint16_t* data() const override { return source_.two_bytes_data(); }
length() const549 size_t length() const override { return source_.length(); }
550
551 NonOwningExternalTwoByteResource(const NonOwningExternalTwoByteResource&) =
552 delete;
553 NonOwningExternalTwoByteResource& operator=(
554 const NonOwningExternalTwoByteResource&) = delete;
555
556 private:
557 const UnionBytes source_;
558 };
559
560 } // anonymous namespace
561
ToStringChecked(Isolate * isolate) const562 Local<String> UnionBytes::ToStringChecked(Isolate* isolate) const {
563 if (UNLIKELY(length() == 0)) {
564 // V8 requires non-null data pointers for empty external strings,
565 // but we don't guarantee that. Solve this by not creating an
566 // external string at all in that case.
567 return String::Empty(isolate);
568 }
569 if (is_one_byte()) {
570 NonOwningExternalOneByteResource* source =
571 new NonOwningExternalOneByteResource(*this);
572 return String::NewExternalOneByte(isolate, source).ToLocalChecked();
573 } else {
574 NonOwningExternalTwoByteResource* source =
575 new NonOwningExternalTwoByteResource(*this);
576 return String::NewExternalTwoByte(isolate, source).ToLocalChecked();
577 }
578 }
579
580 } // namespace node
581