nocore.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // nocore <cmd> [args]: runs a command and all its descendants under ptrace and kills any of them that gets a
  2. // fatal signal (SEGV, ABRT, BUS, ILL, FPE) with SIGKILL before the kernel starts a core dump. RLIMIT_CORE=0 does not
  3. // help with a core_pattern that pipes to systemd-coredump, the handler still runs and the desktop shows a crash report.
  4. // gcc -O2 -o nocore tools/nocore.c
  5. #include <errno.h>
  6. #include <signal.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <sys/ptrace.h>
  10. #include <sys/wait.h>
  11. #include <unistd.h>
  12. int main(int argc, char **argv) {
  13. if (argc < 2) {
  14. fprintf(stderr, "usage: nocore <cmd> [args]\n");
  15. return 2;
  16. }
  17. pid_t root = fork();
  18. if (root < 0) {
  19. perror("fork");
  20. return 2;
  21. }
  22. if (root == 0) {
  23. ptrace(PTRACE_TRACEME, 0, 0, 0);
  24. execvp(argv[1], argv + 1);
  25. perror(argv[1]);
  26. _exit(127);
  27. }
  28. int rootStatus = 0;
  29. int first = 1;
  30. for (;;) {
  31. int status;
  32. pid_t pid = waitpid(-1, &status, __WALL);
  33. if (pid < 0) {
  34. if (errno == EINTR)
  35. continue;
  36. break;
  37. }
  38. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  39. if (pid == root)
  40. rootStatus = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
  41. continue;
  42. }
  43. if (!WIFSTOPPED(status))
  44. continue;
  45. if (first && pid == root) {
  46. ptrace(PTRACE_SETOPTIONS, pid, 0,
  47. PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_EXITKILL);
  48. first = 0;
  49. }
  50. int sig = WSTOPSIG(status);
  51. if (status >> 16 || sig == SIGTRAP || sig == SIGSTOP) {
  52. ptrace(PTRACE_CONT, pid, 0, 0);
  53. } else if (sig == SIGSEGV || sig == SIGABRT || sig == SIGBUS || sig == SIGILL || sig == SIGFPE) {
  54. fprintf(stderr, "nocore: pid %d got signal %d, killed without a core dump\n", pid, sig);
  55. kill(pid, SIGKILL);
  56. ptrace(PTRACE_CONT, pid, 0, SIGKILL);
  57. } else {
  58. ptrace(PTRACE_CONT, pid, 0, sig);
  59. }
  60. }
  61. return rootStatus;
  62. }