debug: activate inspector with _debugProcess

This pull request switches the signal handler to start inspector socket
server instead of the legacy V8 debug protocol.

PR-URL: https://github.com/nodejs/node/pull/11431

Fixes: https://github.com/nodejs/node/issues/8464
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
This commit is contained in:
Eugene Ostroukhov committed 2017-04-06 09:10:29 -07:00
1 parent 47f8f7462f
commit 7599b0ef9d
7 files changed
+968 -691

No files matched your search

+2
View File
@@ -77,9 +77,11 @@
],
'sources': [
'src/inspector_agent.cc',
'src/inspector_io.cc',
'src/inspector_socket.cc',
'src/inspector_socket_server.cc',
'src/inspector_agent.h',
'src/inspector_io.h',
'src/inspector_socket.h',
'src/inspector_socket_server.h',
],
+367 -547
View File
File diff suppressed because it is too large. Load diff
+16 -2
View File
@@ -22,20 +22,28 @@ class Value;
class Message;
} // namespace v8
namespace v8_inspector {
class StringView;
} // namespace v8_inspector
namespace node {
namespace inspector {
class AgentImpl;
class InspectorSessionDelegate {
public:
virtual bool WaitForFrontendMessage() = 0;
virtual void OnMessage(const v8_inspector::StringView& message) = 0;
};
class Agent {
public:
explicit Agent(node::Environment* env);
~Agent();
// Start the inspector agent thread
bool Start(v8::Platform* platform, const char* path,
const DebugOptions& options);
// Stop the inspector agent
void Stop();
bool IsStarted();
@@ -44,8 +52,14 @@ class Agent {
void FatalException(v8::Local<v8::Value> error,
v8::Local<v8::Message> message);
void SchedulePauseOnNextStatement(const std::string& reason);
void Connect(InspectorSessionDelegate* delegate);
void Disconnect();
void Dispatch(const v8_inspector::StringView& message);
InspectorSessionDelegate* delegate();
void RunMessageLoop();
private:
AgentImpl* impl;
friend class AgentImpl;
};
} // namespace inspector
+441
View File
@@ -0,0 +1,441 @@
#include "inspector_io.h"
#include "inspector_socket_server.h"
#include "env.h"
#include "env-inl.h"
#include "node.h"
#include "node_crypto.h"
#include "node_mutex.h"
#include "v8-inspector.h"
#include "util.h"
#include "zlib.h"
#include <sstream>
#include <unicode/unistr.h>
#include <string.h>
#include <vector>
namespace node {
namespace inspector {
namespace {
using v8_inspector::StringBuffer;
using v8_inspector::StringView;
template<typename Transport>
using TransportAndIo = std::pair<Transport*, InspectorIo*>;
std::string GetProcessTitle() {
// uv_get_process_title will trim the title if it is too long.
char title[2048];
int err = uv_get_process_title(title, sizeof(title));
if (err == 0) {
return title;
} else {
return "Node.js";
}
}
// UUID RFC: https://www.ietf.org/rfc/rfc4122.txt
// Used ver 4 - with numbers
std::string GenerateID() {
uint16_t buffer[8];
CHECK(crypto::EntropySource(reinterpret_cast<unsigned char*>(buffer),
sizeof(buffer)));
char uuid[256];
snprintf(uuid, sizeof(uuid), "%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
buffer[0], // time_low
buffer[1], // time_mid
buffer[2], // time_low
(buffer[3] & 0x0fff) | 0x4000, // time_hi_and_version
(buffer[4] & 0x3fff) | 0x8000, // clk_seq_hi clk_seq_low
buffer[5], // node
buffer[6],
buffer[7]);
return uuid;
}
std::string StringViewToUtf8(const StringView& view) {
if (view.is8Bit()) {
return std::string(reinterpret_cast<const char*>(view.characters8()),
view.length());
}
const uint16_t* source = view.characters16();
const UChar* unicodeSource = reinterpret_cast<const UChar*>(source);
static_assert(sizeof(*source) == sizeof(*unicodeSource),
"sizeof(*source) == sizeof(*unicodeSource)");
size_t result_length = view.length() * sizeof(*source);
std::string result(result_length, '\0');
UnicodeString utf16(unicodeSource, view.length());
// ICU components for std::string compatibility are not enabled in build...
bool done = false;
while (!done) {
CheckedArrayByteSink sink(&result[0], result_length);
utf16.toUTF8(sink);
result_length = sink.NumberOfBytesAppended();
result.resize(result_length);
done = !sink.Overflowed();
}
return result;
}
void HandleSyncCloseCb(uv_handle_t* handle) {
*static_cast<bool*>(handle->data) = true;
}
int CloseAsyncAndLoop(uv_async_t* async) {
bool is_closed = false;
async->data = &is_closed;
uv_close(reinterpret_cast<uv_handle_t*>(async), HandleSyncCloseCb);
while (!is_closed)
uv_run(async->loop, UV_RUN_ONCE);
async->data = nullptr;
return uv_loop_close(async->loop);
}
} // namespace
std::unique_ptr<StringBuffer> Utf8ToStringView(const std::string& message) {
UnicodeString utf16 =
UnicodeString::fromUTF8(StringPiece(message.data(), message.length()));
StringView view(reinterpret_cast<const uint16_t*>(utf16.getBuffer()),
utf16.length());
return StringBuffer::create(view);
}
class IoSessionDelegate : public InspectorSessionDelegate {
public:
explicit IoSessionDelegate(InspectorIo* io) : io_(io) { }
bool WaitForFrontendMessage() override;
void OnMessage(const v8_inspector::StringView& message) override;
private:
InspectorIo* io_;
};
class InspectorIoDelegate: public node::inspector::SocketServerDelegate {
public:
InspectorIoDelegate(InspectorIo* io, const std::string& script_path,
const std::string& script_name, bool wait);
bool StartSession(int session_id, const std::string& target_id) override;
void MessageReceived(int session_id, const std::string& message) override;
void EndSession(int session_id) override;
std::vector<std::string> GetTargetIds() override;
std::string GetTargetTitle(const std::string& id) override;
std::string GetTargetUrl(const std::string& id) override;
bool IsConnected() { return connected_; }
private:
InspectorIo* io_;
bool connected_;
int session_id_;
const std::string script_name_;
const std::string script_path_;
const std::string target_id_;
bool waiting_;
};
void InterruptCallback(v8::Isolate*, void* io) {
static_cast<InspectorIo*>(io)->DispatchMessages();
}
class DispatchOnInspectorBackendTask : public v8::Task {
public:
explicit DispatchOnInspectorBackendTask(InspectorIo* io) : io_(io) {}
void Run() override {
io_->DispatchMessages();
}
private:
InspectorIo* io_;
};
InspectorIo::InspectorIo(Environment* env, v8::Platform* platform,
const std::string& path, const DebugOptions& options)
: options_(options), delegate_(nullptr),
shutting_down_(false), state_(State::kNew),
parent_env_(env), io_thread_req_(),
platform_(platform), dispatching_messages_(false),
session_id_(0), script_name_(path) {
CHECK_EQ(0, uv_async_init(env->event_loop(), &main_thread_req_,
InspectorIo::MainThreadAsyncCb));
uv_unref(reinterpret_cast<uv_handle_t*>(&main_thread_req_));
CHECK_EQ(0, uv_sem_init(&start_sem_, 0));
}
bool InspectorIo::Start() {
CHECK_EQ(uv_thread_create(&thread_, InspectorIo::ThreadCbIO, this), 0);
uv_sem_wait(&start_sem_);
if (state_ == State::kError) {
Stop();
return false;
}
state_ = State::kAccepting;
if (options_.wait_for_connect()) {
DispatchMessages();
}
return true;
}
void InspectorIo::Stop() {
int err = uv_thread_join(&thread_);
CHECK_EQ(err, 0);
}
bool InspectorIo::IsConnected() {
return delegate_ != nullptr && delegate_->IsConnected();
}
bool InspectorIo::IsStarted() {
return platform_ != nullptr;
}
void InspectorIo::WaitForDisconnect() {
if (state_ == State::kConnected) {
shutting_down_ = true;
Write(TransportAction::kStop, 0, StringView());
fprintf(stderr, "Waiting for the debugger to disconnect...\n");
fflush(stderr);
parent_env_->inspector_agent()->RunMessageLoop();
}
}
// static
void InspectorIo::ThreadCbIO(void* io) {
static_cast<InspectorIo*>(io)->WorkerRunIO<InspectorSocketServer>();
}
// static
template <typename Transport>
void InspectorIo::WriteCbIO(uv_async_t* async) {
TransportAndIo<Transport>* io_and_transport =
static_cast<TransportAndIo<Transport>*>(async->data);
if (io_and_transport == nullptr) {
return;
}
MessageQueue<TransportAction> outgoing_messages;
InspectorIo* io = io_and_transport->second;
io->SwapBehindLock(&io->outgoing_message_queue_, &outgoing_messages);
for (const auto& outgoing : outgoing_messages) {
switch (std::get<0>(outgoing)) {
case TransportAction::kStop:
io_and_transport->first->Stop(nullptr);
break;
case TransportAction::kSendMessage:
std::string message = StringViewToUtf8(std::get<2>(outgoing)->string());
io_and_transport->first->Send(std::get<1>(outgoing), message);
break;
}
}
}
template<typename Transport>
void InspectorIo::WorkerRunIO() {
uv_loop_t loop;
int err = uv_loop_init(&loop);
CHECK_EQ(err, 0);
io_thread_req_.data = nullptr;
err = uv_async_init(&loop, &io_thread_req_, WriteCbIO<Transport>);
CHECK_EQ(err, 0);
std::string script_path;
if (!script_name_.empty()) {
uv_fs_t req;
if (0 == uv_fs_realpath(&loop, &req, script_name_.c_str(), nullptr))
script_path = std::string(static_cast<char*>(req.ptr));
uv_fs_req_cleanup(&req);
}
InspectorIoDelegate delegate(this, script_path, script_name_,
options_.wait_for_connect());
delegate_ = &delegate;
InspectorSocketServer server(&delegate,
options_.host_name(),
options_.port());
TransportAndIo<Transport> queue_transport(&server, this);
io_thread_req_.data = &queue_transport;
if (!server.Start(&loop)) {
state_ = State::kError; // Safe, main thread is waiting on semaphore
CHECK_EQ(0, CloseAsyncAndLoop(&io_thread_req_));
uv_sem_post(&start_sem_);
return;
}
if (!options_.wait_for_connect()) {
uv_sem_post(&start_sem_);
}
uv_run(&loop, UV_RUN_DEFAULT);
io_thread_req_.data = nullptr;
server.Stop(nullptr);
server.TerminateConnections(nullptr);
CHECK_EQ(CloseAsyncAndLoop(&io_thread_req_), 0);
delegate_ = nullptr;
}
template <typename ActionType>
bool InspectorIo::AppendMessage(MessageQueue<ActionType>* queue,
ActionType action, int session_id,
std::unique_ptr<StringBuffer> buffer) {
Mutex::ScopedLock scoped_lock(state_lock_);
bool trigger_pumping = queue->empty();
queue->push_back(std::make_tuple(action, session_id, std::move(buffer)));
return trigger_pumping;
}
template <typename ActionType>
void InspectorIo::SwapBehindLock(MessageQueue<ActionType>* vector1,
MessageQueue<ActionType>* vector2) {
Mutex::ScopedLock scoped_lock(state_lock_);
vector1->swap(*vector2);
}
void InspectorIo::PostIncomingMessage(InspectorAction action, int session_id,
const std::string& message) {
if (AppendMessage(&incoming_message_queue_, action, session_id,
Utf8ToStringView(message))) {
v8::Isolate* isolate = parent_env_->isolate();
platform_->CallOnForegroundThread(isolate,
new DispatchOnInspectorBackendTask(this));
isolate->RequestInterrupt(InterruptCallback, this);
CHECK_EQ(0, uv_async_send(&main_thread_req_));
}
NotifyMessageReceived();
}
void InspectorIo::WaitForFrontendMessage() {
Mutex::ScopedLock scoped_lock(state_lock_);
if (incoming_message_queue_.empty())
incoming_message_cond_.Wait(scoped_lock);
}
void InspectorIo::NotifyMessageReceived() {
Mutex::ScopedLock scoped_lock(state_lock_);
incoming_message_cond_.Broadcast(scoped_lock);
}
void InspectorIo::DispatchMessages() {
// This function can be reentered if there was an incoming message while
// V8 was processing another inspector request (e.g. if the user is
// evaluating a long-running JS code snippet). This can happen only at
// specific points (e.g. the lines that call inspector_ methods)
if (dispatching_messages_)
return;
dispatching_messages_ = true;
MessageQueue<InspectorAction> tasks;
do {
tasks.clear();
SwapBehindLock(&incoming_message_queue_, &tasks);
for (const auto& task : tasks) {
StringView message = std::get<2>(task)->string();
switch (std::get<0>(task)) {
case InspectorAction::kStartSession:
CHECK_EQ(session_delegate_, nullptr);
session_id_ = std::get<1>(task);
state_ = State::kConnected;
fprintf(stderr, "Debugger attached.\n");
session_delegate_ = std::unique_ptr<InspectorSessionDelegate>(
new IoSessionDelegate(this));
parent_env_->inspector_agent()->Connect(session_delegate_.get());
break;
case InspectorAction::kEndSession:
CHECK_NE(session_delegate_, nullptr);
if (shutting_down_) {
state_ = State::kDone;
} else {
state_ = State::kAccepting;
}
parent_env_->inspector_agent()->Disconnect();
session_delegate_.reset();
break;
case InspectorAction::kSendMessage:
parent_env_->inspector_agent()->Dispatch(message);
break;
}
}
} while (!tasks.empty());
dispatching_messages_ = false;
}
// static
void InspectorIo::MainThreadAsyncCb(uv_async_t* req) {
InspectorIo* io = node::ContainerOf(&InspectorIo::main_thread_req_, req);
io->DispatchMessages();
}
void InspectorIo::Write(TransportAction action, int session_id,
const StringView& inspector_message) {
AppendMessage(&outgoing_message_queue_, action, session_id,
StringBuffer::create(inspector_message));
int err = uv_async_send(&io_thread_req_);
CHECK_EQ(0, err);
}
InspectorIoDelegate::InspectorIoDelegate(InspectorIo* io,
const std::string& script_path,
const std::string& script_name,
bool wait)
: io_(io),
connected_(false),
session_id_(0),
script_name_(script_name),
script_path_(script_path),
target_id_(GenerateID()),
waiting_(wait) { }
bool InspectorIoDelegate::StartSession(int session_id,
const std::string& target_id) {
if (connected_)
return false;
connected_ = true;
session_id_++;
io_->PostIncomingMessage(InspectorAction::kStartSession, session_id, "");
return true;
}
void InspectorIoDelegate::MessageReceived(int session_id,
const std::string& message) {
// TODO(pfeldman): Instead of blocking execution while debugger
// engages, node should wait for the run callback from the remote client
// and initiate its startup. This is a change to node.cc that should be
// upstreamed separately.
if (waiting_) {
if (message.find("\"Runtime.runIfWaitingForDebugger\"") !=
std::string::npos) {
waiting_ = false;
io_->ResumeStartup();
}
}
io_->PostIncomingMessage(InspectorAction::kSendMessage, session_id,
message);
}
void InspectorIoDelegate::EndSession(int session_id) {
connected_ = false;
io_->PostIncomingMessage(InspectorAction::kEndSession, session_id, "");
}
std::vector<std::string> InspectorIoDelegate::GetTargetIds() {
return { target_id_ };
}
std::string InspectorIoDelegate::GetTargetTitle(const std::string& id) {
return script_name_.empty() ? GetProcessTitle() : script_name_;
}
std::string InspectorIoDelegate::GetTargetUrl(const std::string& id) {
return "file://" + script_path_;
}
bool IoSessionDelegate::WaitForFrontendMessage() {
io_->WaitForFrontendMessage();
return true;
}
void IoSessionDelegate::OnMessage(const v8_inspector::StringView& message) {
io_->Write(TransportAction::kSendMessage, io_->session_id_, message);
}
} // namespace inspector
} // namespace node
+125
View File
@@ -0,0 +1,125 @@
#ifndef SRC_INSPECTOR_IO_H_
#define SRC_INSPECTOR_IO_H_
#include "inspector_socket_server.h"
#include "node_debug_options.h"
#include "node_mutex.h"
#include "uv.h"
#include <memory>
#include <stddef.h>
#include <vector>
#if !HAVE_INSPECTOR
#error("This header can only be used when inspector is enabled")
#endif
// Forward declaration to break recursive dependency chain with src/env.h.
namespace node {
class Environment;
} // namespace node
namespace v8_inspector {
class StringBuffer;
class StringView;
} // namespace v8_inspector
namespace node {
namespace inspector {
class InspectorIoDelegate;
enum class InspectorAction {
kStartSession, kEndSession, kSendMessage
};
enum class TransportAction {
kSendMessage, kStop
};
class InspectorIo {
public:
InspectorIo(node::Environment* env, v8::Platform* platform,
const std::string& path, const DebugOptions& options);
// Start the inspector agent thread
bool Start();
// Stop the inspector agent
void Stop();
bool IsStarted();
bool IsConnected();
void WaitForDisconnect();
void PostIncomingMessage(InspectorAction action, int session_id,
const std::string& message);
void ResumeStartup() {
uv_sem_post(&start_sem_);
}
private:
template <typename Action>
using MessageQueue =
std::vector<std::tuple<Action, int,
std::unique_ptr<v8_inspector::StringBuffer>>>;
enum class State { kNew, kAccepting, kConnected, kDone, kError };
static void ThreadCbIO(void* agent);
static void MainThreadAsyncCb(uv_async_t* req);
template <typename Transport> static void WriteCbIO(uv_async_t* async);
template <typename Transport> void WorkerRunIO();
void SetConnected(bool connected);
void DispatchMessages();
void Write(TransportAction action, int session_id,
const v8_inspector::StringView& message);
template <typename ActionType>
bool AppendMessage(MessageQueue<ActionType>* vector, ActionType action,
int session_id,
std::unique_ptr<v8_inspector::StringBuffer> buffer);
template <typename ActionType>
void SwapBehindLock(MessageQueue<ActionType>* vector1,
MessageQueue<ActionType>* vector2);
void WaitForFrontendMessage();
void NotifyMessageReceived();
bool StartThread(bool wait);
// Message queues
ConditionVariable incoming_message_cond_;
const DebugOptions options_;
uv_sem_t start_sem_;
Mutex state_lock_;
uv_thread_t thread_;
InspectorIoDelegate* delegate_;
bool shutting_down_;
State state_;
node::Environment* parent_env_;
uv_async_t io_thread_req_;
uv_async_t main_thread_req_;
std::unique_ptr<InspectorSessionDelegate> session_delegate_;
v8::Platform* platform_;
MessageQueue<InspectorAction> incoming_message_queue_;
MessageQueue<TransportAction> outgoing_message_queue_;
bool dispatching_messages_;
int session_id_;
std::string script_name_;
std::string script_path_;
const std::string id_;
friend class DispatchOnInspectorBackendTask;
friend class IoSessionDelegate;
friend void InterruptCallback(v8::Isolate*, void* agent);
};
std::unique_ptr<v8_inspector::StringBuffer> Utf8ToStringView(
const std::string& message);
} // namespace inspector
} // namespace node
#endif // SRC_INSPECTOR_IO_H_
+14 -139
View File
@@ -270,7 +270,7 @@ static struct {
bool StartInspector(Environment *env, const char* script_path,
const node::DebugOptions& options) {
env->ThrowError("Node compiled with NODE_USE_V8_PLATFORM=0");
return false; // make compiler happy
return true;
}
void StartTracingAgent() {
@@ -282,7 +282,6 @@ static struct {
} v8_platform;
#ifdef __POSIX__
static uv_sem_t debug_semaphore;
static const unsigned kMaxSignal = 32;
#endif
@@ -2581,9 +2580,7 @@ void FatalException(Isolate* isolate,
if (exit_code) {
#if HAVE_INSPECTOR
if (debug_options.inspector_enabled()) {
env->inspector_agent()->FatalException(error, message);
}
env->inspector_agent()->FatalException(error, message);
#endif
exit(exit_code);
}
@@ -3860,10 +3857,6 @@ static void DispatchMessagesDebugAgentCallback(Environment* env) {
static void StartDebug(Environment* env, const char* path,
DebugOptions debug_options) {
CHECK(!debugger_running);
#if HAVE_INSPECTOR
if (debug_options.inspector_enabled())
debugger_running = v8_platform.StartInspector(env, path, debug_options);
#endif // HAVE_INSPECTOR
if (debug_options.debugger_enabled()) {
env->debugger_agent()->set_dispatch_handler(
DispatchMessagesDebugAgentCallback);
@@ -3873,6 +3866,10 @@ static void StartDebug(Environment* env, const char* path,
debug_options.host_name().c_str(), debug_options.port());
fflush(stderr);
}
#if HAVE_INSPECTOR
} else {
debugger_running = v8_platform.StartInspector(env, path, debug_options);
#endif // HAVE_INSPECTOR
}
}
@@ -3881,10 +3878,6 @@ static void StartDebug(Environment* env, const char* path,
static void EnableDebug(Environment* env) {
CHECK(debugger_running);
if (!debug_options.debugger_enabled()) {
return;
}
// Send message to enable debug in workers
HandleScope handle_scope(env->isolate());
@@ -3902,16 +3895,6 @@ static void EnableDebug(Environment* env) {
}
// Called from an arbitrary thread.
static void TryStartDebugger() {
Mutex::ScopedLock scoped_lock(node_isolate_mutex);
if (auto isolate = node_isolate) {
v8::Debug::DebugBreak(isolate);
uv_async_send(&dispatch_debug_messages_async);
}
}
// Called from the main thread.
static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) {
Mutex::ScopedLock scoped_lock(node_isolate_mutex);
@@ -3934,11 +3917,6 @@ static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) {
#ifdef __POSIX__
static void EnableDebugSignalHandler(int signo) {
uv_sem_post(&debug_semaphore);
}
void RegisterSignalHandler(int signal,
void (*handler)(int signal),
bool reset_handler) {
@@ -3972,112 +3950,16 @@ void DebugProcess(const FunctionCallbackInfo<Value>& args) {
return env->ThrowErrnoException(errno, "kill");
}
}
inline void* DebugSignalThreadMain(void* unused) {
for (;;) {
uv_sem_wait(&debug_semaphore);
TryStartDebugger();
}
return nullptr;
}
static int RegisterDebugSignalHandler() {
// Start a watchdog thread for calling v8::Debug::DebugBreak() because
// it's not safe to call directly from the signal handler, it can
// deadlock with the thread it interrupts.
CHECK_EQ(0, uv_sem_init(&debug_semaphore, 0));
pthread_attr_t attr;
CHECK_EQ(0, pthread_attr_init(&attr));
// Don't shrink the thread's stack on FreeBSD. Said platform decided to
// follow the pthreads specification to the letter rather than in spirit:
// https://lists.freebsd.org/pipermail/freebsd-current/2014-March/048885.html
#ifndef __FreeBSD__
CHECK_EQ(0, pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN));
#endif // __FreeBSD__
CHECK_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
sigset_t sigmask;
sigfillset(&sigmask);
CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, &sigmask));
pthread_t thread;
const int err =
pthread_create(&thread, &attr, DebugSignalThreadMain, nullptr);
CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr));
CHECK_EQ(0, pthread_attr_destroy(&attr));
if (err != 0) {
fprintf(stderr, "node[%d]: pthread_create: %s\n", getpid(), strerror(err));
fflush(stderr);
// Leave SIGUSR1 blocked. We don't install a signal handler,
// receiving the signal would terminate the process.
return -err;
}
RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
// Unblock SIGUSR1. A pending SIGUSR1 signal will now be delivered.
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGUSR1);
CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr));
return 0;
}
#endif // __POSIX__
#ifdef _WIN32
DWORD WINAPI EnableDebugThreadProc(void* arg) {
TryStartDebugger();
return 0;
}
static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
size_t buf_len) {
return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
}
static int RegisterDebugSignalHandler() {
wchar_t mapping_name[32];
HANDLE mapping_handle;
DWORD pid;
LPTHREAD_START_ROUTINE* handler;
pid = GetCurrentProcessId();
if (GetDebugSignalHandlerMappingName(pid,
mapping_name,
arraysize(mapping_name)) < 0) {
return -1;
}
mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
nullptr,
PAGE_READWRITE,
0,
sizeof *handler,
mapping_name);
if (mapping_handle == nullptr) {
return -1;
}
handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
MapViewOfFile(mapping_handle,
FILE_MAP_ALL_ACCESS,
0,
0,
sizeof *handler));
if (handler == nullptr) {
CloseHandle(mapping_handle);
return -1;
}
*handler = EnableDebugThreadProc;
UnmapViewOfFile(static_cast<void*>(handler));
return 0;
}
static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = args.GetIsolate();
@@ -4177,7 +4059,7 @@ static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
if (debugger_running) {
Environment* env = Environment::GetCurrent(args);
#if HAVE_INSPECTOR
if (debug_options.inspector_enabled()) {
if (!debug_options.debugger_enabled()) {
env->inspector_agent()->Stop();
} else {
#endif
@@ -4373,10 +4255,6 @@ void Init(int* argc,
const char no_typed_array_heap[] = "--typed_array_max_size_in_heap=0";
V8::SetFlagsFromString(no_typed_array_heap, sizeof(no_typed_array_heap) - 1);
if (!debug_options.debugger_enabled() && !debug_options.inspector_enabled()) {
RegisterDebugSignalHandler();
}
// We should set node_is_initialized here instead of in node::Start,
// otherwise embedders using node::Init to initialize everything will not be
// able to set it and native modules will not load for them.
@@ -4490,16 +4368,13 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data,
Environment env(isolate_data, context);
env.Start(argc, argv, exec_argc, exec_argv, v8_is_profiling);
bool debug_enabled =
debug_options.debugger_enabled() || debug_options.inspector_enabled();
const char* path = argc > 1 ? argv[1] : nullptr;
StartDebug(&env, path, debug_options);
// Start debug agent when argv has --debug
if (debug_enabled) {
const char* path = argc > 1 ? argv[1] : nullptr;
StartDebug(&env, path, debug_options);
if (!debugger_running)
return 12; // Signal internal error.
}
bool debugger_enabled =
debug_options.debugger_enabled() || debug_options.inspector_enabled();
if (debugger_enabled && !debugger_running)
return 12; // Signal internal error.
{
Environment::AsyncCallbackScope callback_scope(&env);
@@ -4509,7 +4384,7 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data,
env.set_trace_sync_io(trace_sync_io);
// Enable debugger
if (debug_enabled)
if (debug_options.debugger_enabled())
EnableDebug(&env);
if (load_napi_modules) {
+3 -3
View File
@@ -134,10 +134,10 @@ bool DebugOptions::ParseOption(const std::string& option) {
int DebugOptions::port() const {
int port = port_;
if (port < 0) {
#if HAVE_INSPECTOR
port = inspector_enabled_ ? default_inspector_port : default_debugger_port;
#else
port = default_debugger_port;
#if HAVE_INSPECTOR
if (!debugger_enabled_ || inspector_enabled_)
port = default_inspector_port;
#endif // HAVE_INSPECTOR
}
return port;