GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/hooks.cc Lines: 100 105 95.2 %
Date: 2022-08-06 04:16:36 Branches: 31 46 67.4 %

Line Branch Exec Source
1
#include "env-inl.h"
2
#include "node_internals.h"
3
#include "node_process-inl.h"
4
#include "async_wrap.h"
5
6
namespace node {
7
8
using v8::Context;
9
using v8::HandleScope;
10
using v8::Integer;
11
using v8::Isolate;
12
using v8::Just;
13
using v8::Local;
14
using v8::Maybe;
15
using v8::NewStringType;
16
using v8::Nothing;
17
using v8::Object;
18
using v8::String;
19
using v8::Value;
20
21
6185
void RunAtExit(Environment* env) {
22
6185
  env->RunAtExitCallbacks();
23
6185
}
24
25
12178
void AtExit(Environment* env, void (*cb)(void* arg), void* arg) {
26
12178
  CHECK_NOT_NULL(env);
27
12178
  env->AtExit(cb, arg);
28
12178
}
29
30
void EmitBeforeExit(Environment* env) {
31
  USE(EmitProcessBeforeExit(env));
32
}
33
34
5251
Maybe<bool> EmitProcessBeforeExit(Environment* env) {
35

15307
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "BeforeExit");
36
5251
  if (!env->destroy_async_id_list()->empty())
37
218
    AsyncWrap::DestroyAsyncIdsCallback(env);
38
39
10500
  HandleScope handle_scope(env->isolate());
40
5251
  Local<Context> context = env->context();
41
5251
  Context::Scope context_scope(context);
42
43
  Local<Value> exit_code_v;
44
15753
  if (!env->process_object()->Get(context, env->exit_code_string())
45
5251
      .ToLocal(&exit_code_v)) return Nothing<bool>();
46
47
  Local<Integer> exit_code;
48
10500
  if (!exit_code_v->ToInteger(context).ToLocal(&exit_code)) {
49
    return Nothing<bool>();
50
  }
51
52
5250
  return ProcessEmit(env, "beforeExit", exit_code).IsEmpty() ?
53
5248
      Nothing<bool>() : Just(true);
54
}
55
56
int EmitExit(Environment* env) {
57
  return EmitProcessExit(env).FromMaybe(1);
58
}
59
60
5218
Maybe<int> EmitProcessExit(Environment* env) {
61
  // process.emit('exit')
62
5218
  Isolate* isolate = env->isolate();
63
10426
  HandleScope handle_scope(isolate);
64
5218
  Local<Context> context = env->context();
65
5218
  Context::Scope context_scope(context);
66
5218
  Local<Object> process_object = env->process_object();
67
68
  // TODO(addaleax): It might be nice to share process.exitCode via
69
  // getter/setter pairs that pass data directly to the native side, so that we
70
  // don't manually have to read and write JS properties here. These getters
71
  // could use e.g. a typed array for performance.
72
5218
  env->set_exiting(true);
73
74
5218
  Local<String> exit_code = env->exit_code_string();
75
  Local<Value> code_v;
76
  int code;
77
5218
  if (!process_object->Get(context, exit_code).ToLocal(&code_v) ||
78
10436
      !code_v->Int32Value(context).To(&code) ||
79
15644
      ProcessEmit(env, "exit", Integer::New(isolate, code)).IsEmpty() ||
80
      // Reload exit code, it may be changed by `emit('exit')`
81

20838
      !process_object->Get(context, exit_code).ToLocal(&code_v) ||
82

15620
      !code_v->Int32Value(context).To(&code)) {
83
2
    return Nothing<int>();
84
  }
85
86
5206
  return Just(code);
87
}
88
89
typedef void (*CleanupHook)(void* arg);
90
typedef void (*AsyncCleanupHook)(void* arg, void(*)(void*), void*);
91
92
struct AsyncCleanupHookInfo final {
93
  Environment* env;
94
  AsyncCleanupHook fun;
95
  void* arg;
96
  bool started = false;
97
  // Use a self-reference to make sure the storage is kept alive while the
98
  // cleanup hook is registered but not yet finished.
99
  std::shared_ptr<AsyncCleanupHookInfo> self;
100
};
101
102
// Opaque type that is basically an alias for `shared_ptr<AsyncCleanupHookInfo>`
103
// (but not publicly so for easier ABI/API changes). In particular,
104
// std::shared_ptr does not generally maintain a consistent ABI even on a
105
// specific platform.
106
struct ACHHandle final {
107
  std::shared_ptr<AsyncCleanupHookInfo> info;
108
};
109
// This is implemented as an operator on a struct because otherwise you can't
110
// default-initialize AsyncCleanupHookHandle, because in C++ for a
111
// std::unique_ptr to be default-initializable the deleter type also needs
112
// to be default-initializable; in particular, function types don't satisfy
113
// this.
114
10
void DeleteACHHandle::operator ()(ACHHandle* handle) const { delete handle; }
115
116
41
void AddEnvironmentCleanupHook(Isolate* isolate,
117
                               CleanupHook fun,
118
                               void* arg) {
119
41
  Environment* env = Environment::GetCurrent(isolate);
120
41
  CHECK_NOT_NULL(env);
121
41
  env->AddCleanupHook(fun, arg);
122
41
}
123
124
27
void RemoveEnvironmentCleanupHook(Isolate* isolate,
125
                                  CleanupHook fun,
126
                                  void* arg) {
127
27
  Environment* env = Environment::GetCurrent(isolate);
128
27
  CHECK_NOT_NULL(env);
129
27
  env->RemoveCleanupHook(fun, arg);
130
27
}
131
132
6
static void FinishAsyncCleanupHook(void* arg) {
133
6
  AsyncCleanupHookInfo* info = static_cast<AsyncCleanupHookInfo*>(arg);
134
12
  std::shared_ptr<AsyncCleanupHookInfo> keep_alive = info->self;
135
136
6
  info->env->DecreaseWaitingRequestCounter();
137
6
  info->self.reset();
138
6
}
139
140
6
static void RunAsyncCleanupHook(void* arg) {
141
6
  AsyncCleanupHookInfo* info = static_cast<AsyncCleanupHookInfo*>(arg);
142
6
  info->env->IncreaseWaitingRequestCounter();
143
6
  info->started = true;
144
6
  info->fun(info->arg, FinishAsyncCleanupHook, info);
145
6
}
146
147
10
ACHHandle* AddEnvironmentCleanupHookInternal(
148
    Isolate* isolate,
149
    AsyncCleanupHook fun,
150
    void* arg) {
151
10
  Environment* env = Environment::GetCurrent(isolate);
152
10
  CHECK_NOT_NULL(env);
153
10
  auto info = std::make_shared<AsyncCleanupHookInfo>();
154
10
  info->env = env;
155
10
  info->fun = fun;
156
10
  info->arg = arg;
157
10
  info->self = info;
158
10
  env->AddCleanupHook(RunAsyncCleanupHook, info.get());
159
10
  return new ACHHandle { info };
160
}
161
162
10
void RemoveEnvironmentCleanupHookInternal(
163
    ACHHandle* handle) {
164
10
  if (handle->info->started) return;
165
4
  handle->info->self.reset();
166
4
  handle->info->env->RemoveCleanupHook(RunAsyncCleanupHook, handle->info.get());
167
}
168
169
2
async_id AsyncHooksGetExecutionAsyncId(Isolate* isolate) {
170
2
  Environment* env = Environment::GetCurrent(isolate);
171
2
  if (env == nullptr) return -1;
172
2
  return env->execution_async_id();
173
}
174
175
2
async_id AsyncHooksGetTriggerAsyncId(Isolate* isolate) {
176
2
  Environment* env = Environment::GetCurrent(isolate);
177
2
  if (env == nullptr) return -1;
178
2
  return env->trigger_async_id();
179
}
180
181
182
542
async_context EmitAsyncInit(Isolate* isolate,
183
                            Local<Object> resource,
184
                            const char* name,
185
                            async_id trigger_async_id) {
186
1084
  HandleScope handle_scope(isolate);
187
  Local<String> type =
188
542
      String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
189
542
          .ToLocalChecked();
190
542
  return EmitAsyncInit(isolate, resource, type, trigger_async_id);
191
}
192
193
542
async_context EmitAsyncInit(Isolate* isolate,
194
                            Local<Object> resource,
195
                            Local<String> name,
196
                            async_id trigger_async_id) {
197
542
  DebugSealHandleScope handle_scope(isolate);
198
542
  Environment* env = Environment::GetCurrent(isolate);
199
542
  CHECK_NOT_NULL(env);
200
201
  // Initialize async context struct
202
542
  if (trigger_async_id == -1)
203
539
    trigger_async_id = env->get_default_trigger_async_id();
204
205
  async_context context = {
206
542
    env->new_async_id(),  // async_id_
207
    trigger_async_id  // trigger_async_id_
208
542
  };
209
210
  // Run init hooks
211
542
  AsyncWrap::EmitAsyncInit(env, resource, name, context.async_id,
212
                           context.trigger_async_id);
213
214
542
  return context;
215
}
216
217
3
void EmitAsyncDestroy(Isolate* isolate, async_context asyncContext) {
218
3
  EmitAsyncDestroy(Environment::GetCurrent(isolate), asyncContext);
219
3
}
220
221
538
void EmitAsyncDestroy(Environment* env, async_context asyncContext) {
222
538
  AsyncWrap::EmitDestroy(env, asyncContext.async_id);
223
538
}
224
225
}  // namespace node