Переглянути джерело

LibCore: Implement a helper that waits for a debugger then breaks

This method can be used to force the current process to sleep, waiting
for a debugger to attach. On attach, the debugger breaks at the callsite
 directly.

This is tested on Linux and macOS, in Clion and also terminal gdb and
lldb.
Sebastian Zaha 2 роки тому
батько
коміт
35c45a94d3

+ 22 - 0
Userland/Libraries/LibCore/Process.cpp

@@ -166,4 +166,26 @@ ErrorOr<bool> Process::is_being_debugged()
     return Error::from_string_view("Platform does not support checking for debugger"sv);
 }
 
+// Forces the process to sleep until a debugger is attached, then breaks.
+void Process::wait_for_debugger_and_break()
+{
+    bool should_print_process_info { true };
+    for (;;) {
+        auto check = Process::is_being_debugged();
+        if (check.is_error()) {
+            dbgln("Cannot wait for debugger: {}. Continuing.", check.release_error());
+            return;
+        }
+        if (check.value()) {
+            kill(getpid(), SIGTRAP);
+            return;
+        }
+        if (should_print_process_info) {
+            dbgln("Process {} with pid {} is sleeping, waiting for debugger.", Process::get_name(), getpid());
+            should_print_process_info = false;
+        }
+        ::usleep(100 * 1000);
+    }
+}
+
 }

+ 1 - 0
Userland/Libraries/LibCore/Process.h

@@ -31,6 +31,7 @@ public:
     };
     static ErrorOr<void> set_name(StringView, SetThreadName = SetThreadName::No);
 
+    static void wait_for_debugger_and_break();
     static ErrorOr<bool> is_being_debugged();
 };