Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting whether a debugger is attached to the current process #15137

Open
HertzDevil opened this issue Oct 29, 2024 · 0 comments
Open

Detecting whether a debugger is attached to the current process #15137

HertzDevil opened this issue Oct 29, 2024 · 0 comments

Comments

@HertzDevil
Copy link
Contributor

HertzDevil commented Oct 29, 2024

Sometimes, it is desirable to perform extra actions in a process only when a debugger is already attached, e.g. log more information, trigger a debugger break, or implement #4263. Although the extra actions can be conditionally guarded using some compile-time flag, more convenient would be detecting the debugger's presence at execution time; this reduces recompilations, and allows the process to react to live debugger attachments and detachments.

On Windows, the implementation is very simple, and supports Visual Studio / LLDB / GDB:

lib LibC
  fun IsDebuggerPresent : BOOL
end

def debugger_present? : Bool
  LibC.IsDebuggerPresent != 0
end

On Linux, the conventional way seems to be reading from /proc/self/status. It is slower, but more expressive as it can obtain the debugger's process ID and handle other processes:

def debugger_present? : Bool
  File.each_line("/proc/self/status") do |line|
    if tracer_pid = line.lchop?("TracerPid:").try(&.to_i?)
      return true if tracer_pid != 0
    end
  end
  false
end

However, some BSDs, including macOS, do not have procfs. It seems sysctl would do the job.

On Solaris /proc/*/status is a binary blob.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant