GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/hooks.cc Lines: 106 111 95.5 %
Date: 2022-09-25 04:23:55 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
6380
void RunAtExit(Environment* env) {
22
6380
  env->RunAtExitCallbacks();
23
6380
}
24
25
12604
void AtExit(Environment* env, void (*cb)(void* arg), void* arg) {
26
12604
  CHECK_NOT_NULL(env);
27
12604
  env->AtExit(cb, arg);
28
12604
}
29
30
void EmitBeforeExit(Environment* env) {
31
  USE(EmitProcessBeforeExit(env));
32
}
33
34
5295
Maybe<bool> EmitProcessBeforeExit(Environment* env) {
35

15472
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "BeforeExit");
36
5295
  if (!env->destroy_async_id_list()->empty())
37
246
    AsyncWrap::DestroyAsyncIdsCallback(env);
38
39
10588
  HandleScope handle_scope(env->isolate());
40
5295
  Local<Context> context = env->context();
41
5295
  Context::Scope context_scope(context);
42
43
  Local<Value> exit_code_v;
44
15885
  if (!env->process_object()->Get(context, env->exit_code_string())
45
5295
      .ToLocal(&exit_code_v)) return Nothing<bool>();
46
47
  Local<Integer> exit_code;
48
10588
  if (!exit_code_v->ToInteger(context).ToLocal(&exit_code)) {
49
    return Nothing<bool>();
50
  }
51
52
5294
  return ProcessEmit(env, "beforeExit", exit_code).IsEmpty() ?
53
5292
      Nothing<bool>() : Just(true);
54
}
55
56
int EmitExit(Environment* env) {
57
  return EmitProcessExit(env).FromMaybe(1);
58
}
59
60
5262
Maybe<int> EmitProcessExit(Environment* env) {
61
  // process.emit('exit')
62
5262
  Isolate* isolate = env->isolate();
63
10514
  HandleScope handle_scope(isolate);
64
5262
  Local<Context> context = env->context();
65
5262
  Context::Scope context_scope(context);
66
5262
  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
5262
  env->set_exiting(true);
73
74
5262
  Local<String> exit_code = env->exit_code_string();
75
  Local<Value> code_v;
76
  int code;
77
5262
  if (!process_object->Get(context, exit_code).ToLocal(&code_v) ||
78
10524
      !code_v->Int32Value(context).To(&code) ||
79
15776
      ProcessEmit(env, "exit", Integer::New(isolate, code)).IsEmpty() ||
80
      // Reload exit code, it may be changed by `emit('exit')`
81

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

15746
      !code_v->Int32Value(context).To(&code)) {
83
5
    return Nothing<int>();
84
  }
85
86
5247
  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
3
void RequestInterrupt(Environment* env, void (*fun)(void* arg), void* arg) {
170
3
  env->RequestInterrupt([fun, arg](Environment* env) {
171
    // Disallow JavaScript execution during interrupt.
172
    Isolate::DisallowJavascriptExecutionScope scope(
173
        env->isolate(),
174
4
        Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
175
3
    fun(arg);
176
1
  });
177
3
}
178
179
2
async_id AsyncHooksGetExecutionAsyncId(Isolate* isolate) {
180
2
  Environment* env = Environment::GetCurrent(isolate);
181
2
  if (env == nullptr) return -1;
182
2
  return env->execution_async_id();
183
}
184
185
2
async_id AsyncHooksGetTriggerAsyncId(Isolate* isolate) {
186
2
  Environment* env = Environment::GetCurrent(isolate);
187
2
  if (env == nullptr) return -1;
188
2
  return env->trigger_async_id();
189
}
190
191
192
542
async_context EmitAsyncInit(Isolate* isolate,
193
                            Local<Object> resource,
194
                            const char* name,
195
                            async_id trigger_async_id) {
196
1084
  HandleScope handle_scope(isolate);
197
  Local<String> type =
198
542
      String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
199
542
          .ToLocalChecked();
200
542
  return EmitAsyncInit(isolate, resource, type, trigger_async_id);
201
}
202
203
542
async_context EmitAsyncInit(Isolate* isolate,
204
                            Local<Object> resource,
205
                            Local<String> name,
206
                            async_id trigger_async_id) {
207
542
  DebugSealHandleScope handle_scope(isolate);
208
542
  Environment* env = Environment::GetCurrent(isolate);
209
542
  CHECK_NOT_NULL(env);
210
211
  // Initialize async context struct
212
542
  if (trigger_async_id == -1)
213
539
    trigger_async_id = env->get_default_trigger_async_id();
214
215
  async_context context = {
216
542
    env->new_async_id(),  // async_id_
217
    trigger_async_id  // trigger_async_id_
218
542
  };
219
220
  // Run init hooks
221
542
  AsyncWrap::EmitAsyncInit(env, resource, name, context.async_id,
222
                           context.trigger_async_id);
223
224
542
  return context;
225
}
226
227
3
void EmitAsyncDestroy(Isolate* isolate, async_context asyncContext) {
228
3
  EmitAsyncDestroy(Environment::GetCurrent(isolate), asyncContext);
229
3
}
230
231
538
void EmitAsyncDestroy(Environment* env, async_context asyncContext) {
232
538
  AsyncWrap::EmitDestroy(env, asyncContext.async_id);
233
538
}
234
235
}  // namespace node