GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/node_internals.h Lines: 39 40 97.5 %
Date: 2017-10-21 Branches: 21 30 70.0 %

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
#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 "env.h"
31
#include "env-inl.h"
32
#include "uv.h"
33
#include "v8.h"
34
#include "tracing/trace_event.h"
35
#include "node_perf_common.h"
36
#include "node_debug_options.h"
37
38
#include <stdint.h>
39
#include <stdlib.h>
40
41
#include <string>
42
43
// Custom constants used by both node_constants.cc and node_zlib.cc
44
#define Z_MIN_WINDOWBITS 8
45
#define Z_MAX_WINDOWBITS 15
46
#define Z_DEFAULT_WINDOWBITS 15
47
// Fewer than 64 bytes per chunk is not recommended.
48
// Technically it could work with as few as 8, but even 64 bytes
49
// is low.  Usually a MB or more is best.
50
#define Z_MIN_CHUNK 64
51
#define Z_MAX_CHUNK std::numeric_limits<double>::infinity()
52
#define Z_DEFAULT_CHUNK (16 * 1024)
53
#define Z_MIN_MEMLEVEL 1
54
#define Z_MAX_MEMLEVEL 9
55
#define Z_DEFAULT_MEMLEVEL 8
56
#define Z_MIN_LEVEL -1
57
#define Z_MAX_LEVEL 9
58
#define Z_DEFAULT_LEVEL Z_DEFAULT_COMPRESSION
59
60
struct sockaddr;
61
62
// Variation on NODE_DEFINE_CONSTANT that sets a String value.
63
#define NODE_DEFINE_STRING_CONSTANT(target, name, constant)                   \
64
  do {                                                                        \
65
    v8::Isolate* isolate = target->GetIsolate();                              \
66
    v8::Local<v8::String> constant_name =                                     \
67
        v8::String::NewFromUtf8(isolate, name);                               \
68
    v8::Local<v8::String> constant_value =                                    \
69
        v8::String::NewFromUtf8(isolate, constant);                           \
70
    v8::PropertyAttribute constant_attributes =                               \
71
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);    \
72
    target->DefineOwnProperty(isolate->GetCurrentContext(),                   \
73
                              constant_name,                                  \
74
                              constant_value,                                 \
75
                              constant_attributes).FromJust();                \
76
  } while (0)
77
78
namespace node {
79
80
// Set in node.cc by ParseArgs with the value of --openssl-config.
81
// Used in node_crypto.cc when initializing OpenSSL.
82
extern std::string openssl_config;
83
84
// Set in node.cc by ParseArgs when --preserve-symlinks is used.
85
// Used in node_config.cc to set a constant on process.binding('config')
86
// that is used by lib/module.js
87
extern bool config_preserve_symlinks;
88
89
// Set in node.cc by ParseArgs when --experimental-modules is used.
90
// Used in node_config.cc to set a constant on process.binding('config')
91
// that is used by lib/module.js
92
extern bool config_experimental_modules;
93
94
// Set in node.cc by ParseArgs when --loader is used.
95
// Used in node_config.cc to set a constant on process.binding('config')
96
// that is used by lib/internal/bootstrap_node.js
97
extern std::string config_userland_loader;
98
99
// Set in node.cc by ParseArgs when --expose-internals or --expose_internals is
100
// used.
101
// Used in node_config.cc to set a constant on process.binding('config')
102
// that is used by lib/internal/bootstrap_node.js
103
extern bool config_expose_internals;
104
105
// Set in node.cc by ParseArgs when --redirect-warnings= is used.
106
// Used to redirect warning output to a file rather than sending
107
// it to stderr.
108
extern std::string config_warning_file;  // NOLINT(runtime/string)
109
110
// Set in node.cc by ParseArgs when --pending-deprecation or
111
// NODE_PENDING_DEPRECATION is used
112
extern bool config_pending_deprecation;
113
114
// Tells whether it is safe to call v8::Isolate::GetCurrent().
115
extern bool v8_initialized;
116
117
// Contains initial debug options.
118
// Set in node.cc.
119
// Used in node_config.cc.
120
extern node::DebugOptions debug_options;
121
122
// Forward declaration
123
class Environment;
124
125
// If persistent.IsWeak() == false, then do not call persistent.Reset()
126
// while the returned Local<T> is still in scope, it will destroy the
127
// reference to the object.
128
template <class TypeName>
129
inline v8::Local<TypeName> PersistentToLocal(
130
    v8::Isolate* isolate,
131
    const v8::Persistent<TypeName>& persistent);
132
133
// Creates a new context with Node.js-specific tweaks.  Currently, it removes
134
// the `v8BreakIterator` property from the global `Intl` object if present.
135
// See https://github.com/nodejs/node/issues/14909 for more info.
136
v8::Local<v8::Context> NewContext(
137
    v8::Isolate* isolate,
138
    v8::Local<v8::ObjectTemplate> object_template =
139
        v8::Local<v8::ObjectTemplate>());
140
141
// Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object.
142
// Sets address and port properties on the info object and returns it.
143
// If |info| is omitted, a new object is returned.
144
v8::Local<v8::Object> AddressToJS(
145
    Environment* env,
146
    const sockaddr* addr,
147
    v8::Local<v8::Object> info = v8::Local<v8::Object>());
148
149
template <typename T, int (*F)(const typename T::HandleType*, sockaddr*, int*)>
150
1519
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
151
1519
  T* const wrap = Unwrap<T>(args.Holder());
152

1519
  if (wrap == nullptr)
153
1519
    return args.GetReturnValue().Set(UV_EBADF);
154

3038
  CHECK(args[0]->IsObject());
155
  sockaddr_storage storage;
156
1519
  int addrlen = sizeof(storage);
157
1519
  sockaddr* const addr = reinterpret_cast<sockaddr*>(&storage);
158
1519
  const int err = F(&wrap->handle_, addr, &addrlen);
159

1519
  if (err == 0)
160
3028
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
161
3038
  args.GetReturnValue().Set(err);
162
}
163
164
void SignalExit(int signo);
165
#ifdef __POSIX__
166
void RegisterSignalHandler(int signal,
167
                           void (*handler)(int signal),
168
                           bool reset_handler = false);
169
#endif
170
171
bool SafeGetenv(const char* key, std::string* text);
172
173
template <typename T, size_t N>
174
2854521
constexpr size_t arraysize(const T(&)[N]) { return N; }
175
176
#ifndef ROUND_UP
177
# define ROUND_UP(a, b) ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a))
178
#endif
179
180
#ifdef __GNUC__
181
# define MUST_USE_RESULT __attribute__((warn_unused_result))
182
#else
183
# define MUST_USE_RESULT
184
#endif
185
186
bool IsExceptionDecorated(Environment* env, v8::Local<v8::Value> er);
187
188
enum ErrorHandlingMode { FATAL_ERROR, CONTEXTIFY_ERROR };
189
void AppendExceptionLine(Environment* env,
190
                         v8::Local<v8::Value> er,
191
                         v8::Local<v8::Message> message,
192
                         enum ErrorHandlingMode mode);
193
194
NO_RETURN void FatalError(const char* location, const char* message);
195
196
void ProcessEmitWarning(Environment* env, const char* fmt, ...);
197
198
void FillStatsArray(double* fields, const uv_stat_t* s);
199
200
void SetupProcessObject(Environment* env,
201
                        int argc,
202
                        const char* const* argv,
203
                        int exec_argc,
204
                        const char* const* exec_argv);
205
206
enum Endianness {
207
  kLittleEndian,  // _Not_ LITTLE_ENDIAN, clashes with endian.h.
208
  kBigEndian
209
};
210
211
8386
inline enum Endianness GetEndianness() {
212
  // Constant-folded by the compiler.
213
  const union {
214
    uint8_t u8[2];
215
    uint16_t u16;
216
  } u = {
217
    { 1, 0 }
218
8386
  };
219
8386
  return u.u16 == 1 ? kLittleEndian : kBigEndian;
220
}
221
222
2731
inline bool IsLittleEndian() {
223
2731
  return GetEndianness() == kLittleEndian;
224
}
225
226
5535
inline bool IsBigEndian() {
227
5535
  return GetEndianness() == kBigEndian;
228
}
229
230
2842
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
231
 public:
232
3202
  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
233
234
  virtual void* Allocate(size_t size);  // Defined in src/node.cc
235
5730
  virtual void* AllocateUninitialized(size_t size)
236
5730
    { return node::UncheckedMalloc(size); }
237
78470
  virtual void Free(void* data, size_t) { free(data); }
238
239
 private:
240
  uint32_t zero_fill_field_ = 1;  // Boolean but exposed as uint32 to JS land.
241
};
242
243
// Clear any domain and/or uncaughtException handlers to force the error's
244
// propagation and shutdown the process. Use this to force the process to exit
245
// by clearing all callbacks that could handle the error.
246
void ClearFatalExceptionHandlers(Environment* env);
247
248
namespace Buffer {
249
v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
250
v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
251
// Takes ownership of |data|.
252
v8::MaybeLocal<v8::Object> New(Environment* env,
253
                               char* data,
254
                               size_t length,
255
                               void (*callback)(char* data, void* hint),
256
                               void* hint);
257
// Takes ownership of |data|.  Must allocate |data| with malloc() or realloc()
258
// because ArrayBufferAllocator::Free() deallocates it again with free().
259
// Mixing operator new and free() is undefined behavior so don't do that.
260
v8::MaybeLocal<v8::Object> New(Environment* env, char* data, size_t length);
261
262
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
263
// Utf8Value and TwoByteValue).
264
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
265
// changed.
266
// If |buf| contains actual data, this method takes ownership of |buf|'s
267
// underlying buffer. However, |buf| itself can be reused even after this call,
268
// but its capacity, if increased through AllocateSufficientStorage, is not
269
// guaranteed to stay the same.
270
template <typename T>
271
36
static v8::MaybeLocal<v8::Object> New(Environment* env,
272
                                      MaybeStackBuffer<T>* buf) {
273
  v8::MaybeLocal<v8::Object> ret;
274
36
  char* src = reinterpret_cast<char*>(buf->out());
275
36
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
276
277

36
  if (buf->IsAllocated())
278
2
    ret = New(env, src, len_in_bytes);
279

34
  else if (!buf->IsInvalidated())
280
34
    ret = Copy(env, src, len_in_bytes);
281
282

36
  if (ret.IsEmpty())
283
    return ret;
284
285

36
  if (buf->IsAllocated())
286
2
    buf->Release();
287
288
36
  return ret;
289
}
290
}  // namespace Buffer
291
292
v8::MaybeLocal<v8::Value> InternalMakeCallback(
293
    Environment* env,
294
    v8::Local<v8::Object> recv,
295
    const v8::Local<v8::Function> callback,
296
    int argc,
297
    v8::Local<v8::Value> argv[],
298
    async_context asyncContext);
299
300
class InternalCallbackScope {
301
 public:
302
  // Tell the constructor whether its `object` parameter may be empty or not.
303
  enum ResourceExpectation { kRequireResource, kAllowEmptyResource };
304
  InternalCallbackScope(Environment* env,
305
                        v8::Local<v8::Object> object,
306
                        const async_context& asyncContext,
307
                        ResourceExpectation expect = kRequireResource);
308
  ~InternalCallbackScope();
309
  void Close();
310
311
803578
  inline bool Failed() const { return failed_; }
312
1096
  inline void MarkAsFailed() { failed_ = true; }
313
403083
  inline bool IsInnerMakeCallback() const {
314
403083
    return callback_scope_.in_makecallback();
315
  }
316
317
 private:
318
  Environment* env_;
319
  async_context async_context_;
320
  v8::Local<v8::Object> object_;
321
  Environment::AsyncCallbackScope callback_scope_;
322
  bool failed_ = false;
323
  bool pushed_ids_ = false;
324
  bool closed_ = false;
325
};
326
327
#define NODE_MODULE_CONTEXT_AWARE_INTERNAL(modname, regfunc)          \
328
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, NM_F_INTERNAL)  \
329
330
}  // namespace node
331
332
333
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
334
335
#endif  // SRC_NODE_INTERNALS_H_