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: 44 49 89.8 %
Date: 2020-06-24 22:13:30 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
4054
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
74
  T* wrap;
75

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

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

4054
  if (err == 0)
84
8098
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
85
8108
  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
13259
class NodeArrayBufferAllocator : public ArrayBufferAllocator {
109
 public:
110
1344887
  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
  void* Reallocate(void* data, size_t old_size, size_t size) override;
116
  virtual void RegisterPointer(void* data, size_t size) {
117
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
118
  }
119
  virtual void UnregisterPointer(void* data, size_t size) {
120
    total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
121
  }
122
123
4686
  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
// Creates a Buffer instance over an existing ArrayBuffer.
165
v8::MaybeLocal<v8::Uint8Array> New(Environment* env,
166
                                   v8::Local<v8::ArrayBuffer> ab,
167
                                   size_t byte_offset,
168
                                   size_t length);
169
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
170
// Utf8Value and TwoByteValue).
171
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
172
// changed.
173
// If |buf| contains actual data, this method takes ownership of |buf|'s
174
// underlying buffer. However, |buf| itself can be reused even after this call,
175
// but its capacity, if increased through AllocateSufficientStorage, is not
176
// guaranteed to stay the same.
177
template <typename T>
178
7599
static v8::MaybeLocal<v8::Object> New(Environment* env,
179
                                      MaybeStackBuffer<T>* buf) {
180
  v8::MaybeLocal<v8::Object> ret;
181
7599
  char* src = reinterpret_cast<char*>(buf->out());
182
7599
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
183
184

7599
  if (buf->IsAllocated())
185
65
    ret = New(env, src, len_in_bytes);
186

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

7599
  if (ret.IsEmpty())
190
    return ret;
191
192

7599
  if (buf->IsAllocated())
193
65
    buf->Release();
194
195
7599
  return ret;
196
}
197
}  // namespace Buffer
198
199
v8::MaybeLocal<v8::Value> InternalMakeCallback(
200
    Environment* env,
201
    v8::Local<v8::Object> resource,
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
1221655
  inline bool Failed() const { return failed_; }
230
656
  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
1554810
  explicit inline DebugSealHandleScope(v8::Isolate* isolate = nullptr)
246
#ifdef DEBUG
247
    : actual_scope_(isolate != nullptr ? isolate : v8::Isolate::GetCurrent())
248
#endif
249
1554810
  {}
250
251
 private:
252
#ifdef DEBUG
253
  v8::SealHandleScope actual_scope_;
254
#endif
255
};
256
257
class ThreadPoolWork {
258
 public:
259
2179
  explicit inline ThreadPoolWork(Environment* env) : env_(env) {
260
2179
    CHECK_NOT_NULL(env);
261
2179
  }
262
2001
  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
657
  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
// This overload automatically picks the right 'main_script_id' if no callback
301
// was provided by the embedder.
302
v8::MaybeLocal<v8::Value> StartExecution(Environment* env,
303
                                         StartExecutionCallback cb = nullptr);
304
v8::MaybeLocal<v8::Object> GetPerContextExports(v8::Local<v8::Context> context);
305
v8::MaybeLocal<v8::Value> ExecuteBootstrapper(
306
    Environment* env,
307
    const char* id,
308
    std::vector<v8::Local<v8::String>>* parameters,
309
    std::vector<v8::Local<v8::Value>>* arguments);
310
void MarkBootstrapComplete(const v8::FunctionCallbackInfo<v8::Value>& args);
311
312
8314
struct InitializationResult {
313
  int exit_code = 0;
314
  std::vector<std::string> args;
315
  std::vector<std::string> exec_args;
316
  bool early_return = false;
317
};
318
InitializationResult InitializeOncePerProcess(int argc, char** argv);
319
void TearDownOncePerProcess();
320
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s);
321
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s);
322
void SetIsolateCreateParamsForNode(v8::Isolate::CreateParams* params);
323
324
#if HAVE_INSPECTOR
325
namespace profiler {
326
void StartProfilers(Environment* env);
327
}
328
#endif  // HAVE_INSPECTOR
329
330
#ifdef __POSIX__
331
static constexpr unsigned kMaxSignal = 32;
332
#endif
333
334
bool HasSignalJSHandler(int signum);
335
336
#ifdef _WIN32
337
typedef SYSTEMTIME TIME_TYPE;
338
#else  // UNIX, OSX
339
typedef struct tm TIME_TYPE;
340
#endif
341
342
double GetCurrentTimeInMicroseconds();
343
int WriteFileSync(const char* path, uv_buf_t buf);
344
int WriteFileSync(v8::Isolate* isolate,
345
                  const char* path,
346
                  v8::Local<v8::String> string);
347
348
26
class DiagnosticFilename {
349
 public:
350
  static void LocalTime(TIME_TYPE* tm_struct);
351
352
  inline DiagnosticFilename(Environment* env,
353
                            const char* prefix,
354
                            const char* ext);
355
356
  inline DiagnosticFilename(uint64_t thread_id,
357
                            const char* prefix,
358
                            const char* ext);
359
360
  inline const char* operator*() const;
361
362
 private:
363
  static std::string MakeFilename(
364
      uint64_t thread_id,
365
      const char* prefix,
366
      const char* ext);
367
368
  std::string filename_;
369
};
370
371
class TraceEventScope {
372
 public:
373
833360
  TraceEventScope(const char* category,
374
                  const char* name,
375
833360
                  void* id) : category_(category), name_(name), id_(id) {
376

1666722
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
377
833361
  }
378
1666684
  ~TraceEventScope() {
379

1666684
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
380
833342
  }
381
382
 private:
383
  const char* category_;
384
  const char* name_;
385
  void* id_;
386
};
387
388
namespace heap {
389
390
void DeleteHeapSnapshot(const v8::HeapSnapshot* snapshot);
391
using HeapSnapshotPointer =
392
  DeleteFnPtr<const v8::HeapSnapshot, DeleteHeapSnapshot>;
393
394
BaseObjectPtr<AsyncWrap> CreateHeapSnapshotStream(
395
    Environment* env, HeapSnapshotPointer&& snapshot);
396
}  // namespace heap
397
398
namespace fs {
399
std::string Basename(const std::string& str, const std::string& extension);
400
}  // namespace fs
401
402
}  // namespace node
403
404
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
405
406
#endif  // SRC_NODE_INTERNALS_H_