GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_internals.h Lines: 47 50 94.0 %
Date: 2020-02-19 22:14:06 Branches: 29 38 76.3 %

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 "env.h"
28
#include "node.h"
29
#include "node_binding.h"
30
#include "node_mutex.h"
31
#include "tracing/trace_event.h"
32
#include "util.h"
33
#include "uv.h"
34
#include "v8.h"
35
36
#include <cstdint>
37
#include <cstdlib>
38
39
#include <string>
40
#include <vector>
41
42
// Custom constants used by both node_constants.cc and node_zlib.cc
43
#define Z_MIN_WINDOWBITS 8
44
#define Z_MAX_WINDOWBITS 15
45
#define Z_DEFAULT_WINDOWBITS 15
46
47
struct sockaddr;
48
49
namespace node {
50
51
namespace native_module {
52
class NativeModuleLoader;
53
}
54
55
namespace per_process {
56
extern Mutex env_var_mutex;
57
extern uint64_t node_start_time;
58
extern bool v8_is_profiling;
59
}  // namespace per_process
60
61
// Forward declaration
62
class Environment;
63
64
// Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object.
65
// Sets address and port properties on the info object and returns it.
66
// If |info| is omitted, a new object is returned.
67
v8::Local<v8::Object> AddressToJS(
68
    Environment* env,
69
    const sockaddr* addr,
70
    v8::Local<v8::Object> info = v8::Local<v8::Object>());
71
72
template <typename T, int (*F)(const typename T::HandleType*, sockaddr*, int*)>
73
3925
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
74
  T* wrap;
75

3925
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
76
                          args.Holder(),
77
                          args.GetReturnValue().Set(UV_EBADF));
78

7850
  CHECK(args[0]->IsObject());
79
  sockaddr_storage storage;
80
3925
  int addrlen = sizeof(storage);
81
3925
  sockaddr* const addr = reinterpret_cast<sockaddr*>(&storage);
82
3925
  const int err = F(&wrap->handle_, addr, &addrlen);
83

3925
  if (err == 0)
84
7840
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
85
7850
  args.GetReturnValue().Set(err);
86
}
87
88
void PrintStackTrace(v8::Isolate* isolate, v8::Local<v8::StackTrace> stack);
89
void PrintCaughtException(v8::Isolate* isolate,
90
                          v8::Local<v8::Context> context,
91
                          const v8::TryCatch& try_catch);
92
93
void ResetStdio();  // Safe to call more than once and from signal handlers.
94
#ifdef __POSIX__
95
void SignalExit(int signal, siginfo_t* info, void* ucontext);
96
#endif
97
98
std::string GetProcessTitle(const char* default_title);
99
std::string GetHumanReadableProcessName();
100
101
void InitializeContextRuntime(v8::Local<v8::Context>);
102
bool InitializePrimordials(v8::Local<v8::Context> context);
103
104
namespace task_queue {
105
void PromiseRejectCallback(v8::PromiseRejectMessage message);
106
}  // namespace task_queue
107
108
12318
class NodeArrayBufferAllocator : public ArrayBufferAllocator {
109
 public:
110
4351
  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
111
112
  void* Allocate(size_t size) override;  // Defined in src/node.cc
113
  void* AllocateUninitialized(size_t size) override;
114
  void Free(void* data, size_t size) override;
115
  virtual void* Reallocate(void* data, size_t old_size, size_t size);
116
444
  virtual void RegisterPointer(void* data, size_t size) {
117
444
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
118
444
  }
119
  virtual void UnregisterPointer(void* data, size_t size) {
120
    total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
121
  }
122
123
4353
  NodeArrayBufferAllocator* GetImpl() final { return this; }
124
527
  inline uint64_t total_mem_usage() const {
125
1054
    return total_mem_usage_.load(std::memory_order_relaxed);
126
  }
127
128
 private:
129
  uint32_t zero_fill_field_ = 1;  // Boolean but exposed as uint32 to JS land.
130
  std::atomic<size_t> total_mem_usage_ {0};
131
};
132
133
3
class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator {
134
 public:
135
  ~DebuggingArrayBufferAllocator() override;
136
  void* Allocate(size_t size) override;
137
  void* AllocateUninitialized(size_t size) override;
138
  void Free(void* data, size_t size) override;
139
  void* Reallocate(void* data, size_t old_size, size_t size) override;
140
  void RegisterPointer(void* data, size_t size) override;
141
  void UnregisterPointer(void* data, size_t size) override;
142
143
 private:
144
  void RegisterPointerInternal(void* data, size_t size);
145
  void UnregisterPointerInternal(void* data, size_t size);
146
  Mutex mutex_;
147
  std::unordered_map<void*, size_t> allocations_;
148
};
149
150
namespace Buffer {
151
v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
152
v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
153
// Takes ownership of |data|.
154
v8::MaybeLocal<v8::Object> New(Environment* env,
155
                               char* data,
156
                               size_t length,
157
                               void (*callback)(char* data, void* hint),
158
                               void* hint);
159
// Takes ownership of |data|.  Must allocate |data| with the current Isolate's
160
// ArrayBuffer::Allocator().
161
v8::MaybeLocal<v8::Object> New(Environment* env,
162
                               char* data,
163
                               size_t length,
164
                               bool uses_malloc);
165
// Creates a Buffer instance over an existing ArrayBuffer.
166
v8::MaybeLocal<v8::Uint8Array> New(Environment* env,
167
                                   v8::Local<v8::ArrayBuffer> ab,
168
                                   size_t byte_offset,
169
                                   size_t length);
170
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
171
// Utf8Value and TwoByteValue).
172
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
173
// changed.
174
// If |buf| contains actual data, this method takes ownership of |buf|'s
175
// underlying buffer. However, |buf| itself can be reused even after this call,
176
// but its capacity, if increased through AllocateSufficientStorage, is not
177
// guaranteed to stay the same.
178
template <typename T>
179
7341
static v8::MaybeLocal<v8::Object> New(Environment* env,
180
                                      MaybeStackBuffer<T>* buf) {
181
  v8::MaybeLocal<v8::Object> ret;
182
7341
  char* src = reinterpret_cast<char*>(buf->out());
183
7341
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
184
185

7341
  if (buf->IsAllocated())
186
2
    ret = New(env, src, len_in_bytes, true);
187

7339
  else if (!buf->IsInvalidated())
188
7339
    ret = Copy(env, src, len_in_bytes);
189
190

7341
  if (ret.IsEmpty())
191
    return ret;
192
193

7341
  if (buf->IsAllocated())
194
2
    buf->Release();
195
196
7341
  return ret;
197
}
198
}  // namespace Buffer
199
200
v8::MaybeLocal<v8::Value> InternalMakeCallback(
201
    Environment* env,
202
    v8::Local<v8::Object> recv,
203
    const v8::Local<v8::Function> callback,
204
    int argc,
205
    v8::Local<v8::Value> argv[],
206
    async_context asyncContext);
207
208
class InternalCallbackScope {
209
 public:
210
  enum Flags {
211
    kNoFlags = 0,
212
    // Indicates whether 'before' and 'after' hooks should be skipped.
213
    kSkipAsyncHooks = 1,
214
    // Indicates whether nextTick and microtask queues should be skipped.
215
    // This should only be used when there is no call into JS in this scope.
216
    // (The HTTP parser also uses it for some weird backwards
217
    // compatibility issues, but it shouldn't.)
218
    kSkipTaskQueues = 2
219
  };
220
  InternalCallbackScope(Environment* env,
221
                        v8::Local<v8::Object> object,
222
                        const async_context& asyncContext,
223
                        int flags = kNoFlags);
224
  // Utility that can be used by AsyncWrap classes.
225
  explicit InternalCallbackScope(AsyncWrap* async_wrap, int flags = 0);
226
  ~InternalCallbackScope();
227
  void Close();
228
229
1195250
  inline bool Failed() const { return failed_; }
230
593
  inline void MarkAsFailed() { failed_ = true; }
231
232
 private:
233
  Environment* env_;
234
  async_context async_context_;
235
  v8::Local<v8::Object> object_;
236
  bool skip_hooks_;
237
  bool skip_task_queues_;
238
  bool failed_ = false;
239
  bool pushed_ids_ = false;
240
  bool closed_ = false;
241
};
242
243
class DebugSealHandleScope {
244
 public:
245
1113625
  explicit inline DebugSealHandleScope(v8::Isolate* isolate)
246
#ifdef DEBUG
247
    : actual_scope_(isolate)
248
#endif
249
1113625
  {}
250
251
 private:
252
#ifdef DEBUG
253
  v8::SealHandleScope actual_scope_;
254
#endif
255
};
256
257
class ThreadPoolWork {
258
 public:
259
2171
  explicit inline ThreadPoolWork(Environment* env) : env_(env) {
260
2171
    CHECK_NOT_NULL(env);
261
2171
  }
262
1993
  inline virtual ~ThreadPoolWork() = default;
263
264
  inline void ScheduleWork();
265
  inline int CancelWork();
266
267
  virtual void DoThreadPoolWork() = 0;
268
  virtual void AfterThreadPoolWork(int status) = 0;
269
270
650
  Environment* env() const { return env_; }
271
272
 private:
273
  Environment* env_;
274
  uv_work_t work_req_;
275
};
276
277
#define TRACING_CATEGORY_NODE "node"
278
#define TRACING_CATEGORY_NODE1(one)                                           \
279
    TRACING_CATEGORY_NODE ","                                                 \
280
    TRACING_CATEGORY_NODE "." #one
281
#define TRACING_CATEGORY_NODE2(one, two)                                      \
282
    TRACING_CATEGORY_NODE ","                                                 \
283
    TRACING_CATEGORY_NODE "." #one ","                                        \
284
    TRACING_CATEGORY_NODE "." #one "." #two
285
286
// Functions defined in node.cc that are exposed via the bootstrapper object
287
288
#if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__)
289
#define NODE_IMPLEMENTS_POSIX_CREDENTIALS 1
290
#endif  // __POSIX__ && !defined(__ANDROID__) && !defined(__CloudABI__)
291
292
namespace credentials {
293
bool SafeGetenv(const char* key, std::string* text, Environment* env = nullptr);
294
}  // namespace credentials
295
296
void DefineZlibConstants(v8::Local<v8::Object> target);
297
v8::Isolate* NewIsolate(v8::Isolate::CreateParams* params,
298
                        uv_loop_t* event_loop,
299
                        MultiIsolatePlatform* platform);
300
v8::MaybeLocal<v8::Value> StartExecution(Environment* env,
301
                                         const char* main_script_id);
302
v8::MaybeLocal<v8::Object> GetPerContextExports(v8::Local<v8::Context> context);
303
v8::MaybeLocal<v8::Value> ExecuteBootstrapper(
304
    Environment* env,
305
    const char* id,
306
    std::vector<v8::Local<v8::String>>* parameters,
307
    std::vector<v8::Local<v8::Value>>* arguments);
308
void MarkBootstrapComplete(const v8::FunctionCallbackInfo<v8::Value>& args);
309
310
7961
struct InitializationResult {
311
  int exit_code = 0;
312
  std::vector<std::string> args;
313
  std::vector<std::string> exec_args;
314
  bool early_return = false;
315
};
316
InitializationResult InitializeOncePerProcess(int argc, char** argv);
317
void TearDownOncePerProcess();
318
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s);
319
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s);
320
void SetIsolateCreateParamsForNode(v8::Isolate::CreateParams* params);
321
322
#if HAVE_INSPECTOR
323
namespace profiler {
324
void StartProfilers(Environment* env);
325
}
326
#endif  // HAVE_INSPECTOR
327
328
#ifdef __POSIX__
329
static constexpr unsigned kMaxSignal = 32;
330
#endif
331
332
bool HasSignalJSHandler(int signum);
333
334
#ifdef _WIN32
335
typedef SYSTEMTIME TIME_TYPE;
336
#else  // UNIX, OSX
337
typedef struct tm TIME_TYPE;
338
#endif
339
340
double GetCurrentTimeInMicroseconds();
341
int WriteFileSync(const char* path, uv_buf_t buf);
342
int WriteFileSync(v8::Isolate* isolate,
343
                  const char* path,
344
                  v8::Local<v8::String> string);
345
346
25
class DiagnosticFilename {
347
 public:
348
  static void LocalTime(TIME_TYPE* tm_struct);
349
350
  inline DiagnosticFilename(Environment* env,
351
                            const char* prefix,
352
                            const char* ext);
353
354
  inline DiagnosticFilename(uint64_t thread_id,
355
                            const char* prefix,
356
                            const char* ext);
357
358
  inline const char* operator*() const;
359
360
 private:
361
  static std::string MakeFilename(
362
      uint64_t thread_id,
363
      const char* prefix,
364
      const char* ext);
365
366
  std::string filename_;
367
};
368
369
class TraceEventScope {
370
 public:
371
826682
  TraceEventScope(const char* category,
372
                  const char* name,
373
826682
                  void* id) : category_(category), name_(name), id_(id) {
374

1653370
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
375
826685
  }
376
1653325
  ~TraceEventScope() {
377

1653328
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
378
826664
  }
379
380
 private:
381
  const char* category_;
382
  const char* name_;
383
  void* id_;
384
};
385
386
namespace heap {
387
388
void DeleteHeapSnapshot(const v8::HeapSnapshot* snapshot);
389
using HeapSnapshotPointer =
390
  DeleteFnPtr<const v8::HeapSnapshot, DeleteHeapSnapshot>;
391
392
BaseObjectPtr<AsyncWrap> CreateHeapSnapshotStream(
393
    Environment* env, HeapSnapshotPointer&& snapshot);
394
}  // namespace heap
395
396
}  // namespace node
397
398
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
399
400
#endif  // SRC_NODE_INTERNALS_H_