4

When using ptrace_attach.How can you know if the process you're attaching is running in 32 or 64 bits ?

I'm coding a little strace-like and I need to know if it's 32 or 64 bits because the number of the syscalls in RAX(EAX) will not have the same meaning.

When you're tracing a cmd (strace ls) it's quiet simple, you mmap the binary and you perform some checking with Elf.

But I cannot find anything regarding an already existing process ?

Thank you !

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Lks
  • 71
  • 1
  • Some suggestions: http://superuser.com/q/224533/4160, http://unix.stackexchange.com/q/106234/615 – Josh Kelley May 07 '15 at 17:45
  • `open()` and then `mmap()` `/proc//exe`? – twalberg May 07 '15 at 18:23
  • Yep this is what I just did, works fine, thx guys ! But is this fully portable ? I mean /proc/pid/exe is it like a universal path on linux systems ? – Lks May 07 '15 at 18:35
  • @Lks near enough on Linux systems, unless you need to work with some embedded platforms that run a Linux kernel without a /proc file system. Not so portable to other *nixen, though... – twalberg May 07 '15 at 18:38

1 Answers1

3

This is quite an interesting question.

Using /proc/<PID>/exe is easy, but is not very reliable: /proc filesystem may not be mounted, or the process could be executing in a chroot.

I took a look at what strace does. It executes the following:

union {
  struct user_regs_struct x86_64_r;
  struct i386_user_regs_struct i386_r;
} regs;

struct iovec {
  .iov_base = &regs,
  .iov_len = sizeof(regs)
} x86_io;

ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &x86_io);
if (regs.iov_len == sizeof(i386_user_regs_struct) {
  // this is a 32-bit process
} else {
  // this is either x86_64, or x32 process
}

But is this fully portable

Nothing about ptrace is fully-portable. Just about every UNIX variant will require custom handling here.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • Indeed, this continues to report original bitness even if the process has jumped to a segment with another bitness. – Ruslan Sep 06 '15 at 19:37