2 * Copyright (c) 2002 Poul-Henning Kamp
3 * Copyright (c) 2002 Networks Associates Technology, Inc.
6 * This software was developed for the FreeBSD Project by Poul-Henning Kamp
7 * and NAI Labs, the Security Research Division of Network Associates, Inc.
8 * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9 * DARPA CHATS research program.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior written
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1986, 1992, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 4. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
66 #include <sys/param.h>
68 #include <sys/kerneldump.h>
69 #include <sys/mount.h>
86 /* The size of the buffer used for I/O. */
87 #define BUFFERSIZE (1024*1024)
91 #define STATUS_UNKNOWN 2
93 static int checkfor, compress, clear, force, keep, verbose; /* flags */
94 static int nfound, nsaved, nerr; /* statistics */
97 extern FILE *zopen(const char *, const char *);
99 static sig_atomic_t got_siginfo;
100 static void infohandler(int);
103 printheader(xo_handle_t *xo, const struct kerneldumpheader *h, const char *device,
104 int bounds, const int status)
108 const char *stat_str;
111 xo_emit_h(xo, "{Lwc:Dump header from device}{:dump_device/%s}\n", device);
112 xo_emit_h(xo, "{P: }{Lwc:Architecture}{:architecture/%s}\n", h->architecture);
113 xo_emit_h(xo, "{P: }{Lwc:Architecture Version}{:architecture_version/%u}\n", dtoh32(h->architectureversion));
114 dumplen = dtoh64(h->dumplength);
115 xo_emit_h(xo, "{P: }{Lwc:Dump Length}{:dump_length_bytes/%lld}\n", (long long)dumplen);
116 xo_emit_h(xo, "{P: }{Lwc:Blocksize}{:blocksize/%d}\n", dtoh32(h->blocksize));
117 t = dtoh64(h->dumptime);
118 xo_emit_h(xo, "{P: }{Lwc:Dumptime}{:dumptime/%s}", ctime(&t));
119 xo_emit_h(xo, "{P: }{Lwc:Hostname}{:hostname/%s}\n", h->hostname);
120 xo_emit_h(xo, "{P: }{Lwc:Magic}{:magic/%s}\n", h->magic);
121 xo_emit_h(xo, "{P: }{Lwc:Version String}{:version_string/%s}", h->versionstring);
122 xo_emit_h(xo, "{P: }{Lwc:Panic String}{:panic_string/%s}\n", h->panicstring);
123 xo_emit_h(xo, "{P: }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity);
124 xo_emit_h(xo, "{P: }{Lwc:Bounds}{:bounds/%d}\n", bounds);
134 stat_str = "unknown";
136 xo_emit_h(xo, "{P: }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str);
148 if ((fp = fopen("bounds", "r")) == NULL) {
150 printf("unable to open bounds file, using 0\n");
154 if (fgets(buf, sizeof buf, fp) == NULL) {
156 syslog(LOG_WARNING, "bounds file is empty, using 0");
158 syslog(LOG_WARNING, "bounds file: %s", strerror(errno));
164 ret = (int)strtol(buf, NULL, 10);
165 if (ret == 0 && (errno == EINVAL || errno == ERANGE))
166 syslog(LOG_WARNING, "invalid value found in bounds, using 0");
172 writebounds(int bounds) {
175 if ((fp = fopen("bounds", "w")) == NULL) {
176 syslog(LOG_WARNING, "unable to write to bounds file: %m");
181 printf("bounds number: %d\n", bounds);
183 fprintf(fp, "%d\n", bounds);
188 writekey(const char *keyname, uint8_t *dumpkey, uint32_t dumpkeysize)
192 fd = open(keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
194 syslog(LOG_ERR, "Unable to open %s to write the key: %m.",
199 if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
200 syslog(LOG_ERR, "Unable to write the key to %s: %m.", keyname);
210 file_size(const char *path)
214 /* Ignore all errors, those file may not exists. */
215 if (stat(path, &sb) == -1)
221 saved_dump_size(int bounds)
223 static char path[PATH_MAX];
228 (void)snprintf(path, sizeof(path), "info.%d", bounds);
229 dumpsize += file_size(path);
230 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
231 dumpsize += file_size(path);
232 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
233 dumpsize += file_size(path);
234 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
235 dumpsize += file_size(path);
236 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
237 dumpsize += file_size(path);
243 saved_dump_remove(int bounds)
245 static char path[PATH_MAX];
247 (void)snprintf(path, sizeof(path), "info.%d", bounds);
249 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
251 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
253 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
255 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
260 symlinks_remove(void)
263 (void)unlink("info.last");
264 (void)unlink("key.last");
265 (void)unlink("vmcore.last");
266 (void)unlink("vmcore.last.gz");
267 (void)unlink("vmcore_encrypted.last");
268 (void)unlink("vmcore_encrypted.last.gz");
269 (void)unlink("textdump.tar.last");
270 (void)unlink("textdump.tar.last.gz");
274 * Check that sufficient space is available on the disk that holds the
278 check_space(const char *savedir, off_t dumpsize, int bounds)
281 off_t minfree, spacefree, totfree, needed;
285 if (statfs(".", &fsbuf) < 0) {
286 syslog(LOG_ERR, "%s: %m", savedir);
289 spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
290 totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
292 if ((fp = fopen("minfree", "r")) == NULL)
295 if (fgets(buf, sizeof(buf), fp) == NULL)
302 needed = dumpsize / 1024 + 2; /* 2 for info file */
303 needed -= saved_dump_size(bounds);
304 if ((minfree > 0 ? spacefree : totfree) - needed < minfree) {
306 "no dump, not enough free space on device (%lld available, need %lld)",
307 (long long)(minfree > 0 ? spacefree : totfree),
311 if (spacefree - needed < 0)
313 "dump performed, but free space threshold crossed");
317 #define BLOCKSIZE (1<<12)
318 #define BLOCKMASK (~(BLOCKSIZE-1))
321 DoRegularFile(int fd, bool isencrypted, off_t dumpsize, char *buf,
322 const char *device, const char *filename, FILE *fp)
324 int he, hs, nr, nw, wl;
325 off_t dmpcnt, origsize;
330 while (dumpsize > 0) {
334 nr = read(fd, buf, wl);
338 "WARNING: EOF on dump device");
340 syslog(LOG_ERR, "read error on %s: %m", device);
344 if (compress || isencrypted) {
345 nw = fwrite(buf, 1, wl, fp);
347 for (nw = 0; nw < nr; nw = he) {
348 /* find a contiguous block of zeroes */
349 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
350 for (he = hs; he < nr && buf[he] == 0;
353 /* is the hole long enough to matter? */
354 if (he >= hs + BLOCKSIZE)
358 /* back down to a block boundary */
362 * 1) Don't go beyond the end of the buffer.
363 * 2) If the end of the buffer is less than
364 * BLOCKSIZE bytes away, we're at the end
365 * of the file, so just grab what's left.
367 if (hs + BLOCKSIZE > nr)
371 * At this point, we have a partial ordering:
372 * nw <= hs <= he <= nr
373 * If hs > nw, buf[nw..hs] contains non-zero data.
374 * If he > hs, buf[hs..he] is all zeroes.
377 if (fwrite(buf + nw, hs - nw, 1, fp)
381 if (fseeko(fp, he - hs, SEEK_CUR) == -1)
387 "write error on %s file: %m", filename);
389 "WARNING: vmcore may be incomplete");
395 printf("%llu\r", (unsigned long long)dmpcnt);
400 printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
401 (double)dumpsize / (double)origsize)));
409 * Specialized version of dump-reading logic for use with textdumps, which
410 * are written backwards from the end of the partition, and must be reversed
411 * before being written to the file. Textdumps are small, so do a bit less
412 * work to optimize/sparsify.
415 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
416 const char *device, const char *filename, FILE *fp)
419 off_t dmpcnt, totsize;
424 if ((dumpsize % wl) != 0) {
425 syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
430 while (dumpsize > 0) {
431 nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
435 "WARNING: EOF on dump device");
437 syslog(LOG_ERR, "read error on %s: %m", device);
441 nw = fwrite(buf, 1, wl, fp);
444 "write error on %s file: %m", filename);
446 "WARNING: textdump may be incomplete");
452 printf("%llu\r", (unsigned long long)dmpcnt);
461 DoFile(const char *savedir, const char *device)
463 xo_handle_t *xostdout, *xoinfo;
464 static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
465 static char keyname[PATH_MAX];
466 static char *buf = NULL;
468 struct kerneldumpheader kdhf, kdhl;
470 off_t mediasize, dumpsize, firsthd, lasthd;
473 int fd, fdinfo, error;
475 u_int sectorsize, xostyle;
477 uint32_t dumpkeysize;
478 bool isencrypted, ret;
480 bounds = getbounds();
483 status = STATUS_UNKNOWN;
485 xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
486 if (xostdout == NULL) {
487 syslog(LOG_ERR, "%s: %m", infoname);
491 if (maxdumps > 0 && bounds == maxdumps)
495 buf = malloc(BUFFERSIZE);
497 syslog(LOG_ERR, "%m");
503 printf("checking for kernel dump on device %s\n", device);
505 fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
507 syslog(LOG_ERR, "%s: %m", device);
511 error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
513 error = ioctl(fd, DIOCGSECTORSIZE, §orsize);
516 "couldn't find media and/or sector size of %s: %m", device);
521 printf("mediasize = %lld\n", (long long)mediasize);
522 printf("sectorsize = %u\n", sectorsize);
525 if (sectorsize < sizeof(kdhl)) {
527 "Sector size is less the kernel dump header %zu",
532 lasthd = mediasize - sectorsize;
533 temp = malloc(sectorsize);
535 syslog(LOG_ERR, "%m");
538 if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
539 read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
541 "error reading last dump header at offset %lld in %s: %m",
542 (long long)lasthd, device);
545 memcpy(&kdhl, temp, sizeof(kdhl));
547 if (strncmp(kdhl.magic, TEXTDUMPMAGIC, sizeof kdhl) == 0) {
549 printf("textdump magic on last dump header on %s\n",
552 if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
554 "unknown version (%d) in last dump header on %s",
555 dtoh32(kdhl.version), device);
561 } else if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic) ==
563 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
565 "unknown version (%d) in last dump header on %s",
566 dtoh32(kdhl.version), device);
574 printf("magic mismatch on last dump header on %s\n",
581 if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
582 sizeof kdhl.magic) == 0) {
584 printf("forcing magic on %s\n", device);
585 memcpy(kdhl.magic, KERNELDUMPMAGIC,
588 syslog(LOG_ERR, "unable to force dump - bad magic");
591 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
593 "unknown version (%d) in last dump header on %s",
594 dtoh32(kdhl.version), device);
606 if (kerneldump_parity(&kdhl)) {
608 "parity error on last dump header on %s", device);
614 dumpsize = dtoh64(kdhl.dumplength);
615 dumpkeysize = dtoh32(kdhl.dumpkeysize);
616 firsthd = lasthd - dumpsize - sectorsize - dumpkeysize;
617 if (lseek(fd, firsthd, SEEK_SET) != firsthd ||
618 read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
620 "error reading first dump header at offset %lld in %s: %m",
621 (long long)firsthd, device);
625 memcpy(&kdhf, temp, sizeof(kdhf));
628 printf("First dump headers:\n");
629 printheader(xostdout, &kdhf, device, bounds, -1);
631 printf("\nLast dump headers:\n");
632 printheader(xostdout, &kdhl, device, bounds, -1);
636 if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
638 "first and last dump headers disagree on %s", device);
644 status = STATUS_GOOD;
648 printf("A dump exists on %s\n", device);
653 if (kdhl.panicstring[0] != '\0')
654 syslog(LOG_ALERT, "reboot after panic: %*s",
655 (int)sizeof(kdhl.panicstring), kdhl.panicstring);
657 syslog(LOG_ALERT, "reboot");
660 printf("Checking for available free space\n");
662 if (!check_space(savedir, dumpsize, bounds)) {
667 writebounds(bounds + 1);
669 saved_dump_remove(bounds);
671 snprintf(infoname, sizeof(infoname), "info.%d", bounds);
674 * Create or overwrite any existing dump header files.
676 fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
678 syslog(LOG_ERR, "%s: %m", infoname);
683 oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
684 isencrypted = (dumpkeysize > 0);
686 snprintf(corename, sizeof(corename), "%s.%d.gz",
687 istextdump ? "textdump.tar" :
688 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
689 fp = zopen(corename, "w");
691 snprintf(corename, sizeof(corename), "%s.%d",
692 istextdump ? "textdump.tar" :
693 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
694 fp = fopen(corename, "w");
697 syslog(LOG_ERR, "%s: %m", corename);
704 info = fdopen(fdinfo, "w");
707 syslog(LOG_ERR, "fdopen failed: %m");
712 xostyle = xo_get_style(NULL);
713 xoinfo = xo_create_to_file(info, xostyle, 0);
714 if (xoinfo == NULL) {
715 syslog(LOG_ERR, "%s: %m", infoname);
719 xo_open_container_h(xoinfo, "crashdump");
722 printheader(xostdout, &kdhl, device, bounds, status);
724 printheader(xoinfo, &kdhl, device, bounds, status);
725 xo_close_container_h(xoinfo, "crashdump");
731 dumpkey = calloc(1, dumpkeysize);
732 if (dumpkey == NULL) {
733 syslog(LOG_ERR, "Unable to allocate kernel dump key.");
738 if (read(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
739 syslog(LOG_ERR, "Unable to read kernel dump key: %m.");
744 snprintf(keyname, sizeof(keyname), "key.%d", bounds);
745 ret = writekey(keyname, dumpkey, dumpkeysize);
746 explicit_bzero(dumpkey, dumpkeysize);
753 syslog(LOG_NOTICE, "writing %s%score to %s/%s",
754 isencrypted ? "encrypted " : "", compress ? "compressed " : "",
758 if (DoTextdumpFile(fd, dumpsize, lasthd, buf, device,
762 if (DoRegularFile(fd, isencrypted, dumpsize, buf, device,
770 if (fclose(fp) < 0) {
771 syslog(LOG_ERR, "error on %s: %m", corename);
777 if (symlink(infoname, "info.last") == -1) {
778 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
779 savedir, "info.last");
782 if (symlink(keyname, "key.last") == -1) {
784 "unable to create symlink %s/%s: %m", savedir,
789 snprintf(linkname, sizeof(linkname), "%s.last.gz",
790 istextdump ? "textdump.tar" :
791 (isencrypted ? "vmcore_encrypted" : "vmcore"));
793 snprintf(linkname, sizeof(linkname), "%s.last",
794 istextdump ? "textdump.tar" :
795 (isencrypted ? "vmcore_encrypted" : "vmcore"));
797 if (symlink(corename, linkname) == -1) {
798 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
805 printf("dump saved\n");
810 printf("clearing dump header\n");
811 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
812 memcpy(temp, &kdhl, sizeof(kdhl));
813 if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
814 write(fd, temp, sectorsize) != (ssize_t)sectorsize)
816 "error while clearing the dump header: %m");
818 xo_close_container_h(xostdout, "crashdump");
819 xo_finish_h(xostdout);
837 xo_error("%s\n%s\n%s\n",
838 "usage: savecore -c [-v] [device ...]",
839 " savecore -C [-v] [device ...]",
840 " savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
845 main(int argc, char **argv)
847 const char *savedir = ".";
851 checkfor = compress = clear = force = keep = verbose = 0;
852 nfound = nsaved = nerr = 0;
854 openlog("savecore", LOG_PERROR, LOG_DAEMON);
855 signal(SIGINFO, infohandler);
857 argc = xo_parse_args(argc, argv);
861 while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
876 maxdumps = atoi(optarg);
878 syslog(LOG_ERR, "Invalid maxdump value");
892 if (checkfor && (clear || force || keep))
894 if (clear && (compress || keep))
896 if (maxdumps > 0 && (checkfor || clear))
900 if (argc >= 1 && !checkfor && !clear) {
901 error = chdir(argv[0]);
903 syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
915 if (strcmp(fsp->fs_vfstype, "swap") &&
916 strcmp(fsp->fs_vfstype, "dump"))
918 DoFile(savedir, fsp->fs_spec);
922 for (i = 0; i < argc; i++)
923 DoFile(savedir, argv[i]);
926 /* Emit minimal output. */
930 printf("No dump exists\n");
934 syslog(LOG_WARNING, "no dumps found");
935 } else if (nsaved == 0) {
938 syslog(LOG_WARNING, "unsaved dumps found but not saved");
941 syslog(LOG_WARNING, "no unsaved dumps found");
948 infohandler(int sig __unused)