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 49 95.9 %
Date: 2019-07-28 22:34:34 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
3885
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
74
  T* wrap;
75

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

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

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

534
  if (buf->IsAllocated())
176
2
    ret = New(env, src, len_in_bytes, true);
177

532
  else if (!buf->IsInvalidated())
178
532
    ret = Copy(env, src, len_in_bytes);
179
180

534
  if (ret.IsEmpty())
181
    return ret;
182
183

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

1024328
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
349
512164
  }
350
512127
  ~TraceEventScope() {
351

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