GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_watchdog.cc Lines: 166 197 84.3 %
Date: 2022-07-29 04:16:17 Branches: 37 68 54.4 %

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
#include <algorithm>
23
24
#include "async_wrap-inl.h"
25
#include "debug_utils-inl.h"
26
#include "env-inl.h"
27
#include "node_errors.h"
28
#include "node_internals.h"
29
#include "node_watchdog.h"
30
#include "util-inl.h"
31
32
namespace node {
33
34
using v8::Context;
35
using v8::FunctionCallbackInfo;
36
using v8::FunctionTemplate;
37
using v8::Local;
38
using v8::Object;
39
using v8::Value;
40
41
18
Watchdog::Watchdog(v8::Isolate* isolate, uint64_t ms, bool* timed_out)
42
18
    : isolate_(isolate), timed_out_(timed_out) {
43
44
  int rc;
45
18
  rc = uv_loop_init(&loop_);
46
18
  if (rc != 0) {
47
    FatalError("node::Watchdog::Watchdog()",
48
               "Failed to initialize uv loop.");
49
  }
50
51
18
  rc = uv_async_init(&loop_, &async_, [](uv_async_t* signal) {
52
5
    Watchdog* w = ContainerOf(&Watchdog::async_, signal);
53
5
    uv_stop(&w->loop_);
54
5
  });
55
56
18
  CHECK_EQ(0, rc);
57
58
18
  rc = uv_timer_init(&loop_, &timer_);
59
18
  CHECK_EQ(0, rc);
60
61
18
  rc = uv_timer_start(&timer_, &Watchdog::Timer, ms, 0);
62
18
  CHECK_EQ(0, rc);
63
64
18
  rc = uv_thread_create(&thread_, &Watchdog::Run, this);
65
18
  CHECK_EQ(0, rc);
66
18
}
67
68
69
36
Watchdog::~Watchdog() {
70
18
  uv_async_send(&async_);
71
18
  uv_thread_join(&thread_);
72
73
18
  uv_close(reinterpret_cast<uv_handle_t*>(&async_), nullptr);
74
75
  // UV_RUN_DEFAULT so that libuv has a chance to clean up.
76
18
  uv_run(&loop_, UV_RUN_DEFAULT);
77
78
18
  CheckedUvLoopClose(&loop_);
79
18
}
80
81
82
18
void Watchdog::Run(void* arg) {
83
18
  Watchdog* wd = static_cast<Watchdog*>(arg);
84
85
  // UV_RUN_DEFAULT the loop will be stopped either by the async or the
86
  // timer handle.
87
18
  uv_run(&wd->loop_, UV_RUN_DEFAULT);
88
89
  // Loop ref count reaches zero when both handles are closed.
90
  // Close the timer handle on this side and let ~Watchdog() close async_
91
18
  uv_close(reinterpret_cast<uv_handle_t*>(&wd->timer_), nullptr);
92
18
}
93
94
13
void Watchdog::Timer(uv_timer_t* timer) {
95
13
  Watchdog* w = ContainerOf(&Watchdog::timer_, timer);
96
13
  *w->timed_out_ = true;
97
13
  w->isolate()->TerminateExecution();
98
13
  uv_stop(&w->loop_);
99
13
}
100
101
102
1198
SigintWatchdog::SigintWatchdog(
103
1198
  v8::Isolate* isolate, bool* received_signal)
104
1198
    : isolate_(isolate), received_signal_(received_signal) {
105
2396
  Mutex::ScopedLock lock(SigintWatchdogHelper::GetInstanceActionMutex());
106
  // Register this watchdog with the global SIGINT/Ctrl+C listener.
107
1198
  SigintWatchdogHelper::GetInstance()->Register(this);
108
  // Start the helper thread, if that has not already happened.
109
1198
  SigintWatchdogHelper::GetInstance()->Start();
110
1198
}
111
112
113
2390
SigintWatchdog::~SigintWatchdog() {
114
4780
  Mutex::ScopedLock lock(SigintWatchdogHelper::GetInstanceActionMutex());
115
2390
  SigintWatchdogHelper::GetInstance()->Unregister(this);
116
2390
  SigintWatchdogHelper::GetInstance()->Stop();
117
}
118
119
11
SignalPropagation SigintWatchdog::HandleSigint() {
120
11
  *received_signal_ = true;
121
11
  isolate_->TerminateExecution();
122
11
  return SignalPropagation::kStopPropagation;
123
}
124
125
2
void TraceSigintWatchdog::Init(Environment* env, Local<Object> target) {
126
2
  Local<FunctionTemplate> constructor = env->NewFunctionTemplate(New);
127
4
  constructor->InstanceTemplate()->SetInternalFieldCount(
128
      TraceSigintWatchdog::kInternalFieldCount);
129
2
  constructor->Inherit(HandleWrap::GetConstructorTemplate(env));
130
131
2
  env->SetProtoMethod(constructor, "start", Start);
132
2
  env->SetProtoMethod(constructor, "stop", Stop);
133
134
2
  env->SetConstructorFunction(target, "TraceSigintWatchdog", constructor);
135
2
}
136
137
1
void TraceSigintWatchdog::New(const FunctionCallbackInfo<Value>& args) {
138
  // This constructor should not be exposed to public javascript.
139
  // Therefore we assert that we are not trying to call this as a
140
  // normal function.
141
1
  CHECK(args.IsConstructCall());
142
1
  Environment* env = Environment::GetCurrent(args);
143
1
  new TraceSigintWatchdog(env, args.This());
144
1
}
145
146
2
void TraceSigintWatchdog::Start(const FunctionCallbackInfo<Value>& args) {
147
  TraceSigintWatchdog* watchdog;
148
2
  ASSIGN_OR_RETURN_UNWRAP(&watchdog, args.Holder());
149
4
  Mutex::ScopedLock lock(SigintWatchdogHelper::GetInstanceActionMutex());
150
  // Register this watchdog with the global SIGINT/Ctrl+C listener.
151
2
  SigintWatchdogHelper::GetInstance()->Register(watchdog);
152
  // Start the helper thread, if that has not already happened.
153
2
  int r = SigintWatchdogHelper::GetInstance()->Start();
154
2
  CHECK_EQ(r, 0);
155
}
156
157
2
void TraceSigintWatchdog::Stop(const FunctionCallbackInfo<Value>& args) {
158
  TraceSigintWatchdog* watchdog;
159
2
  ASSIGN_OR_RETURN_UNWRAP(&watchdog, args.Holder());
160
4
  Mutex::ScopedLock lock(SigintWatchdogHelper::GetInstanceActionMutex());
161
2
  SigintWatchdogHelper::GetInstance()->Unregister(watchdog);
162
2
  SigintWatchdogHelper::GetInstance()->Stop();
163
}
164
165
1
TraceSigintWatchdog::TraceSigintWatchdog(Environment* env, Local<Object> object)
166
    : HandleWrap(env,
167
                 object,
168
1
                 reinterpret_cast<uv_handle_t*>(&handle_),
169
1
                 AsyncWrap::PROVIDER_SIGINTWATCHDOG) {
170
1
  int r = uv_async_init(env->event_loop(), &handle_, [](uv_async_t* handle) {
171
    TraceSigintWatchdog* watchdog =
172
        ContainerOf(&TraceSigintWatchdog::handle_, handle);
173
    watchdog->signal_flag_ = SignalFlags::FromIdle;
174
    watchdog->HandleInterrupt();
175
1
  });
176
1
  CHECK_EQ(r, 0);
177
1
  uv_unref(reinterpret_cast<uv_handle_t*>(&handle_));
178
1
}
179
180
SignalPropagation TraceSigintWatchdog::HandleSigint() {
181
  /**
182
   * In case of uv loop polling, i.e. no JS currently running, activate the
183
   * loop to run a piece of JS code to trigger interruption.
184
   */
185
  CHECK_EQ(uv_async_send(&handle_), 0);
186
  env()->isolate()->RequestInterrupt(
187
      [](v8::Isolate* isolate, void* data) {
188
        TraceSigintWatchdog* self = static_cast<TraceSigintWatchdog*>(data);
189
        if (self->signal_flag_ == SignalFlags::None) {
190
          self->signal_flag_ = SignalFlags::FromInterrupt;
191
        }
192
        self->HandleInterrupt();
193
      },
194
      this);
195
  return SignalPropagation::kContinuePropagation;
196
}
197
198
void TraceSigintWatchdog::HandleInterrupt() {
199
  // Do not nest interrupts.
200
  if (interrupting) {
201
    return;
202
  }
203
  interrupting = true;
204
  if (signal_flag_ == SignalFlags::None) {
205
    return;
206
  }
207
  Environment* env_ = env();
208
  // FIXME: Before
209
  // https://github.com/nodejs/node/pull/29207#issuecomment-527667993 get
210
  // fixed, additional JavaScript code evaluation shall be prevented from
211
  // running during interruption.
212
  FPrintF(stderr,
213
      "KEYBOARD_INTERRUPT: Script execution was interrupted by `SIGINT`\n");
214
  if (signal_flag_ == SignalFlags::FromInterrupt) {
215
    PrintStackTrace(env_->isolate(),
216
                    v8::StackTrace::CurrentStackTrace(
217
                        env_->isolate(), 10, v8::StackTrace::kDetailed));
218
  }
219
  signal_flag_ = SignalFlags::None;
220
  interrupting = false;
221
222
  Mutex::ScopedLock lock(SigintWatchdogHelper::GetInstanceActionMutex());
223
  SigintWatchdogHelper::GetInstance()->Unregister(this);
224
  SigintWatchdogHelper::GetInstance()->Stop();
225
  raise(SIGINT);
226
}
227
228
#ifdef __POSIX__
229
616
void* SigintWatchdogHelper::RunSigintWatchdog(void* arg) {
230
  // Inside the helper thread.
231
  bool is_stopping;
232
233
14
  do {
234
616
    uv_sem_wait(&instance.sem_);
235
616
    is_stopping = InformWatchdogsAboutSignal();
236
616
  } while (!is_stopping);
237
238
602
  return nullptr;
239
}
240
241
14
void SigintWatchdogHelper::HandleSignal(int signum,
242
                                        siginfo_t* info,
243
                                        void* ucontext) {
244
14
  uv_sem_post(&instance.sem_);
245
14
}
246
247
#else
248
249
// Windows starts a separate thread for executing the handler, so no extra
250
// helper thread is required.
251
BOOL WINAPI SigintWatchdogHelper::WinCtrlCHandlerRoutine(DWORD dwCtrlType) {
252
  if (!instance.watchdog_disabled_ &&
253
      (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT)) {
254
    InformWatchdogsAboutSignal();
255
256
    // Return true because the signal has been handled.
257
    return TRUE;
258
  } else {
259
    return FALSE;
260
  }
261
}
262
#endif
263
264
265
616
bool SigintWatchdogHelper::InformWatchdogsAboutSignal() {
266
616
  Mutex::ScopedLock list_lock(instance.list_mutex_);
267
268
616
  bool is_stopping = false;
269
#ifdef __POSIX__
270
616
  is_stopping = instance.stopping_;
271
#endif
272
273
  // If there are no listeners and the helper thread has been awoken by a signal
274
  // (= not when stopping it), indicate that by setting has_pending_signal_.
275

616
  if (instance.watchdogs_.empty() && !is_stopping) {
276
3
    instance.has_pending_signal_ = true;
277
  }
278
279
616
  for (auto it = instance.watchdogs_.rbegin(); it != instance.watchdogs_.rend();
280
       it++) {
281
11
    SignalPropagation wp = (*it)->HandleSigint();
282
11
    if (wp == SignalPropagation::kStopPropagation) {
283
11
      break;
284
    }
285
  }
286
287
616
  return is_stopping;
288
}
289
290
291
1395
int SigintWatchdogHelper::Start() {
292
2790
  Mutex::ScopedLock lock(mutex_);
293
294
1395
  if (start_stop_count_++ > 0) {
295
793
    return 0;
296
  }
297
298
#ifdef __POSIX__
299
602
  CHECK_EQ(has_running_thread_, false);
300
602
  has_pending_signal_ = false;
301
602
  stopping_ = false;
302
303
  sigset_t sigmask;
304
602
  sigfillset(&sigmask);
305
  sigset_t savemask;
306
602
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, &savemask));
307
602
  sigmask = savemask;
308
602
  int ret = pthread_create(&thread_, nullptr, RunSigintWatchdog, nullptr);
309
602
  CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr));
310
602
  if (ret != 0) {
311
    return ret;
312
  }
313
602
  has_running_thread_ = true;
314
315
602
  RegisterSignalHandler(SIGINT, HandleSignal);
316
#else
317
  if (watchdog_disabled_) {
318
    watchdog_disabled_ = false;
319
  } else {
320
    SetConsoleCtrlHandler(WinCtrlCHandlerRoutine, TRUE);
321
  }
322
#endif
323
324
602
  return 0;
325
}
326
327
328
6744
bool SigintWatchdogHelper::Stop() {
329
  bool had_pending_signal;
330
13488
  Mutex::ScopedLock lock(mutex_);
331
332
  {
333
6744
    Mutex::ScopedLock list_lock(list_mutex_);
334
335
6744
    had_pending_signal = has_pending_signal_;
336
337
6744
    if (--start_stop_count_ > 0) {
338
790
      has_pending_signal_ = false;
339
790
      return had_pending_signal;
340
    }
341
342
#ifdef __POSIX__
343
    // Set stopping now because it's only protected by list_mutex_.
344
5954
    stopping_ = true;
345
#endif
346
347
5954
    watchdogs_.clear();
348
  }
349
350
#ifdef __POSIX__
351
5954
  if (!has_running_thread_) {
352
5352
    has_pending_signal_ = false;
353
5352
    return had_pending_signal;
354
  }
355
356
  // Wake up the helper thread.
357
602
  uv_sem_post(&sem_);
358
359
  // Wait for the helper thread to finish.
360
602
  CHECK_EQ(0, pthread_join(thread_, nullptr));
361
602
  has_running_thread_ = false;
362
363
602
  RegisterSignalHandler(SIGINT, SignalExit, true);
364
#else
365
  watchdog_disabled_ = true;
366
#endif
367
368
602
  had_pending_signal = has_pending_signal_;
369
602
  has_pending_signal_ = false;
370
371
602
  return had_pending_signal;
372
}
373
374
375
4
bool SigintWatchdogHelper::HasPendingSignal() {
376
4
  Mutex::ScopedLock lock(list_mutex_);
377
378
4
  return has_pending_signal_;
379
}
380
381
1200
void SigintWatchdogHelper::Register(SigintWatchdogBase* wd) {
382
2400
  Mutex::ScopedLock lock(list_mutex_);
383
384
1200
  watchdogs_.push_back(wd);
385
1200
}
386
387
1197
void SigintWatchdogHelper::Unregister(SigintWatchdogBase* wd) {
388
1197
  Mutex::ScopedLock lock(list_mutex_);
389
390
1197
  auto it = std::find(watchdogs_.begin(), watchdogs_.end(), wd);
391
392
1197
  CHECK_NE(it, watchdogs_.end());
393
1197
  watchdogs_.erase(it);
394
1197
}
395
396
397
5355
SigintWatchdogHelper::SigintWatchdogHelper()
398
    : start_stop_count_(0),
399
5355
      has_pending_signal_(false) {
400
#ifdef __POSIX__
401
5355
  has_running_thread_ = false;
402
5355
  stopping_ = false;
403
5355
  CHECK_EQ(0, uv_sem_init(&sem_, 0));
404
#else
405
  watchdog_disabled_ = false;
406
#endif
407
5355
}
408
409
410
5355
SigintWatchdogHelper::~SigintWatchdogHelper() {
411
5355
  start_stop_count_ = 0;
412
5355
  Stop();
413
414
#ifdef __POSIX__
415
5355
  CHECK_EQ(has_running_thread_, false);
416
5355
  uv_sem_destroy(&sem_);
417
#endif
418
5355
}
419
420
SigintWatchdogHelper SigintWatchdogHelper::instance;
421
Mutex SigintWatchdogHelper::instance_action_mutex_;
422
423
namespace watchdog {
424
2
static void Initialize(Local<Object> target,
425
                       Local<Value> unused,
426
                       Local<Context> context,
427
                       void* priv) {
428
2
  Environment* env = Environment::GetCurrent(context);
429
2
  TraceSigintWatchdog::Init(env, target);
430
2
}
431
}  // namespace watchdog
432
433
}  // namespace node
434
435
5355
NODE_MODULE_CONTEXT_AWARE_INTERNAL(watchdog, node::watchdog::Initialize)