Node.js  v8.x
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine
node_internals.h
Go to the documentation of this file.
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 #ifndef SRC_NODE_INTERNALS_H_
23 #define SRC_NODE_INTERNALS_H_
24 
25 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26 
27 #include "node.h"
28 #include "util.h"
29 #include "util-inl.h"
30 #include "uv.h"
31 #include "v8.h"
32 #include "tracing/trace_event.h"
33 #include "node_perf_common.h"
34 #include "node_debug_options.h"
35 
36 #include <stdint.h>
37 #include <stdlib.h>
38 
39 #include <string>
40 
41 struct sockaddr;
42 
43 // Variation on NODE_DEFINE_CONSTANT that sets a String value.
44 #define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \
45  do { \
46  v8::Isolate* isolate = target->GetIsolate(); \
47  v8::Local<v8::String> constant_name = \
48  v8::String::NewFromUtf8(isolate, name); \
49  v8::Local<v8::String> constant_value = \
50  v8::String::NewFromUtf8(isolate, constant); \
51  v8::PropertyAttribute constant_attributes = \
52  static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); \
53  target->DefineOwnProperty(isolate->GetCurrentContext(), \
54  constant_name, \
55  constant_value, \
56  constant_attributes).FromJust(); \
57  } while (0)
58 
59 namespace node {
60 
61 // Set in node.cc by ParseArgs with the value of --openssl-config.
62 // Used in node_crypto.cc when initializing OpenSSL.
63 extern std::string openssl_config;
64 
65 // Set in node.cc by ParseArgs when --preserve-symlinks is used.
66 // Used in node_config.cc to set a constant on process.binding('config')
67 // that is used by lib/module.js
68 extern bool config_preserve_symlinks;
69 
70 // Set in node.cc by ParseArgs when --expose-http2 is used.
71 extern bool config_expose_http2;
72 // Set in node.cc by ParseArgs when --experimental-modules is used.
73 // Used in node_config.cc to set a constant on process.binding('config')
74 // that is used by lib/module.js
75 extern bool config_experimental_modules;
76 
77 // Set in node.cc by ParseArgs when --expose-internals or --expose_internals is
78 // used.
79 // Used in node_config.cc to set a constant on process.binding('config')
80 // that is used by lib/internal/bootstrap_node.js
81 extern bool config_expose_internals;
82 
83 // Set in node.cc by ParseArgs when --redirect-warnings= is used.
84 // Used to redirect warning output to a file rather than sending
85 // it to stderr.
86 extern std::string config_warning_file; // NOLINT(runtime/string)
87 
88 // Set in node.cc by ParseArgs when --pending-deprecation or
89 // NODE_PENDING_DEPRECATION is used
90 extern bool config_pending_deprecation;
91 
92 // Tells whether it is safe to call v8::Isolate::GetCurrent().
93 extern bool v8_initialized;
94 
95 // Contains initial debug options.
96 // Set in node.cc.
97 // Used in node_config.cc.
99 
100 // Forward declaration
101 class Environment;
102 
103 // If persistent.IsWeak() == false, then do not call persistent.Reset()
104 // while the returned Local<T> is still in scope, it will destroy the
105 // reference to the object.
106 template <class TypeName>
107 inline v8::Local<TypeName> PersistentToLocal(
108  v8::Isolate* isolate,
109  const v8::Persistent<TypeName>& persistent);
110 
111 // Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object.
112 // Sets address and port properties on the info object and returns it.
113 // If |info| is omitted, a new object is returned.
114 v8::Local<v8::Object> AddressToJS(
115  Environment* env,
116  const sockaddr* addr,
117  v8::Local<v8::Object> info = v8::Local<v8::Object>());
118 
119 template <typename T, int (*F)(const typename T::HandleType*, sockaddr*, int*)>
120 void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
121  T* const wrap = Unwrap<T>(args.Holder());
122  if (wrap == nullptr)
123  return args.GetReturnValue().Set(UV_EBADF);
124  CHECK(args[0]->IsObject());
125  sockaddr_storage storage;
126  int addrlen = sizeof(storage);
127  sockaddr* const addr = reinterpret_cast<sockaddr*>(&storage);
128  const int err = F(&wrap->handle_, addr, &addrlen);
129  if (err == 0)
130  AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
131  args.GetReturnValue().Set(err);
132 }
133 
134 void SignalExit(int signo);
135 #ifdef __POSIX__
136 void RegisterSignalHandler(int signal,
137  void (*handler)(int signal),
138  bool reset_handler = false);
139 #endif
140 
141 bool SafeGetenv(const char* key, std::string* text);
142 
143 template <typename T, size_t N>
144 constexpr size_t arraysize(const T(&)[N]) { return N; }
145 
146 #ifndef ROUND_UP
147 # define ROUND_UP(a, b) ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a))
148 #endif
149 
150 #ifdef __GNUC__
151 # define MUST_USE_RESULT __attribute__((warn_unused_result))
152 #else
153 # define MUST_USE_RESULT
154 #endif
155 
156 bool IsExceptionDecorated(Environment* env, v8::Local<v8::Value> er);
157 
158 enum ErrorHandlingMode { FATAL_ERROR, CONTEXTIFY_ERROR };
159 void AppendExceptionLine(Environment* env,
160  v8::Local<v8::Value> er,
161  v8::Local<v8::Message> message,
162  enum ErrorHandlingMode mode);
163 
164 NO_RETURN void FatalError(const char* location, const char* message);
165 
166 void ProcessEmitWarning(Environment* env, const char* fmt, ...);
167 
168 void FillStatsArray(double* fields, const uv_stat_t* s);
169 
170 void SetupProcessObject(Environment* env,
171  int argc,
172  const char* const* argv,
173  int exec_argc,
174  const char* const* exec_argv);
175 
176 enum Endianness {
177  kLittleEndian, // _Not_ LITTLE_ENDIAN, clashes with endian.h.
178  kBigEndian
179 };
180 
181 inline enum Endianness GetEndianness() {
182  // Constant-folded by the compiler.
183  const union {
184  uint8_t u8[2];
185  uint16_t u16;
186  } u = {
187  { 1, 0 }
188  };
189  return u.u16 == 1 ? kLittleEndian : kBigEndian;
190 }
191 
192 inline bool IsLittleEndian() {
193  return GetEndianness() == kLittleEndian;
194 }
195 
196 inline bool IsBigEndian() {
197  return GetEndianness() == kBigEndian;
198 }
199 
200 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
201  public:
202  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
203 
204  virtual void* Allocate(size_t size); // Defined in src/node.cc
205  virtual void* AllocateUninitialized(size_t size)
206  { return node::UncheckedMalloc(size); }
207  virtual void Free(void* data, size_t) { free(data); }
208 
209  private:
210  uint32_t zero_fill_field_ = 1; // Boolean but exposed as uint32 to JS land.
211 };
212 
213 // Clear any domain and/or uncaughtException handlers to force the error's
214 // propagation and shutdown the process. Use this to force the process to exit
215 // by clearing all callbacks that could handle the error.
216 void ClearFatalExceptionHandlers(Environment* env);
217 
218 namespace Buffer {
219 v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
220 v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
221 // Takes ownership of |data|.
222 v8::MaybeLocal<v8::Object> New(Environment* env,
223  char* data,
224  size_t length,
225  void (*callback)(char* data, void* hint),
226  void* hint);
227 // Takes ownership of |data|. Must allocate |data| with malloc() or realloc()
228 // because ArrayBufferAllocator::Free() deallocates it again with free().
229 // Mixing operator new and free() is undefined behavior so don't do that.
230 v8::MaybeLocal<v8::Object> New(Environment* env, char* data, size_t length);
231 
232 // Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
233 // Utf8Value and TwoByteValue).
234 // If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
235 // changed.
236 // If |buf| contains actual data, this method takes ownership of |buf|'s
237 // underlying buffer. However, |buf| itself can be reused even after this call,
238 // but its capacity, if increased through AllocateSufficientStorage, is not
239 // guaranteed to stay the same.
240 template <typename T>
241 static v8::MaybeLocal<v8::Object> New(Environment* env,
242  MaybeStackBuffer<T>* buf) {
243  v8::MaybeLocal<v8::Object> ret;
244  char* src = reinterpret_cast<char*>(buf->out());
245  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
246 
247  if (buf->IsAllocated())
248  ret = New(env, src, len_in_bytes);
249  else if (!buf->IsInvalidated())
250  ret = Copy(env, src, len_in_bytes);
251 
252  if (ret.IsEmpty())
253  return ret;
254 
255  if (buf->IsAllocated())
256  buf->Release();
257 
258  return ret;
259 }
260 } // namespace Buffer
261 
262 } // namespace node
263 
264 #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
265 
266 #endif // SRC_NODE_INTERNALS_H_
bool IsExceptionDecorated(Environment *env, Local< Value > er)
Definition: node.cc:1607
void AppendExceptionLine(Environment *env, Local< Value > er, Local< Message > message, enum ErrorHandlingMode mode)
Definition: node.cc:1618
unsigned char * buf
Definition: cares_wrap.cc:483
bool config_expose_http2
Definition: node.cc:247
void ClearFatalExceptionHandlers(Environment *env)
Definition: node.cc:2688
int len
Definition: cares_wrap.cc:485
void ProcessEmitWarning(Environment *env, const char *fmt,...)
Definition: node.cc:2707
QueryWrap * wrap
Definition: cares_wrap.cc:478
NO_RETURN void FatalError(const char *location, const char *message)
Definition: node.cc:2616
union node::cares_wrap::@8::CaresAsyncData::@0 data
bool config_experimental_modules
Definition: node.cc:231
bool SafeGetenv(const char *key, std::string *text)
Definition: node.cc:1002
void SignalExit(int signo)
Definition: node.cc:3544
bool v8_initialized
Definition: node.cc:249
node::DebugOptions debug_options
Definition: node.cc:259
bool config_pending_deprecation
Definition: node.cc:235
std::string config_warning_file
Definition: node.cc:238
void FillStatsArray(double *fields, const uv_stat_t *s)
Definition: node_file.cc:463
dtrace s
Definition: v8ustack.d:615
Local< Object > AddressToJS(Environment *env, const sockaddr *addr, Local< Object > info)
Definition: tcp_wrap.cc:324
bool config_preserve_symlinks
Definition: node.cc:226
MaybeLocal< Object > New(Isolate *isolate, Local< String > string, enum encoding enc)
Definition: node_buffer.cc:241
void SetupProcessObject(Environment *env, int argc, const char *const *argv, int exec_argc, const char *const *exec_argv)
Definition: node.cc:3167
bool config_expose_internals
Definition: node.cc:244
MaybeLocal< Object > Copy(Isolate *isolate, const char *data, size_t length)
Definition: node_buffer.cc:320