Skip to content

Instantly share code, notes, and snippets.

@fcamel
Last active December 18, 2015 19:09
Show Gist options
  • Save fcamel/5830507 to your computer and use it in GitHub Desktop.
Save fcamel/5830507 to your computer and use it in GitHub Desktop.
// Ref. chromium/src/base/debug/debugger_posix.cc
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#define HANDLE_EINTR(x) ({ \
typeof(x) __eintr_result__; \
do { \
__eintr_result__ = (x); \
} while (__eintr_result__ == -1 && errno == EINTR); \
__eintr_result__;\
})
bool BeingDebugged() {
// NOTE: This code MUST be async-signal safe (it's used by in-process
// stack dumping signal handler). NO malloc or stdio is allowed here.
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
if (HANDLE_EINTR(close(status_fd)) < 0)
return false;
if (num_read <= 0)
return false;
const char *target = "TracerPid:\t";
char *found = strstr(buf, target);
if (!found)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
int index = found - buf + strlen(target);
return index < num_read && buf[index] != '0';
}
int main(void) {
while (true) {
sleep(1);
std::cout << getpid() << " is debugged? " << BeingDebugged() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment