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: 48 49 98.0 %
Date: 2019-10-06 22:30:00 Branches: 31 42 73.8 %

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
3903
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
74
  T* wrap;
75

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

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

3903
  if (err == 0)
84
7796
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
85
7806
  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 WaitForInspectorDisconnect(Environment* env);
94
void ResetStdio();  // Safe to call more than once and from signal handlers.
95
#ifdef __POSIX__
96
void SignalExit(int signal, siginfo_t* info, void* ucontext);
97
#endif
98
99
std::string GetHumanReadableProcessName();
100
void GetHumanReadableProcessName(char (*name)[1024]);
101
102
void InitializeContextRuntime(v8::Local<v8::Context>);
103
104
namespace task_queue {
105
void PromiseRejectCallback(v8::PromiseRejectMessage message);
106
}  // namespace task_queue
107
108
14769
class NodeArrayBufferAllocator : public ArrayBufferAllocator {
109
 public:
110
5209
  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
111
112
  void* Allocate(size_t size) override;  // Defined in src/node.cc
113
550171
  void* AllocateUninitialized(size_t size) override
114
550171
    { return node::UncheckedMalloc(size); }
115
1451314
  void Free(void* data, size_t) override { free(data); }
116
324309
  virtual void* Reallocate(void* data, size_t old_size, size_t size) {
117
    return static_cast<void*>(
118
324309
        UncheckedRealloc<char>(static_cast<char*>(data), size));
119
  }
120
535
  virtual void RegisterPointer(void* data, size_t size) {}
121
11
  virtual void UnregisterPointer(void* data, size_t size) {}
122
123
5219
  NodeArrayBufferAllocator* GetImpl() final { return this; }
124
125
 private:
126
  uint32_t zero_fill_field_ = 1;  // Boolean but exposed as uint32 to JS land.
127
};
128
129
2
class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator {
130
 public:
131
  ~DebuggingArrayBufferAllocator() override;
132
  void* Allocate(size_t size) override;
133
  void* AllocateUninitialized(size_t size) override;
134
  void Free(void* data, size_t size) override;
135
  void* Reallocate(void* data, size_t old_size, size_t size) override;
136
  void RegisterPointer(void* data, size_t size) override;
137
  void UnregisterPointer(void* data, size_t size) override;
138
139
 private:
140
  void RegisterPointerInternal(void* data, size_t size);
141
  void UnregisterPointerInternal(void* data, size_t size);
142
  Mutex mutex_;
143
  std::unordered_map<void*, size_t> allocations_;
144
};
145
146
namespace Buffer {
147
v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
148
v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
149
// Takes ownership of |data|.
150
v8::MaybeLocal<v8::Object> New(Environment* env,
151
                               char* data,
152
                               size_t length,
153
                               void (*callback)(char* data, void* hint),
154
                               void* hint);
155
// Takes ownership of |data|.  Must allocate |data| with the current Isolate's
156
// ArrayBuffer::Allocator().
157
v8::MaybeLocal<v8::Object> New(Environment* env,
158
                               char* data,
159
                               size_t length,
160
                               bool uses_malloc);
161
162
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
163
// Utf8Value and TwoByteValue).
164
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
165
// changed.
166
// If |buf| contains actual data, this method takes ownership of |buf|'s
167
// underlying buffer. However, |buf| itself can be reused even after this call,
168
// but its capacity, if increased through AllocateSufficientStorage, is not
169
// guaranteed to stay the same.
170
template <typename T>
171
7338
static v8::MaybeLocal<v8::Object> New(Environment* env,
172
                                      MaybeStackBuffer<T>* buf) {
173
  v8::MaybeLocal<v8::Object> ret;
174
7338
  char* src = reinterpret_cast<char*>(buf->out());
175
7338
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
176
177

7338
  if (buf->IsAllocated())
178
2
    ret = New(env, src, len_in_bytes, true);
179

7336
  else if (!buf->IsInvalidated())
180
7336
    ret = Copy(env, src, len_in_bytes);
181
182

7338
  if (ret.IsEmpty())
183
    return ret;
184
185

7338
  if (buf->IsAllocated())
186
2
    buf->Release();
187
188
7338
  return ret;
189
}
190
}  // namespace Buffer
191
192
v8::MaybeLocal<v8::Value> InternalMakeCallback(
193
    Environment* env,
194
    v8::Local<v8::Object> recv,
195
    const v8::Local<v8::Function> callback,
196
    int argc,
197
    v8::Local<v8::Value> argv[],
198
    async_context asyncContext);
199
200
class InternalCallbackScope {
201
 public:
202
  // Tell the constructor whether its `object` parameter may be empty or not.
203
  enum ResourceExpectation { kRequireResource, kAllowEmptyResource };
204
  InternalCallbackScope(Environment* env,
205
                        v8::Local<v8::Object> object,
206
                        const async_context& asyncContext,
207
                        ResourceExpectation expect = kRequireResource);
208
  // Utility that can be used by AsyncWrap classes.
209
  explicit InternalCallbackScope(AsyncWrap* async_wrap);
210
  ~InternalCallbackScope();
211
  void Close();
212
213
2353101
  inline bool Failed() const { return failed_; }
214
588
  inline void MarkAsFailed() { failed_ = true; }
215
216
 private:
217
  Environment* env_;
218
  async_context async_context_;
219
  v8::Local<v8::Object> object_;
220
  AsyncCallbackScope callback_scope_;
221
  bool failed_ = false;
222
  bool pushed_ids_ = false;
223
  bool closed_ = false;
224
};
225
226
class DebugSealHandleScope {
227
 public:
228
1133186
  explicit inline DebugSealHandleScope(v8::Isolate* isolate)
229
#ifdef DEBUG
230
    : actual_scope_(isolate)
231
#endif
232
1133186
  {}
233
234
 private:
235
#ifdef DEBUG
236
  v8::SealHandleScope actual_scope_;
237
#endif
238
};
239
240
class ThreadPoolWork {
241
 public:
242
2523
  explicit inline ThreadPoolWork(Environment* env) : env_(env) {
243
2523
    CHECK_NOT_NULL(env);
244
2523
  }
245
2515
  inline virtual ~ThreadPoolWork() = default;
246
247
  inline void ScheduleWork();
248
  inline int CancelWork();
249
250
  virtual void DoThreadPoolWork() = 0;
251
  virtual void AfterThreadPoolWork(int status) = 0;
252
253
 private:
254
  Environment* env_;
255
  uv_work_t work_req_;
256
};
257
258
#define TRACING_CATEGORY_NODE "node"
259
#define TRACING_CATEGORY_NODE1(one)                                           \
260
    TRACING_CATEGORY_NODE ","                                                 \
261
    TRACING_CATEGORY_NODE "." #one
262
#define TRACING_CATEGORY_NODE2(one, two)                                      \
263
    TRACING_CATEGORY_NODE ","                                                 \
264
    TRACING_CATEGORY_NODE "." #one ","                                        \
265
    TRACING_CATEGORY_NODE "." #one "." #two
266
267
// Functions defined in node.cc that are exposed via the bootstrapper object
268
269
#if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__)
270
#define NODE_IMPLEMENTS_POSIX_CREDENTIALS 1
271
#endif  // __POSIX__ && !defined(__ANDROID__) && !defined(__CloudABI__)
272
273
namespace credentials {
274
bool SafeGetenv(const char* key, std::string* text, Environment* env = nullptr);
275
}  // namespace credentials
276
277
void DefineZlibConstants(v8::Local<v8::Object> target);
278
v8::Isolate* NewIsolate(v8::Isolate::CreateParams* params,
279
                        uv_loop_t* event_loop,
280
                        MultiIsolatePlatform* platform);
281
v8::MaybeLocal<v8::Value> StartExecution(Environment* env,
282
                                         const char* main_script_id);
283
v8::MaybeLocal<v8::Object> GetPerContextExports(v8::Local<v8::Context> context);
284
v8::MaybeLocal<v8::Value> ExecuteBootstrapper(
285
    Environment* env,
286
    const char* id,
287
    std::vector<v8::Local<v8::String>>* parameters,
288
    std::vector<v8::Local<v8::Value>>* arguments);
289
void MarkBootstrapComplete(const v8::FunctionCallbackInfo<v8::Value>& args);
290
291
9698
struct InitializationResult {
292
  int exit_code = 0;
293
  std::vector<std::string> args;
294
  std::vector<std::string> exec_args;
295
  bool early_return = false;
296
};
297
InitializationResult InitializeOncePerProcess(int argc, char** argv);
298
void TearDownOncePerProcess();
299
enum class IsolateSettingCategories { kErrorHandlers, kMisc };
300
void SetIsolateUpForNode(v8::Isolate* isolate, IsolateSettingCategories cat);
301
void SetIsolateCreateParamsForNode(v8::Isolate::CreateParams* params);
302
303
#if HAVE_INSPECTOR
304
namespace profiler {
305
void StartProfilers(Environment* env);
306
void EndStartedProfilers(Environment* env);
307
}
308
#endif  // HAVE_INSPECTOR
309
310
#ifdef _WIN32
311
typedef SYSTEMTIME TIME_TYPE;
312
#else  // UNIX, OSX
313
typedef struct tm TIME_TYPE;
314
#endif
315
316
double GetCurrentTimeInMicroseconds();
317
int WriteFileSync(const char* path, uv_buf_t buf);
318
int WriteFileSync(v8::Isolate* isolate,
319
                  const char* path,
320
                  v8::Local<v8::String> string);
321
322
25
class DiagnosticFilename {
323
 public:
324
  static void LocalTime(TIME_TYPE* tm_struct);
325
326
  inline DiagnosticFilename(Environment* env,
327
                            const char* prefix,
328
                            const char* ext);
329
330
  inline DiagnosticFilename(uint64_t thread_id,
331
                            const char* prefix,
332
                            const char* ext);
333
334
  inline const char* operator*() const;
335
336
 private:
337
  static std::string MakeFilename(
338
      uint64_t thread_id,
339
      const char* prefix,
340
      const char* ext);
341
342
  std::string filename_;
343
};
344
345
class TraceEventScope {
346
 public:
347
534834
  TraceEventScope(const char* category,
348
                  const char* name,
349
534834
                  void* id) : category_(category), name_(name), id_(id) {
350

1069666
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
351
534833
  }
352
534796
  ~TraceEventScope() {
353

1069592
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
354
534796
  }
355
356
 private:
357
  const char* category_;
358
  const char* name_;
359
  void* id_;
360
};
361
362
}  // namespace node
363
364
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
365
366
#endif  // SRC_NODE_INTERNALS_H_