1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
|
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <string.h>
#ifndef MADV_FREE #define MADV_FREE 8 #endif
int anetPipe(int *fds, int read_flags, int write_flags) { return pipe(fds); }
int smapsGetSharedDirty(unsigned long addr) { int ret, in_mapping = 0, val = -1; unsigned long from, to; char buf[64]; FILE *f;
f = fopen("/proc/self/smaps", "r"); if (!f) return -1;
while (1) { if (!fgets(buf, sizeof(buf), f)) break;
ret = sscanf(buf, "%lx-%lx", &from, &to); if (ret == 2) in_mapping = from <= addr && addr < to;
if (in_mapping && !memcmp(buf, "Shared_Dirty:", 13)) { sscanf(buf, "%*s %d", &val); break; } }
fclose(f); return val; }
int checkLinuxMadvFreeForkBug(char **error_msg) { int ret, pipefd[2] = { -1, -1 }; pid_t pid; char *p = NULL, *q; int res = 1; long page_size = sysconf(_SC_PAGESIZE); long map_size = 3 * page_size;
p = mmap(NULL, map_size, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (p == MAP_FAILED) { return 0; }
q = p + page_size;
ret = mprotect(q, page_size, PROT_READ | PROT_WRITE); if (ret < 0) { res = 0; goto exit; }
*(volatile char*)q = 0;
ret = madvise(q, page_size, MADV_FREE); if (ret < 0) { if (errno == EINVAL) goto exit; res = 0; goto exit; }
*(volatile char*)q = 0;
ret = anetPipe(pipefd, 0, 0); if (ret < 0) { res = 0; goto exit; }
pid = fork(); if (pid < 0) { res = 0; goto exit; } else if (!pid) { ret = smapsGetSharedDirty((unsigned long) q); if (!ret) res = -1; else if (ret == -1) res = 0;
ret = write(pipefd[1], &res, sizeof(res)); exit(0); } else { ret = read(pipefd[0], &res, sizeof(res)); if (ret < 0) { res = 0; }
waitpid(pid, NULL, 0); }
exit: if (pipefd[0] != -1) close(pipefd[0]); if (pipefd[1] != -1) close(pipefd[1]); if (p != NULL) munmap(p, map_size);
if (res == -1 && error_msg) { *error_msg = strdup("Your kernel has a bug that could lead to data corruption during background save. Please upgrade to the latest stable kernel."); }
return res; }
int main() { char *error_msg = NULL; int result = checkLinuxMadvFreeForkBug(&error_msg); if (result == -1) { printf("Kernel bug detected: %s\n", error_msg); free(error_msg); return 1; } else if (result == 1) { printf("No kernel bug detected.\n"); } else { printf("Error checking for kernel bug.\n"); } return 0; }
|