Index: head/contrib/elftoolchain/strings/strings.c =================================================================== --- head/contrib/elftoolchain/strings/strings.c (revision 346315) +++ head/contrib/elftoolchain/strings/strings.c (revision 346316) @@ -1,471 +1,471 @@ /*- * Copyright (c) 2007 S.Sam Arun Raj * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "_elftc.h" ELFTC_VCSID("$Id: strings.c 3648 2018-11-22 23:26:43Z emaste $"); enum radix_style { RADIX_DECIMAL, RADIX_HEX, RADIX_OCTAL }; enum encoding_style { ENCODING_7BIT, ENCODING_8BIT, ENCODING_16BIT_BIG, ENCODING_16BIT_LITTLE, ENCODING_32BIT_BIG, ENCODING_32BIT_LITTLE }; #define PRINTABLE(c) \ ((c) >= 0 && (c) <= 255 && \ ((c) == '\t' || isprint((c)) || \ (encoding == ENCODING_8BIT && (c) > 127))) static int encoding_size, entire_file, show_filename, show_loc; static enum encoding_style encoding; static enum radix_style radix; static intmax_t min_len; static struct option strings_longopts[] = { { "all", no_argument, NULL, 'a'}, { "bytes", required_argument, NULL, 'n'}, { "encoding", required_argument, NULL, 'e'}, { "help", no_argument, NULL, 'h'}, { "print-file-name", no_argument, NULL, 'f'}, { "radix", required_argument, NULL, 't'}, { "version", no_argument, NULL, 'v'}, { NULL, 0, NULL, 0 } }; int getcharacter(FILE *, long *); int handle_file(fileargs_t *fa, const char *); int handle_elf(const char *, FILE *); int handle_binary(const char *, FILE *, size_t); int find_strings(const char *, FILE *, off_t, off_t); void show_version(void); void usage(void); /* * strings(1) extracts text(contiguous printable characters) * from elf and binary files. */ int main(int argc, char **argv) { fileargs_t *fa; cap_rights_t rights; int ch, rc; rc = 0; min_len = 0; encoding_size = 1; if (elf_version(EV_CURRENT) == EV_NONE) errx(EXIT_FAILURE, "ELF library initialization failed: %s", elf_errmsg(-1)); while ((ch = getopt_long(argc, argv, "1234567890ae:fhn:ot:Vv", strings_longopts, NULL)) != -1) { switch ((char)ch) { case 'a': entire_file = 1; break; case 'e': if (*optarg == 's') { encoding = ENCODING_7BIT; } else if (*optarg == 'S') { encoding = ENCODING_8BIT; } else if (*optarg == 'b') { encoding = ENCODING_16BIT_BIG; encoding_size = 2; } else if (*optarg == 'B') { encoding = ENCODING_32BIT_BIG; encoding_size = 4; } else if (*optarg == 'l') { encoding = ENCODING_16BIT_LITTLE; encoding_size = 2; } else if (*optarg == 'L') { encoding = ENCODING_32BIT_LITTLE; encoding_size = 4; } else usage(); /* NOTREACHED */ break; case 'f': show_filename = 1; break; case 'n': min_len = strtoimax(optarg, (char**)NULL, 10); if (min_len <= 0) errx(EX_USAGE, "option -n should specify a " "positive decimal integer."); break; case 'o': show_loc = 1; radix = RADIX_OCTAL; break; case 't': show_loc = 1; if (*optarg == 'd') radix = RADIX_DECIMAL; else if (*optarg == 'o') radix = RADIX_OCTAL; else if (*optarg == 'x') radix = RADIX_HEX; else usage(); /* NOTREACHED */ break; case 'v': case 'V': show_version(); /* NOTREACHED */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': min_len *= 10; min_len += ch - '0'; break; case 'h': case '?': default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; cap_rights_init(&rights, CAP_READ, CAP_SEEK, CAP_FSTAT, CAP_FCNTL); - fa = fileargs_init(argc, argv, O_RDONLY, 0, &rights); + fa = fileargs_init(argc, argv, O_RDONLY, 0, &rights, FA_OPEN); if (fa == NULL) err(1, "Unable to initialize casper fileargs"); caph_cache_catpages(); if (caph_limit_stdio() < 0 && caph_enter_casper() < 0) { fileargs_free(fa); err(1, "Unable to enter capability mode"); } if (min_len == 0) min_len = 4; if (*argv == NULL) rc = find_strings("{standard input}", stdin, 0, 0); else while (*argv != NULL) { if (handle_file(fa, *argv) != 0) rc = 1; argv++; } fileargs_free(fa); return (rc); } int handle_file(fileargs_t *fa, const char *name) { FILE *pfile; int rt; if (name == NULL) return (1); pfile = fileargs_fopen(fa, name, "rb"); if (pfile == NULL) { warnx("'%s': %s", name, strerror(errno)); return (1); } rt = handle_elf(name, pfile); fclose(pfile); return (rt); } /* * Files not understood by handle_elf, will be passed off here and will * treated as a binary file. This would include text file, core dumps ... */ int handle_binary(const char *name, FILE *pfile, size_t size) { (void)fseeko(pfile, 0, SEEK_SET); return (find_strings(name, pfile, 0, size)); } /* * Will analyse a file to see if it ELF, other files including ar(1), * core dumps are passed off and treated as flat binary files. Unlike * GNU size in FreeBSD this routine will not treat ELF object from * different archs as flat binary files(has to overridden using -a). */ int handle_elf(const char *name, FILE *pfile) { struct stat buf; GElf_Ehdr elfhdr; GElf_Shdr shdr; Elf *elf; Elf_Scn *scn; int rc, fd; rc = 0; fd = fileno(pfile); if (fstat(fd, &buf) < 0) return (1); /* If entire file is chosen, treat it as a binary file */ if (entire_file) return (handle_binary(name, pfile, buf.st_size)); (void)lseek(fd, 0, SEEK_SET); elf = elf_begin(fd, ELF_C_READ, NULL); if (elf_kind(elf) != ELF_K_ELF) { (void)elf_end(elf); return (handle_binary(name, pfile, buf.st_size)); } if (gelf_getehdr(elf, &elfhdr) == NULL) { (void)elf_end(elf); warnx("%s: ELF file could not be processed", name); return (1); } if (elfhdr.e_shnum == 0 && elfhdr.e_type == ET_CORE) { (void)elf_end(elf); return (handle_binary(name, pfile, buf.st_size)); } else { scn = NULL; while ((scn = elf_nextscn(elf, scn)) != NULL) { if (gelf_getshdr(scn, &shdr) == NULL) continue; if (shdr.sh_type != SHT_NOBITS && (shdr.sh_flags & SHF_ALLOC) != 0) { rc = find_strings(name, pfile, shdr.sh_offset, shdr.sh_size); } } } (void)elf_end(elf); return (rc); } /* * Retrieves a character from input stream based on the encoding * type requested. */ int getcharacter(FILE *pfile, long *rt) { int i, c; char buf[4]; for(i = 0; i < encoding_size; i++) { c = getc(pfile); if (c == EOF) return (-1); buf[i] = c; } switch (encoding) { case ENCODING_7BIT: case ENCODING_8BIT: *rt = buf[0]; break; case ENCODING_16BIT_BIG: *rt = (buf[0] << 8) | buf[1]; break; case ENCODING_16BIT_LITTLE: *rt = buf[0] | (buf[1] << 8); break; case ENCODING_32BIT_BIG: *rt = ((long) buf[0] << 24) | ((long) buf[1] << 16) | ((long) buf[2] << 8) | buf[3]; break; case ENCODING_32BIT_LITTLE: *rt = buf[0] | ((long) buf[1] << 8) | ((long) buf[2] << 16) | ((long) buf[3] << 24); break; default: return (-1); } return (0); } /* * Input stream is read until the end of file is reached or until * the section size is reached in case of ELF files. Contiguous * characters of >= min_size(default 4) will be displayed. */ int find_strings(const char *name, FILE *pfile, off_t offset, off_t size) { off_t cur_off, start_off; char *obuf; long c; int i; if ((obuf = (char*)calloc(1, min_len + 1)) == NULL) { fprintf(stderr, "Unable to allocate memory: %s\n", strerror(errno)); return (1); } (void)fseeko(pfile, offset, SEEK_SET); cur_off = offset; start_off = 0; for (;;) { if ((offset + size) && (cur_off >= offset + size)) break; start_off = cur_off; memset(obuf, 0, min_len + 1); for(i = 0; i < min_len; i++) { if (getcharacter(pfile, &c) < 0) goto _exit1; if (PRINTABLE(c)) { obuf[i] = c; obuf[i + 1] = 0; cur_off += encoding_size; } else { if (encoding == ENCODING_8BIT && (uint8_t)c > 127) { obuf[i] = c; obuf[i + 1] = 0; cur_off += encoding_size; continue; } cur_off += encoding_size; break; } } if (i >= min_len && ((cur_off <= offset + size) || !(offset + size))) { if (show_filename) printf("%s: ", name); if (show_loc) { switch (radix) { case RADIX_DECIMAL: printf("%7ju ", (uintmax_t)start_off); break; case RADIX_HEX: printf("%7jx ", (uintmax_t)start_off); break; case RADIX_OCTAL: printf("%7jo ", (uintmax_t)start_off); break; } } printf("%s", obuf); for (;;) { if ((offset + size) && (cur_off >= offset + size)) break; if (getcharacter(pfile, &c) < 0) break; cur_off += encoding_size; if (encoding == ENCODING_8BIT && (uint8_t)c > 127) { putchar(c); continue; } if (!PRINTABLE(c)) break; putchar(c); } putchar('\n'); } } _exit1: free(obuf); return (0); } #define USAGE_MESSAGE "\ Usage: %s [options] [file...]\n\ Print contiguous sequences of printable characters.\n\n\ Options:\n\ -a | --all Scan the entire file for strings.\n\ -e ENC | --encoding=ENC Select the character encoding to use.\n\ -f | --print-file-name Print the file name before each string.\n\ -h | --help Print a help message and exit.\n\ -n N | --bytes=N | -N Print sequences with 'N' or more characters.\n\ -o Print offsets in octal.\n\ -t R | --radix=R Print offsets using the radix named by 'R'.\n\ -v | --version Print a version identifier and exit.\n" void usage(void) { fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME()); exit(EXIT_FAILURE); } void show_version(void) { printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version()); exit(EXIT_SUCCESS); } Index: head/sbin/savecore/savecore.c =================================================================== --- head/sbin/savecore/savecore.c (revision 346315) +++ head/sbin/savecore/savecore.c (revision 346316) @@ -1,1177 +1,1177 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2002 Poul-Henning Kamp * Copyright (c) 2002 Networks Associates Technology, Inc. * All rights reserved. * * This software was developed for the FreeBSD Project by Poul-Henning Kamp * and NAI Labs, the Security Research Division of Network Associates, Inc. * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the * DARPA CHATS research program. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the authors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Copyright (c) 1986, 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* The size of the buffer used for I/O. */ #define BUFFERSIZE (1024*1024) #define STATUS_BAD 0 #define STATUS_GOOD 1 #define STATUS_UNKNOWN 2 static cap_channel_t *capsyslog; static fileargs_t *capfa; static int checkfor, compress, clear, force, keep, verbose; /* flags */ static int nfound, nsaved, nerr; /* statistics */ static int maxdumps; extern FILE *zdopen(int, const char *); static sig_atomic_t got_siginfo; static void infohandler(int); static void logmsg(int pri, const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (capsyslog != NULL) cap_vsyslog(capsyslog, pri, fmt, ap); else vsyslog(pri, fmt, ap); va_end(ap); } static FILE * xfopenat(int dirfd, const char *path, int flags, const char *modestr, ...) { va_list ap; FILE *fp; mode_t mode; int error, fd; if ((flags & O_CREAT) == O_CREAT) { va_start(ap, modestr); mode = (mode_t)va_arg(ap, int); va_end(ap); } else mode = 0; fd = openat(dirfd, path, flags, mode); if (fd < 0) return (NULL); fp = fdopen(fd, modestr); if (fp == NULL) { error = errno; (void)close(fd); errno = error; } return (fp); } static void printheader(xo_handle_t *xo, const struct kerneldumpheader *h, const char *device, int bounds, const int status) { uint64_t dumplen; time_t t; const char *stat_str; const char *comp_str; xo_flush_h(xo); xo_emit_h(xo, "{Lwc:Dump header from device}{:dump_device/%s}\n", device); xo_emit_h(xo, "{P: }{Lwc:Architecture}{:architecture/%s}\n", h->architecture); xo_emit_h(xo, "{P: }{Lwc:Architecture Version}{:architecture_version/%u}\n", dtoh32(h->architectureversion)); dumplen = dtoh64(h->dumplength); xo_emit_h(xo, "{P: }{Lwc:Dump Length}{:dump_length_bytes/%lld}\n", (long long)dumplen); xo_emit_h(xo, "{P: }{Lwc:Blocksize}{:blocksize/%d}\n", dtoh32(h->blocksize)); switch (h->compression) { case KERNELDUMP_COMP_NONE: comp_str = "none"; break; case KERNELDUMP_COMP_GZIP: comp_str = "gzip"; break; case KERNELDUMP_COMP_ZSTD: comp_str = "zstd"; break; default: comp_str = "???"; break; } xo_emit_h(xo, "{P: }{Lwc:Compression}{:compression/%s}\n", comp_str); t = dtoh64(h->dumptime); xo_emit_h(xo, "{P: }{Lwc:Dumptime}{:dumptime/%s}", ctime(&t)); xo_emit_h(xo, "{P: }{Lwc:Hostname}{:hostname/%s}\n", h->hostname); xo_emit_h(xo, "{P: }{Lwc:Magic}{:magic/%s}\n", h->magic); xo_emit_h(xo, "{P: }{Lwc:Version String}{:version_string/%s}", h->versionstring); xo_emit_h(xo, "{P: }{Lwc:Panic String}{:panic_string/%s}\n", h->panicstring); xo_emit_h(xo, "{P: }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity); xo_emit_h(xo, "{P: }{Lwc:Bounds}{:bounds/%d}\n", bounds); switch (status) { case STATUS_BAD: stat_str = "bad"; break; case STATUS_GOOD: stat_str = "good"; break; default: stat_str = "unknown"; break; } xo_emit_h(xo, "{P: }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str); xo_flush_h(xo); } static int getbounds(int savedirfd) { FILE *fp; char buf[6]; int ret; /* * If we are just checking, then we haven't done a chdir to the dump * directory and we should not try to read a bounds file. */ if (checkfor) return (0); ret = 0; if ((fp = xfopenat(savedirfd, "bounds", O_RDONLY, "r")) == NULL) { if (verbose) printf("unable to open bounds file, using 0\n"); return (ret); } if (fgets(buf, sizeof(buf), fp) == NULL) { if (feof(fp)) logmsg(LOG_WARNING, "bounds file is empty, using 0"); else logmsg(LOG_WARNING, "bounds file: %s", strerror(errno)); fclose(fp); return (ret); } errno = 0; ret = (int)strtol(buf, NULL, 10); if (ret == 0 && (errno == EINVAL || errno == ERANGE)) logmsg(LOG_WARNING, "invalid value found in bounds, using 0"); fclose(fp); return (ret); } static void writebounds(int savedirfd, int bounds) { FILE *fp; if ((fp = xfopenat(savedirfd, "bounds", O_WRONLY | O_CREAT | O_TRUNC, "w", 0644)) == NULL) { logmsg(LOG_WARNING, "unable to write to bounds file: %m"); return; } if (verbose) printf("bounds number: %d\n", bounds); fprintf(fp, "%d\n", bounds); fclose(fp); } static bool writekey(int savedirfd, const char *keyname, uint8_t *dumpkey, uint32_t dumpkeysize) { int fd; fd = openat(savedirfd, keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd == -1) { logmsg(LOG_ERR, "Unable to open %s to write the key: %m.", keyname); return (false); } if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) { logmsg(LOG_ERR, "Unable to write the key to %s: %m.", keyname); close(fd); return (false); } close(fd); return (true); } static off_t file_size(int savedirfd, const char *path) { struct stat sb; /* Ignore all errors, this file may not exist. */ if (fstatat(savedirfd, path, &sb, 0) == -1) return (0); return (sb.st_size); } static off_t saved_dump_size(int savedirfd, int bounds) { static char path[PATH_MAX]; off_t dumpsize; dumpsize = 0; (void)snprintf(path, sizeof(path), "info.%d", bounds); dumpsize += file_size(savedirfd, path); (void)snprintf(path, sizeof(path), "vmcore.%d", bounds); dumpsize += file_size(savedirfd, path); (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds); dumpsize += file_size(savedirfd, path); (void)snprintf(path, sizeof(path), "vmcore.%d.zst", bounds); dumpsize += file_size(savedirfd, path); (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds); dumpsize += file_size(savedirfd, path); (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds); dumpsize += file_size(savedirfd, path); return (dumpsize); } static void saved_dump_remove(int savedirfd, int bounds) { static char path[PATH_MAX]; (void)snprintf(path, sizeof(path), "info.%d", bounds); (void)unlinkat(savedirfd, path, 0); (void)snprintf(path, sizeof(path), "vmcore.%d", bounds); (void)unlinkat(savedirfd, path, 0); (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds); (void)unlinkat(savedirfd, path, 0); (void)snprintf(path, sizeof(path), "vmcore.%d.zst", bounds); (void)unlinkat(savedirfd, path, 0); (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds); (void)unlinkat(savedirfd, path, 0); (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds); (void)unlinkat(savedirfd, path, 0); } static void symlinks_remove(int savedirfd) { (void)unlinkat(savedirfd, "info.last", 0); (void)unlinkat(savedirfd, "key.last", 0); (void)unlinkat(savedirfd, "vmcore.last", 0); (void)unlinkat(savedirfd, "vmcore.last.gz", 0); (void)unlinkat(savedirfd, "vmcore.last.zst", 0); (void)unlinkat(savedirfd, "vmcore_encrypted.last", 0); (void)unlinkat(savedirfd, "vmcore_encrypted.last.gz", 0); (void)unlinkat(savedirfd, "textdump.tar.last", 0); (void)unlinkat(savedirfd, "textdump.tar.last.gz", 0); } /* * Check that sufficient space is available on the disk that holds the * save directory. */ static int check_space(const char *savedir, int savedirfd, off_t dumpsize, int bounds) { char buf[100]; struct statfs fsbuf; FILE *fp; off_t available, minfree, spacefree, totfree, needed; if (fstatfs(savedirfd, &fsbuf) < 0) { logmsg(LOG_ERR, "%s: %m", savedir); exit(1); } spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024; totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024; if ((fp = xfopenat(savedirfd, "minfree", O_RDONLY, "r")) == NULL) minfree = 0; else { if (fgets(buf, sizeof(buf), fp) == NULL) minfree = 0; else { char *endp; errno = 0; minfree = strtoll(buf, &endp, 10); if (minfree == 0 && errno != 0) minfree = -1; else { while (*endp != '\0' && isspace(*endp)) endp++; if (*endp != '\0' || minfree < 0) minfree = -1; } if (minfree < 0) logmsg(LOG_WARNING, "`minfree` didn't contain a valid size " "(`%s`). Defaulting to 0", buf); } (void)fclose(fp); } available = minfree > 0 ? spacefree - minfree : totfree; needed = dumpsize / 1024 + 2; /* 2 for info file */ needed -= saved_dump_size(savedirfd, bounds); if (available < needed) { logmsg(LOG_WARNING, "no dump: not enough free space on device (need at least " "%jdkB for dump; %jdkB available; %jdkB reserved)", (intmax_t)needed, (intmax_t)available + minfree, (intmax_t)minfree); return (0); } if (spacefree - needed < 0) logmsg(LOG_WARNING, "dump performed, but free space threshold crossed"); return (1); } static bool compare_magic(const struct kerneldumpheader *kdh, const char *magic) { return (strncmp(kdh->magic, magic, sizeof(kdh->magic)) == 0); } #define BLOCKSIZE (1<<12) #define BLOCKMASK (~(BLOCKSIZE-1)) static int DoRegularFile(int fd, off_t dumpsize, u_int sectorsize, bool sparse, char *buf, const char *device, const char *filename, FILE *fp) { int he, hs, nr, nw, wl; off_t dmpcnt, origsize; dmpcnt = 0; origsize = dumpsize; he = 0; while (dumpsize > 0) { wl = BUFFERSIZE; if (wl > dumpsize) wl = dumpsize; nr = read(fd, buf, roundup(wl, sectorsize)); if (nr != (int)roundup(wl, sectorsize)) { if (nr == 0) logmsg(LOG_WARNING, "WARNING: EOF on dump device"); else logmsg(LOG_ERR, "read error on %s: %m", device); nerr++; return (-1); } if (!sparse) { nw = fwrite(buf, 1, wl, fp); } else { for (nw = 0; nw < nr; nw = he) { /* find a contiguous block of zeroes */ for (hs = nw; hs < nr; hs += BLOCKSIZE) { for (he = hs; he < nr && buf[he] == 0; ++he) /* nothing */ ; /* is the hole long enough to matter? */ if (he >= hs + BLOCKSIZE) break; } /* back down to a block boundary */ he &= BLOCKMASK; /* * 1) Don't go beyond the end of the buffer. * 2) If the end of the buffer is less than * BLOCKSIZE bytes away, we're at the end * of the file, so just grab what's left. */ if (hs + BLOCKSIZE > nr) hs = he = nr; /* * At this point, we have a partial ordering: * nw <= hs <= he <= nr * If hs > nw, buf[nw..hs] contains non-zero * data. If he > hs, buf[hs..he] is all zeroes. */ if (hs > nw) if (fwrite(buf + nw, hs - nw, 1, fp) != 1) break; if (he > hs) if (fseeko(fp, he - hs, SEEK_CUR) == -1) break; } } if (nw != wl) { logmsg(LOG_ERR, "write error on %s file: %m", filename); logmsg(LOG_WARNING, "WARNING: vmcore may be incomplete"); nerr++; return (-1); } if (verbose) { dmpcnt += wl; printf("%llu\r", (unsigned long long)dmpcnt); fflush(stdout); } dumpsize -= wl; if (got_siginfo) { printf("%s %.1lf%%\n", filename, (100.0 - (100.0 * (double)dumpsize / (double)origsize))); got_siginfo = 0; } } return (0); } /* * Specialized version of dump-reading logic for use with textdumps, which * are written backwards from the end of the partition, and must be reversed * before being written to the file. Textdumps are small, so do a bit less * work to optimize/sparsify. */ static int DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf, const char *device, const char *filename, FILE *fp) { int nr, nw, wl; off_t dmpcnt, totsize; totsize = dumpsize; dmpcnt = 0; wl = 512; if ((dumpsize % wl) != 0) { logmsg(LOG_ERR, "textdump uneven multiple of 512 on %s", device); nerr++; return (-1); } while (dumpsize > 0) { nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl); if (nr != wl) { if (nr == 0) logmsg(LOG_WARNING, "WARNING: EOF on dump device"); else logmsg(LOG_ERR, "read error on %s: %m", device); nerr++; return (-1); } nw = fwrite(buf, 1, wl, fp); if (nw != wl) { logmsg(LOG_ERR, "write error on %s file: %m", filename); logmsg(LOG_WARNING, "WARNING: textdump may be incomplete"); nerr++; return (-1); } if (verbose) { dmpcnt += wl; printf("%llu\r", (unsigned long long)dmpcnt); fflush(stdout); } dumpsize -= wl; } return (0); } static void DoFile(const char *savedir, int savedirfd, const char *device) { xo_handle_t *xostdout, *xoinfo; static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX]; static char keyname[PATH_MAX]; static char *buf = NULL; char *temp = NULL; struct kerneldumpheader kdhf, kdhl; uint8_t *dumpkey; off_t mediasize, dumpextent, dumplength, firsthd, lasthd; FILE *core, *info; int fdcore, fddev, error; int bounds, status; u_int sectorsize, xostyle; uint32_t dumpkeysize; bool iscompressed, isencrypted, istextdump, ret; bounds = getbounds(savedirfd); dumpkey = NULL; mediasize = 0; status = STATUS_UNKNOWN; xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0); if (xostdout == NULL) { logmsg(LOG_ERR, "%s: %m", infoname); return; } if (maxdumps > 0 && bounds == maxdumps) bounds = 0; if (buf == NULL) { buf = malloc(BUFFERSIZE); if (buf == NULL) { logmsg(LOG_ERR, "%m"); return; } } if (verbose) printf("checking for kernel dump on device %s\n", device); fddev = fileargs_open(capfa, device); if (fddev < 0) { logmsg(LOG_ERR, "%s: %m", device); return; } error = ioctl(fddev, DIOCGMEDIASIZE, &mediasize); if (!error) error = ioctl(fddev, DIOCGSECTORSIZE, §orsize); if (error) { logmsg(LOG_ERR, "couldn't find media and/or sector size of %s: %m", device); goto closefd; } if (verbose) { printf("mediasize = %lld bytes\n", (long long)mediasize); printf("sectorsize = %u bytes\n", sectorsize); } if (sectorsize < sizeof(kdhl)) { logmsg(LOG_ERR, "Sector size is less the kernel dump header %zu", sizeof(kdhl)); goto closefd; } lasthd = mediasize - sectorsize; temp = malloc(sectorsize); if (temp == NULL) { logmsg(LOG_ERR, "%m"); goto closefd; } if (lseek(fddev, lasthd, SEEK_SET) != lasthd || read(fddev, temp, sectorsize) != (ssize_t)sectorsize) { logmsg(LOG_ERR, "error reading last dump header at offset %lld in %s: %m", (long long)lasthd, device); goto closefd; } memcpy(&kdhl, temp, sizeof(kdhl)); iscompressed = istextdump = false; if (compare_magic(&kdhl, TEXTDUMPMAGIC)) { if (verbose) printf("textdump magic on last dump header on %s\n", device); istextdump = true; if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) { logmsg(LOG_ERR, "unknown version (%d) in last dump header on %s", dtoh32(kdhl.version), device); status = STATUS_BAD; if (force == 0) goto closefd; } } else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) { if (dtoh32(kdhl.version) != KERNELDUMPVERSION) { logmsg(LOG_ERR, "unknown version (%d) in last dump header on %s", dtoh32(kdhl.version), device); status = STATUS_BAD; if (force == 0) goto closefd; } switch (kdhl.compression) { case KERNELDUMP_COMP_NONE: break; case KERNELDUMP_COMP_GZIP: case KERNELDUMP_COMP_ZSTD: if (compress && verbose) printf("dump is already compressed\n"); compress = false; iscompressed = true; break; default: logmsg(LOG_ERR, "unknown compression type %d on %s", kdhl.compression, device); break; } } else { if (verbose) printf("magic mismatch on last dump header on %s\n", device); status = STATUS_BAD; if (force == 0) goto closefd; if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) { if (verbose) printf("forcing magic on %s\n", device); memcpy(kdhl.magic, KERNELDUMPMAGIC, sizeof(kdhl.magic)); } else { logmsg(LOG_ERR, "unable to force dump - bad magic"); goto closefd; } if (dtoh32(kdhl.version) != KERNELDUMPVERSION) { logmsg(LOG_ERR, "unknown version (%d) in last dump header on %s", dtoh32(kdhl.version), device); status = STATUS_BAD; if (force == 0) goto closefd; } } nfound++; if (clear) goto nuke; if (kerneldump_parity(&kdhl)) { logmsg(LOG_ERR, "parity error on last dump header on %s", device); nerr++; status = STATUS_BAD; if (force == 0) goto closefd; } dumpextent = dtoh64(kdhl.dumpextent); dumplength = dtoh64(kdhl.dumplength); dumpkeysize = dtoh32(kdhl.dumpkeysize); firsthd = lasthd - dumpextent - sectorsize - dumpkeysize; if (lseek(fddev, firsthd, SEEK_SET) != firsthd || read(fddev, temp, sectorsize) != (ssize_t)sectorsize) { logmsg(LOG_ERR, "error reading first dump header at offset %lld in %s: %m", (long long)firsthd, device); nerr++; goto closefd; } memcpy(&kdhf, temp, sizeof(kdhf)); if (verbose >= 2) { printf("First dump headers:\n"); printheader(xostdout, &kdhf, device, bounds, -1); printf("\nLast dump headers:\n"); printheader(xostdout, &kdhl, device, bounds, -1); printf("\n"); } if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) { logmsg(LOG_ERR, "first and last dump headers disagree on %s", device); nerr++; status = STATUS_BAD; if (force == 0) goto closefd; } else { status = STATUS_GOOD; } if (checkfor) { printf("A dump exists on %s\n", device); close(fddev); exit(0); } if (kdhl.panicstring[0] != '\0') logmsg(LOG_ALERT, "reboot after panic: %.*s", (int)sizeof(kdhl.panicstring), kdhl.panicstring); else logmsg(LOG_ALERT, "reboot"); if (verbose) printf("Checking for available free space\n"); if (!check_space(savedir, savedirfd, dumplength, bounds)) { nerr++; goto closefd; } writebounds(savedirfd, bounds + 1); saved_dump_remove(savedirfd, bounds); snprintf(infoname, sizeof(infoname), "info.%d", bounds); /* * Create or overwrite any existing dump header files. */ if ((info = xfopenat(savedirfd, infoname, O_WRONLY | O_CREAT | O_TRUNC, "w", 0600)) == NULL) { logmsg(LOG_ERR, "open(%s): %m", infoname); nerr++; goto closefd; } isencrypted = (dumpkeysize > 0); if (compress) snprintf(corename, sizeof(corename), "%s.%d.gz", istextdump ? "textdump.tar" : (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds); else if (iscompressed && !isencrypted) snprintf(corename, sizeof(corename), "vmcore.%d.%s", bounds, (kdhl.compression == KERNELDUMP_COMP_GZIP) ? "gz" : "zst"); else snprintf(corename, sizeof(corename), "%s.%d", istextdump ? "textdump.tar" : (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds); fdcore = openat(savedirfd, corename, O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fdcore < 0) { logmsg(LOG_ERR, "open(%s): %m", corename); fclose(info); nerr++; goto closefd; } if (compress) core = zdopen(fdcore, "w"); else core = fdopen(fdcore, "w"); if (core == NULL) { logmsg(LOG_ERR, "%s: %m", corename); (void)close(fdcore); (void)fclose(info); nerr++; goto closefd; } fdcore = -1; xostyle = xo_get_style(NULL); xoinfo = xo_create_to_file(info, xostyle, 0); if (xoinfo == NULL) { logmsg(LOG_ERR, "%s: %m", infoname); fclose(info); nerr++; goto closeall; } xo_open_container_h(xoinfo, "crashdump"); if (verbose) printheader(xostdout, &kdhl, device, bounds, status); printheader(xoinfo, &kdhl, device, bounds, status); xo_close_container_h(xoinfo, "crashdump"); xo_flush_h(xoinfo); xo_finish_h(xoinfo); fclose(info); if (isencrypted) { dumpkey = calloc(1, dumpkeysize); if (dumpkey == NULL) { logmsg(LOG_ERR, "Unable to allocate kernel dump key."); nerr++; goto closeall; } if (read(fddev, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) { logmsg(LOG_ERR, "Unable to read kernel dump key: %m."); nerr++; goto closeall; } snprintf(keyname, sizeof(keyname), "key.%d", bounds); ret = writekey(savedirfd, keyname, dumpkey, dumpkeysize); explicit_bzero(dumpkey, dumpkeysize); if (!ret) { nerr++; goto closeall; } } logmsg(LOG_NOTICE, "writing %s%score to %s/%s", isencrypted ? "encrypted " : "", compress ? "compressed " : "", savedir, corename); if (istextdump) { if (DoTextdumpFile(fddev, dumplength, lasthd, buf, device, corename, core) < 0) goto closeall; } else { if (DoRegularFile(fddev, dumplength, sectorsize, !(compress || iscompressed || isencrypted), buf, device, corename, core) < 0) { goto closeall; } } if (verbose) printf("\n"); if (fclose(core) < 0) { logmsg(LOG_ERR, "error on %s: %m", corename); nerr++; goto closefd; } symlinks_remove(savedirfd); if (symlinkat(infoname, savedirfd, "info.last") == -1) { logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m", savedir, "info.last"); } if (isencrypted) { if (symlinkat(keyname, savedirfd, "key.last") == -1) { logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m", savedir, "key.last"); } } if (compress || iscompressed) { snprintf(linkname, sizeof(linkname), "%s.last.%s", istextdump ? "textdump.tar" : (isencrypted ? "vmcore_encrypted" : "vmcore"), (kdhl.compression == KERNELDUMP_COMP_ZSTD) ? "zst" : "gz"); } else { snprintf(linkname, sizeof(linkname), "%s.last", istextdump ? "textdump.tar" : (isencrypted ? "vmcore_encrypted" : "vmcore")); } if (symlinkat(corename, savedirfd, linkname) == -1) { logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m", savedir, linkname); } nsaved++; if (verbose) printf("dump saved\n"); nuke: if (!keep) { if (verbose) printf("clearing dump header\n"); memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic)); memcpy(temp, &kdhl, sizeof(kdhl)); if (lseek(fddev, lasthd, SEEK_SET) != lasthd || write(fddev, temp, sectorsize) != (ssize_t)sectorsize) logmsg(LOG_ERR, "error while clearing the dump header: %m"); } xo_close_container_h(xostdout, "crashdump"); xo_finish_h(xostdout); free(dumpkey); free(temp); close(fddev); return; closeall: fclose(core); closefd: free(dumpkey); free(temp); close(fddev); } static char ** enum_dumpdevs(int *argcp) { struct fstab *fsp; char **argv; int argc, n; /* * We cannot use getfsent(3) in capability mode, so we must * scan /etc/fstab and build up a list of candidate devices * before proceeding. */ argc = 0; n = 8; argv = malloc(n * sizeof(*argv)); if (argv == NULL) { logmsg(LOG_ERR, "malloc(): %m"); exit(1); } for (;;) { fsp = getfsent(); if (fsp == NULL) break; if (strcmp(fsp->fs_vfstype, "swap") != 0 && strcmp(fsp->fs_vfstype, "dump") != 0) continue; if (argc >= n) { n *= 2; argv = realloc(argv, n * sizeof(*argv)); if (argv == NULL) { logmsg(LOG_ERR, "realloc(): %m"); exit(1); } } argv[argc] = strdup(fsp->fs_spec); if (argv[argc] == NULL) { logmsg(LOG_ERR, "strdup(): %m"); exit(1); } argc++; } *argcp = argc; return (argv); } static void init_caps(int argc, char **argv) { cap_rights_t rights; cap_channel_t *capcas; capcas = cap_init(); if (capcas == NULL) { logmsg(LOG_ERR, "cap_init(): %m"); exit(1); } /* * The fileargs capability does not currently provide a way to limit * ioctls. */ (void)cap_rights_init(&rights, CAP_PREAD, CAP_WRITE, CAP_IOCTL); capfa = fileargs_init(argc, argv, checkfor || keep ? O_RDONLY : O_RDWR, - 0, &rights); + 0, &rights, FA_OPEN); if (capfa == NULL) { logmsg(LOG_ERR, "fileargs_init(): %m"); exit(1); } caph_cache_catpages(); caph_cache_tzdata(); if (caph_enter_casper() != 0) { logmsg(LOG_ERR, "caph_enter_casper(): %m"); exit(1); } capsyslog = cap_service_open(capcas, "system.syslog"); if (capsyslog == NULL) { logmsg(LOG_ERR, "cap_service_open(system.syslog): %m"); exit(1); } cap_close(capcas); } static void usage(void) { xo_error("%s\n%s\n%s\n", "usage: savecore -c [-v] [device ...]", " savecore -C [-v] [device ...]", " savecore [-fkvz] [-m maxdumps] [directory [device ...]]"); exit(1); } int main(int argc, char **argv) { cap_rights_t rights; const char *savedir; int i, ch, error, savedirfd; checkfor = compress = clear = force = keep = verbose = 0; nfound = nsaved = nerr = 0; savedir = "."; openlog("savecore", LOG_PERROR, LOG_DAEMON); signal(SIGINFO, infohandler); argc = xo_parse_args(argc, argv); if (argc < 0) exit(1); while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1) switch(ch) { case 'C': checkfor = 1; break; case 'c': clear = 1; break; case 'f': force = 1; break; case 'k': keep = 1; break; case 'm': maxdumps = atoi(optarg); if (maxdumps <= 0) { logmsg(LOG_ERR, "Invalid maxdump value"); exit(1); } break; case 'v': verbose++; break; case 'z': compress = 1; break; case '?': default: usage(); } if (checkfor && (clear || force || keep)) usage(); if (clear && (compress || keep)) usage(); if (maxdumps > 0 && (checkfor || clear)) usage(); argc -= optind; argv += optind; if (argc >= 1 && !checkfor && !clear) { error = chdir(argv[0]); if (error) { logmsg(LOG_ERR, "chdir(%s): %m", argv[0]); exit(1); } savedir = argv[0]; argc--; argv++; } if (argc == 0) argv = enum_dumpdevs(&argc); savedirfd = open(savedir, O_RDONLY | O_DIRECTORY); if (savedirfd < 0) { logmsg(LOG_ERR, "open(%s): %m", savedir); exit(1); } (void)cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, CAP_FSTATAT, CAP_FSTATFS, CAP_PREAD, CAP_SYMLINKAT, CAP_FTRUNCATE, CAP_UNLINKAT, CAP_WRITE); if (caph_rights_limit(savedirfd, &rights) < 0) { logmsg(LOG_ERR, "cap_rights_limit(): %m"); exit(1); } /* Enter capability mode. */ init_caps(argc, argv); for (i = 0; i < argc; i++) DoFile(savedir, savedirfd, argv[i]); /* Emit minimal output. */ if (nfound == 0) { if (checkfor) { if (verbose) printf("No dump exists\n"); exit(1); } if (verbose) logmsg(LOG_WARNING, "no dumps found"); } else if (nsaved == 0) { if (nerr != 0) { if (verbose) logmsg(LOG_WARNING, "unsaved dumps found but not saved"); exit(1); } else if (verbose) logmsg(LOG_WARNING, "no unsaved dumps found"); } return (0); } static void infohandler(int sig __unused) { got_siginfo = 1; } Index: head/usr.bin/brandelf/brandelf.c =================================================================== --- head/usr.bin/brandelf/brandelf.c (revision 346315) +++ head/usr.bin/brandelf/brandelf.c (revision 346316) @@ -1,234 +1,234 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2000, 2001 David O'Brien * Copyright (c) 1996 Søren Schmidt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include static int elftype(const char *); static const char *iselftype(int); static void printelftypes(void); static void usage(void); struct ELFtypes { const char *str; int value; }; /* XXX - any more types? */ static struct ELFtypes elftypes[] = { { "FreeBSD", ELFOSABI_FREEBSD }, { "Linux", ELFOSABI_LINUX }, { "Solaris", ELFOSABI_SOLARIS }, { "SVR4", ELFOSABI_SYSV } }; int main(int argc, char **argv) { const char *strtype = "FreeBSD"; int ch, flags, retval, type; bool change, force, listed; fileargs_t *fa; cap_rights_t rights; type = ELFOSABI_FREEBSD; retval = 0; change = false; force = false; listed = false; while ((ch = getopt(argc, argv, "f:lt:v")) != -1) switch (ch) { case 'f': if (change) errx(1, "f option incompatible with t option"); force = true; type = atoi(optarg); if (errno == ERANGE || type < 0 || type > 255) { warnx("invalid argument to option f: %s", optarg); usage(); } break; case 'l': printelftypes(); listed = true; break; case 'v': /* does nothing */ break; case 't': if (force) errx(1, "t option incompatible with f option"); change = true; strtype = optarg; break; default: usage(); } argc -= optind; argv += optind; if (argc == 0) { if (listed) exit(0); else { warnx("no file(s) specified"); usage(); } } if (!force && (type = elftype(strtype)) == -1) { warnx("invalid ELF type '%s'", strtype); printelftypes(); usage(); } flags = change || force ? O_RDWR : O_RDONLY; cap_rights_init(&rights, CAP_READ, CAP_SEEK); if (flags == O_RDWR) cap_rights_set(&rights, CAP_WRITE); - fa = fileargs_init(argc, argv, flags, 0, &rights); + fa = fileargs_init(argc, argv, flags, 0, &rights, FA_OPEN); if (fa == NULL) errx(1, "unable to init casper"); caph_cache_catpages(); if (caph_limit_stdio() < 0 || caph_enter_casper() < 0) err(1, "unable to enter capability mode"); while (argc != 0) { int fd; char buffer[EI_NIDENT]; if ((fd = fileargs_open(fa, argv[0])) < 0) { warn("error opening file %s", argv[0]); retval = 1; goto fail; } if (read(fd, buffer, EI_NIDENT) < EI_NIDENT) { warnx("file '%s' too short", argv[0]); retval = 1; goto fail; } if (buffer[0] != ELFMAG0 || buffer[1] != ELFMAG1 || buffer[2] != ELFMAG2 || buffer[3] != ELFMAG3) { warnx("file '%s' is not ELF format", argv[0]); retval = 1; goto fail; } if (!change && !force) { fprintf(stdout, "File '%s' is of brand '%s' (%u).\n", argv[0], iselftype(buffer[EI_OSABI]), buffer[EI_OSABI]); if (!iselftype(type)) { warnx("ELF ABI Brand '%u' is unknown", type); printelftypes(); } } else { buffer[EI_OSABI] = type; lseek(fd, 0, SEEK_SET); if (write(fd, buffer, EI_NIDENT) != EI_NIDENT) { warn("error writing %s %d", argv[0], fd); retval = 1; goto fail; } } fail: close(fd); argc--; argv++; } fileargs_free(fa); return (retval); } static void usage(void) { (void)fprintf(stderr, "usage: brandelf [-lv] [-f ELF_ABI_number] [-t string] file ...\n"); exit(1); } static const char * iselftype(int etype) { size_t elfwalk; for (elfwalk = 0; elfwalk < nitems(elftypes); elfwalk++) if (etype == elftypes[elfwalk].value) return (elftypes[elfwalk].str); return (0); } static int elftype(const char *elfstrtype) { size_t elfwalk; for (elfwalk = 0; elfwalk < nitems(elftypes); elfwalk++) if (strcasecmp(elfstrtype, elftypes[elfwalk].str) == 0) return (elftypes[elfwalk].value); return (-1); } static void printelftypes(void) { size_t elfwalk; fprintf(stderr, "known ELF types are: "); for (elfwalk = 0; elfwalk < nitems(elftypes); elfwalk++) fprintf(stderr, "%s(%u) ", elftypes[elfwalk].str, elftypes[elfwalk].value); fprintf(stderr, "\n"); } Index: head/usr.bin/head/head.c =================================================================== --- head/usr.bin/head/head.c (revision 346315) +++ head/usr.bin/head/head.c (revision 346316) @@ -1,215 +1,215 @@ /* * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1980, 1987, 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1980, 1987, 1992, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)head.c 8.2 (Berkeley) 5/4/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * head - give the first few lines of a stream or of each of a set of files * * Bill Joy UCB August 24, 1977 */ static void head(FILE *, int); static void head_bytes(FILE *, off_t); static void obsolete(char *[]); static void usage(void); static const struct option long_opts[] = { {"bytes", required_argument, NULL, 'c'}, {"lines", required_argument, NULL, 'n'}, {NULL, no_argument, NULL, 0} }; int main(int argc, char *argv[]) { FILE *fp; char *ep; off_t bytecnt; int ch, first, linecnt, eval; fileargs_t *fa; cap_rights_t rights; linecnt = -1; eval = 0; bytecnt = -1; obsolete(argv); while ((ch = getopt_long(argc, argv, "+n:c:", long_opts, NULL)) != -1) { switch(ch) { case 'c': bytecnt = strtoimax(optarg, &ep, 10); if (*ep || bytecnt <= 0) errx(1, "illegal byte count -- %s", optarg); break; case 'n': linecnt = strtol(optarg, &ep, 10); if (*ep || linecnt <= 0) errx(1, "illegal line count -- %s", optarg); break; case '?': default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; fa = fileargs_init(argc, argv, O_RDONLY, 0, - cap_rights_init(&rights, CAP_READ, CAP_FSTAT, CAP_FCNTL)); + cap_rights_init(&rights, CAP_READ, CAP_FSTAT, CAP_FCNTL), FA_OPEN); if (fa == NULL) errx(1, "unable to init casper"); caph_cache_catpages(); if (caph_limit_stdio() < 0 || caph_enter_casper() < 0) err(1, "unable to enter capability mode"); if (linecnt != -1 && bytecnt != -1) errx(1, "can't combine line and byte counts"); if (linecnt == -1) linecnt = 10; if (*argv != NULL) { for (first = 1; *argv != NULL; ++argv) { if ((fp = fileargs_fopen(fa, *argv, "r")) == NULL) { warn("%s", *argv); eval = 1; continue; } if (argc > 1) { (void)printf("%s==> %s <==\n", first ? "" : "\n", *argv); first = 0; } if (bytecnt == -1) head(fp, linecnt); else head_bytes(fp, bytecnt); (void)fclose(fp); } } else if (bytecnt == -1) head(stdin, linecnt); else head_bytes(stdin, bytecnt); fileargs_free(fa); exit(eval); } static void head(FILE *fp, int cnt) { char *cp; size_t error, readlen; while (cnt != 0 && (cp = fgetln(fp, &readlen)) != NULL) { error = fwrite(cp, sizeof(char), readlen, stdout); if (error != readlen) err(1, "stdout"); cnt--; } } static void head_bytes(FILE *fp, off_t cnt) { char buf[4096]; size_t readlen; while (cnt) { if ((uintmax_t)cnt < sizeof(buf)) readlen = cnt; else readlen = sizeof(buf); readlen = fread(buf, sizeof(char), readlen, fp); if (readlen == 0) break; if (fwrite(buf, sizeof(char), readlen, stdout) != readlen) err(1, "stdout"); cnt -= readlen; } } static void obsolete(char *argv[]) { char *ap; while ((ap = *++argv)) { /* Return if "--" or not "-[0-9]*". */ if (ap[0] != '-' || ap[1] == '-' || !isdigit(ap[1])) return; if ((ap = malloc(strlen(*argv) + 2)) == NULL) err(1, NULL); ap[0] = '-'; ap[1] = 'n'; (void)strcpy(ap + 2, *argv + 1); *argv = ap; } } static void usage(void) { (void)fprintf(stderr, "usage: head [-n lines | -c bytes] [file ...]\n"); exit(1); } Index: head/usr.bin/wc/wc.c =================================================================== --- head/usr.bin/wc/wc.c (revision 346315) +++ head/usr.bin/wc/wc.c (revision 346316) @@ -1,372 +1,372 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1980, 1987, 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1980, 1987, 1991, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #if 0 #ifndef lint static char sccsid[] = "@(#)wc.c 8.1 (Berkeley) 6/6/93"; #endif /* not lint */ #endif #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static fileargs_t *fa; static uintmax_t tlinect, twordct, tcharct, tlongline; static int doline, doword, dochar, domulti, dolongline; static volatile sig_atomic_t siginfo; static xo_handle_t *stderr_handle; static void show_cnt(const char *file, uintmax_t linect, uintmax_t wordct, uintmax_t charct, uintmax_t llct); static int cnt(const char *); static void usage(void); static void siginfo_handler(int sig __unused) { siginfo = 1; } static void reset_siginfo(void) { signal(SIGINFO, SIG_DFL); siginfo = 0; } int main(int argc, char *argv[]) { int ch, errors, total; cap_rights_t rights; (void) setlocale(LC_CTYPE, ""); argc = xo_parse_args(argc, argv); if (argc < 0) return (argc); while ((ch = getopt(argc, argv, "clmwL")) != -1) switch((char)ch) { case 'l': doline = 1; break; case 'w': doword = 1; break; case 'c': dochar = 1; domulti = 0; break; case 'L': dolongline = 1; break; case 'm': domulti = 1; dochar = 0; break; case '?': default: usage(); } argv += optind; argc -= optind; (void)signal(SIGINFO, siginfo_handler); fa = fileargs_init(argc, argv, O_RDONLY, 0, - cap_rights_init(&rights, CAP_READ, CAP_FSTAT)); + cap_rights_init(&rights, CAP_READ, CAP_FSTAT), FA_OPEN); if (fa == NULL) { xo_warn("Unable to init casper"); exit(1); } caph_cache_catpages(); if (caph_limit_stdio() < 0) { xo_warn("Unable to limit stdio"); fileargs_free(fa); exit(1); } if (caph_enter_casper() < 0) { xo_warn("Unable to enter capability mode"); fileargs_free(fa); exit(1); } /* Wc's flags are on by default. */ if (doline + doword + dochar + domulti + dolongline == 0) doline = doword = dochar = 1; stderr_handle = xo_create_to_file(stderr, XO_STYLE_TEXT, 0); xo_open_container("wc"); xo_open_list("file"); errors = 0; total = 0; if (!*argv) { xo_open_instance("file"); if (cnt((char *)NULL) != 0) ++errors; xo_close_instance("file"); } else { do { xo_open_instance("file"); if (cnt(*argv) != 0) ++errors; xo_close_instance("file"); ++total; } while(*++argv); } xo_close_list("file"); if (total > 1) { xo_open_container("total"); show_cnt("total", tlinect, twordct, tcharct, tlongline); xo_close_container("total"); } fileargs_free(fa); xo_close_container("wc"); xo_finish(); exit(errors == 0 ? 0 : 1); } static void show_cnt(const char *file, uintmax_t linect, uintmax_t wordct, uintmax_t charct, uintmax_t llct) { xo_handle_t *xop; if (!siginfo) xop = NULL; else { xop = stderr_handle; siginfo = 0; } if (doline) xo_emit_h(xop, " {:lines/%7ju/%ju}", linect); if (doword) xo_emit_h(xop, " {:words/%7ju/%ju}", wordct); if (dochar || domulti) xo_emit_h(xop, " {:characters/%7ju/%ju}", charct); if (dolongline) xo_emit_h(xop, " {:long-lines/%7ju/%ju}", llct); if (file != NULL) xo_emit_h(xop, " {:filename/%s}\n", file); else xo_emit_h(xop, "\n"); } static int cnt(const char *file) { struct stat sb; uintmax_t linect, wordct, charct, llct, tmpll; int fd, len, warned; size_t clen; short gotsp; u_char *p; u_char buf[MAXBSIZE]; wchar_t wch; mbstate_t mbs; linect = wordct = charct = llct = tmpll = 0; if (file == NULL) fd = STDIN_FILENO; else if ((fd = fileargs_open(fa, file)) < 0) { xo_warn("%s: open", file); return (1); } if (doword || (domulti && MB_CUR_MAX != 1)) goto word; /* * If all we need is the number of characters and it's a regular file, * just stat it. */ if (doline == 0 && dolongline == 0) { if (fstat(fd, &sb)) { xo_warn("%s: fstat", file); (void)close(fd); return (1); } if (S_ISREG(sb.st_mode)) { reset_siginfo(); charct = sb.st_size; show_cnt(file, linect, wordct, charct, llct); tcharct += charct; (void)close(fd); return (0); } } /* * For files we can't stat, or if we need line counting, slurp the * file. Line counting is split out because it's a lot faster to get * lines than to get words, since the word count requires locale * handling. */ while ((len = read(fd, buf, MAXBSIZE))) { if (len == -1) { xo_warn("%s: read", file); (void)close(fd); return (1); } if (siginfo) show_cnt(file, linect, wordct, charct, llct); charct += len; if (doline || dolongline) { for (p = buf; len--; ++p) if (*p == '\n') { if (tmpll > llct) llct = tmpll; tmpll = 0; ++linect; } else tmpll++; } } reset_siginfo(); if (doline) tlinect += linect; if (dochar) tcharct += charct; if (dolongline && llct > tlongline) tlongline = llct; show_cnt(file, linect, wordct, charct, llct); (void)close(fd); return (0); /* Do it the hard way... */ word: gotsp = 1; warned = 0; memset(&mbs, 0, sizeof(mbs)); while ((len = read(fd, buf, MAXBSIZE)) != 0) { if (len == -1) { xo_warn("%s: read", file != NULL ? file : "stdin"); (void)close(fd); return (1); } p = buf; while (len > 0) { if (siginfo) show_cnt(file, linect, wordct, charct, llct); if (!domulti || MB_CUR_MAX == 1) { clen = 1; wch = (unsigned char)*p; } else if ((clen = mbrtowc(&wch, p, len, &mbs)) == (size_t)-1) { if (!warned) { errno = EILSEQ; xo_warn("%s", file != NULL ? file : "stdin"); warned = 1; } memset(&mbs, 0, sizeof(mbs)); clen = 1; wch = (unsigned char)*p; } else if (clen == (size_t)-2) break; else if (clen == 0) clen = 1; charct++; if (wch != L'\n') tmpll++; len -= clen; p += clen; if (wch == L'\n') { if (tmpll > llct) llct = tmpll; tmpll = 0; ++linect; } if (iswspace(wch)) gotsp = 1; else if (gotsp) { gotsp = 0; ++wordct; } } } reset_siginfo(); if (domulti && MB_CUR_MAX > 1) if (mbrtowc(NULL, NULL, 0, &mbs) == (size_t)-1 && !warned) xo_warn("%s", file != NULL ? file : "stdin"); if (doline) tlinect += linect; if (doword) twordct += wordct; if (dochar || domulti) tcharct += charct; if (dolongline && llct > tlongline) tlongline = llct; show_cnt(file, linect, wordct, charct, llct); (void)close(fd); return (0); } static void usage(void) { xo_error("usage: wc [-Lclmw] [file ...]\n"); exit(1); }