Is it necessary to run jstack -F as root (on linux) and if so why?

lalala666 picture lalala666 · Dec 13, 2012 · Viewed 9.1k times · Source

Is it necessary to run jstack -F as root (on linux) and if so why?

When trying to jstack -F my own processes I get the following error.

Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: Can't attach to the process

jstack -F works fine if I run it with sudo.

Answer

Frank Pavageau picture Frank Pavageau · Dec 17, 2012

It's because jstack -F uses the ptrace(2) system call to try and access the JVM data, which fails if you don't have the rights:

$ strace -e all -f jstack -F 26846
...
[pid 27653] ptrace(PTRACE_ATTACH, 26846, 0, 0) = -1 EPERM (Operation not permitted)
...

From the ptrace(2) man:

EPERM  The specified process cannot be traced. This could be because the parent
       has insufficient privileges (the required capability is CAP_SYS_PTRACE);
       unprivileged  processes  cannot trace processes that they cannot send
       signals to or those running set-user-ID/set-group-ID programs, for obvious
       reasons.  Alternatively, the process may already be being traced, or be
       init(8) (PID 1).

See also capabilities(7). Using sudo, you get root's capabilities, which include CAP_SYS_PTRACE.