• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
SetFastMethod(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback slow_callback,const v8::CFunction * c_function)361 void SetFastMethod(Local<v8::Context> context,
362                    Local<v8::Object> that,
363                    const char* name,
364                    v8::FunctionCallback slow_callback,
365                    const v8::CFunction* c_function) {
366   Isolate* isolate = context->GetIsolate();
367   Local<v8::Function> function =
368       NewFunctionTemplate(isolate,
369                           slow_callback,
370                           Local<v8::Signature>(),
371                           v8::ConstructorBehavior::kThrow,
372                           v8::SideEffectType::kHasSideEffect,
373                           c_function)
374           ->GetFunction(context)
375           .ToLocalChecked();
376   const v8::NewStringType type = v8::NewStringType::kInternalized;
377   Local<v8::String> name_string =
378       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
379   that->Set(context, name_string, function).Check();
380 }
381 
SetFastMethodNoSideEffect(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback slow_callback,const v8::CFunction * c_function)382 void SetFastMethodNoSideEffect(Local<v8::Context> context,
383                                Local<v8::Object> that,
384                                const char* name,
385                                v8::FunctionCallback slow_callback,
386                                const v8::CFunction* c_function) {
387   Isolate* isolate = context->GetIsolate();
388   Local<v8::Function> function =
389       NewFunctionTemplate(isolate,
390                           slow_callback,
391                           Local<v8::Signature>(),
392                           v8::ConstructorBehavior::kThrow,
393                           v8::SideEffectType::kHasNoSideEffect,
394                           c_function)
395           ->GetFunction(context)
396           .ToLocalChecked();
397   const v8::NewStringType type = v8::NewStringType::kInternalized;
398   Local<v8::String> name_string =
399       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
400   that->Set(context, name_string, function).Check();
401 }
402 
SetMethodNoSideEffect(Local<v8::Context> context,Local<v8::Object> that,const char * name,v8::FunctionCallback callback)403 void SetMethodNoSideEffect(Local<v8::Context> context,
404                            Local<v8::Object> that,
405                            const char* name,
406                            v8::FunctionCallback callback) {
407   Isolate* isolate = context->GetIsolate();
408   Local<v8::Function> function =
409       NewFunctionTemplate(isolate,
410                           callback,
411                           Local<v8::Signature>(),
412                           v8::ConstructorBehavior::kThrow,
413                           v8::SideEffectType::kHasNoSideEffect)
414           ->GetFunction(context)
415           .ToLocalChecked();
416   // kInternalized strings are created in the old space.
417   const v8::NewStringType type = v8::NewStringType::kInternalized;
418   Local<v8::String> name_string =
419       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
420   that->Set(context, name_string, function).Check();
421   function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
422 }
423 
SetProtoMethod(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)424 void SetProtoMethod(v8::Isolate* isolate,
425                     Local<v8::FunctionTemplate> that,
426                     const char* name,
427                     v8::FunctionCallback callback) {
428   Local<v8::Signature> signature = v8::Signature::New(isolate, that);
429   Local<v8::FunctionTemplate> t =
430       NewFunctionTemplate(isolate,
431                           callback,
432                           signature,
433                           v8::ConstructorBehavior::kThrow,
434                           v8::SideEffectType::kHasSideEffect);
435   // kInternalized strings are created in the old space.
436   const v8::NewStringType type = v8::NewStringType::kInternalized;
437   Local<v8::String> name_string =
438       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
439   that->PrototypeTemplate()->Set(name_string, t);
440   t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
441 }
442 
SetProtoMethodNoSideEffect(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)443 void SetProtoMethodNoSideEffect(v8::Isolate* isolate,
444                                 Local<v8::FunctionTemplate> that,
445                                 const char* name,
446                                 v8::FunctionCallback callback) {
447   Local<v8::Signature> signature = v8::Signature::New(isolate, that);
448   Local<v8::FunctionTemplate> t =
449       NewFunctionTemplate(isolate,
450                           callback,
451                           signature,
452                           v8::ConstructorBehavior::kThrow,
453                           v8::SideEffectType::kHasNoSideEffect);
454   // kInternalized strings are created in the old space.
455   const v8::NewStringType type = v8::NewStringType::kInternalized;
456   Local<v8::String> name_string =
457       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
458   that->PrototypeTemplate()->Set(name_string, t);
459   t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
460 }
461 
SetInstanceMethod(v8::Isolate * isolate,Local<v8::FunctionTemplate> that,const char * name,v8::FunctionCallback callback)462 void SetInstanceMethod(v8::Isolate* isolate,
463                        Local<v8::FunctionTemplate> that,
464                        const char* name,
465                        v8::FunctionCallback callback) {
466   Local<v8::Signature> signature = v8::Signature::New(isolate, that);
467   Local<v8::FunctionTemplate> t =
468       NewFunctionTemplate(isolate,
469                           callback,
470                           signature,
471                           v8::ConstructorBehavior::kThrow,
472                           v8::SideEffectType::kHasSideEffect);
473   // kInternalized strings are created in the old space.
474   const v8::NewStringType type = v8::NewStringType::kInternalized;
475   Local<v8::String> name_string =
476       v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
477   that->InstanceTemplate()->Set(name_string, t);
478   t->SetClassName(name_string);
479 }
480 
SetConstructorFunction(Local<v8::Context> context,Local<v8::Object> that,const char * name,Local<v8::FunctionTemplate> tmpl,SetConstructorFunctionFlag flag)481 void SetConstructorFunction(Local<v8::Context> context,
482                             Local<v8::Object> that,
483                             const char* name,
484                             Local<v8::FunctionTemplate> tmpl,
485                             SetConstructorFunctionFlag flag) {
486   Isolate* isolate = context->GetIsolate();
487   SetConstructorFunction(
488       context, that, OneByteString(isolate, name), tmpl, flag);
489 }
490 
SetConstructorFunction(Local<v8::Context> context,Local<v8::Object> that,Local<v8::String> name,Local<v8::FunctionTemplate> tmpl,SetConstructorFunctionFlag flag)491 void SetConstructorFunction(Local<v8::Context> context,
492                             Local<v8::Object> that,
493                             Local<v8::String> name,
494                             Local<v8::FunctionTemplate> tmpl,
495                             SetConstructorFunctionFlag flag) {
496   if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
497     tmpl->SetClassName(name);
498   that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check();
499 }
500 
501 namespace {
502 
503 class NonOwningExternalOneByteResource
504     : public v8::String::ExternalOneByteStringResource {
505  public:
NonOwningExternalOneByteResource(const UnionBytes & source)506   explicit NonOwningExternalOneByteResource(const UnionBytes& source)
507       : source_(source) {}
508   ~NonOwningExternalOneByteResource() override = default;
509 
data() const510   const char* data() const override {
511     return reinterpret_cast<const char*>(source_.one_bytes_data());
512   }
length() const513   size_t length() const override { return source_.length(); }
514 
515   NonOwningExternalOneByteResource(const NonOwningExternalOneByteResource&) =
516       delete;
517   NonOwningExternalOneByteResource& operator=(
518       const NonOwningExternalOneByteResource&) = delete;
519 
520  private:
521   const UnionBytes source_;
522 };
523 
524 class NonOwningExternalTwoByteResource
525     : public v8::String::ExternalStringResource {
526  public:
NonOwningExternalTwoByteResource(const UnionBytes & source)527   explicit NonOwningExternalTwoByteResource(const UnionBytes& source)
528       : source_(source) {}
529   ~NonOwningExternalTwoByteResource() override = default;
530 
data() const531   const uint16_t* data() const override { return source_.two_bytes_data(); }
length() const532   size_t length() const override { return source_.length(); }
533 
534   NonOwningExternalTwoByteResource(const NonOwningExternalTwoByteResource&) =
535       delete;
536   NonOwningExternalTwoByteResource& operator=(
537       const NonOwningExternalTwoByteResource&) = delete;
538 
539  private:
540   const UnionBytes source_;
541 };
542 
543 }  // anonymous namespace
544 
ToStringChecked(Isolate * isolate) const545 Local<String> UnionBytes::ToStringChecked(Isolate* isolate) const {
546   if (UNLIKELY(length() == 0)) {
547     // V8 requires non-null data pointers for empty external strings,
548     // but we don't guarantee that. Solve this by not creating an
549     // external string at all in that case.
550     return String::Empty(isolate);
551   }
552   if (is_one_byte()) {
553     NonOwningExternalOneByteResource* source =
554         new NonOwningExternalOneByteResource(*this);
555     return String::NewExternalOneByte(isolate, source).ToLocalChecked();
556   } else {
557     NonOwningExternalTwoByteResource* source =
558         new NonOwningExternalTwoByteResource(*this);
559     return String::NewExternalTwoByte(isolate, source).ToLocalChecked();
560   }
561 }
562 
563 }  // namespace node
564