xref: /freebsd/sbin/dump/main.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/1/95";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/disklabel.h>
52 
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ffs/fs.h>
55 
56 #include <protocols/dumprestore.h>
57 
58 #include <ctype.h>
59 #include <err.h>
60 #include <fcntl.h>
61 #include <fstab.h>
62 #include <inttypes.h>
63 #include <limits.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <timeconv.h>
69 #include <unistd.h>
70 
71 #include "dump.h"
72 #include "pathnames.h"
73 
74 int	notify = 0;	/* notify operator flag */
75 int	blockswritten = 0;	/* number of blocks written on current tape */
76 int	tapeno = 0;	/* current tape number */
77 int	density = 0;	/* density in bytes/0.1" " <- this is for hilit19 */
78 int	ntrec = NTREC;	/* # tape blocks in each tape record */
79 int	cartridge = 0;	/* Assume non-cartridge tape */
80 int	dokerberos = 0;	/* Use Kerberos authentication */
81 long	dev_bsize = 1;	/* recalculated below */
82 long	blocksperfile;	/* output blocks per file */
83 char	*host = NULL;	/* remote host (if any) */
84 
85 /*
86  * Possible superblock locations ordered from most to least likely.
87  */
88 static int sblock_try[] = SBLOCKSEARCH;
89 
90 static long numarg(const char *, long, long);
91 static void obsolete(int *, char **[]);
92 static void usage(void) __dead2;
93 
94 int
95 main(int argc, char *argv[])
96 {
97 	struct stat sb;
98 	ino_t ino;
99 	int dirty;
100 	union dinode *dp;
101 	struct	fstab *dt;
102 	char *map;
103 	int ch, mode;
104 	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
105 	int just_estimate = 0;
106 	ino_t maxino;
107 	char *tmsg;
108 
109 	spcl.c_date = _time_to_time64(time(NULL));
110 
111 	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
112 	if ((tape = getenv("TAPE")) == NULL)
113 		tape = _PATH_DEFTAPE;
114 	dumpdates = _PATH_DUMPDATES;
115 	temp = _PATH_DTMP;
116 	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
117 		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
118 	level = '0';
119 
120 	if (argc < 2)
121 		usage();
122 
123 	obsolete(&argc, &argv);
124 #ifdef KERBEROS
125 #define optstring "0123456789aB:b:cd:f:h:kns:ST:uWwD:"
126 #else
127 #define optstring "0123456789aB:b:cd:f:h:ns:ST:uWwD:"
128 #endif
129 	while ((ch = getopt(argc, argv, optstring)) != -1)
130 #undef optstring
131 		switch (ch) {
132 		/* dump level */
133 		case '0': case '1': case '2': case '3': case '4':
134 		case '5': case '6': case '7': case '8': case '9':
135 			level = ch;
136 			break;
137 
138 		case 'a':		/* `auto-size', Write to EOM. */
139 			unlimited = 1;
140 			break;
141 
142 		case 'B':		/* blocks per output file */
143 			blocksperfile = numarg("number of blocks per file",
144 			    1L, 0L);
145 			break;
146 
147 		case 'b':		/* blocks per tape write */
148 			ntrec = numarg("number of blocks per write",
149 			    1L, 1000L);
150 			break;
151 
152 		case 'c':		/* Tape is cart. not 9-track */
153 			cartridge = 1;
154 			break;
155 
156 		case 'd':		/* density, in bits per inch */
157 			density = numarg("density", 10L, 327670L) / 10;
158 			if (density >= 625 && !bflag)
159 				ntrec = HIGHDENSITYTREC;
160 			break;
161 
162 		case 'f':		/* output file */
163 			tape = optarg;
164 			break;
165 
166 		case 'D':
167 			dumpdates = optarg;
168 			break;
169 
170 		case 'h':
171 			honorlevel = numarg("honor level", 0L, 10L);
172 			break;
173 
174 #ifdef KERBEROS
175 		case 'k':
176 			dokerberos = 1;
177 			break;
178 #endif
179 
180 		case 'n':		/* notify operators */
181 			notify = 1;
182 			break;
183 
184 		case 's':		/* tape size, feet */
185 			tsize = numarg("tape size", 1L, 0L) * 12 * 10;
186 			break;
187 
188 		case 'S':               /* exit after estimating # of tapes */
189 			just_estimate = 1;
190 			break;
191 
192 		case 'T':		/* time of last dump */
193 			spcl.c_ddate = unctime(optarg);
194 			if (spcl.c_ddate < 0) {
195 				(void)fprintf(stderr, "bad time \"%s\"\n",
196 				    optarg);
197 				exit(X_STARTUP);
198 			}
199 			Tflag = 1;
200 			lastlevel = '?';
201 			break;
202 
203 		case 'u':		/* update /etc/dumpdates */
204 			uflag = 1;
205 			break;
206 
207 		case 'W':		/* what to do */
208 		case 'w':
209 			lastdump(ch);
210 			exit(X_FINOK);	/* do nothing else */
211 
212 		default:
213 			usage();
214 		}
215 	argc -= optind;
216 	argv += optind;
217 
218 	if (argc < 1) {
219 		(void)fprintf(stderr, "Must specify disk or file system\n");
220 		exit(X_STARTUP);
221 	}
222 	disk = *argv++;
223 	argc--;
224 	if (argc >= 1) {
225 		(void)fprintf(stderr, "Unknown arguments to dump:");
226 		while (argc--)
227 			(void)fprintf(stderr, " %s", *argv++);
228 		(void)fprintf(stderr, "\n");
229 		exit(X_STARTUP);
230 	}
231 	if (Tflag && uflag) {
232 	        (void)fprintf(stderr,
233 		    "You cannot use the T and u flags together.\n");
234 		exit(X_STARTUP);
235 	}
236 	if (strcmp(tape, "-") == 0) {
237 		pipeout++;
238 		tape = "standard output";
239 	}
240 
241 	if (blocksperfile)
242 		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
243 	else if (!unlimited) {
244 		/*
245 		 * Determine how to default tape size and density
246 		 *
247 		 *         	density				tape size
248 		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
249 		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
250 		 * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
251 		 *						(450*4 - slop)
252 		 * hilit19 hits again: "
253 		 */
254 		if (density == 0)
255 			density = cartridge ? 100 : 160;
256 		if (tsize == 0)
257 			tsize = cartridge ? 1700L*120L : 2300L*120L;
258 	}
259 
260 	if (strchr(tape, ':')) {
261 		host = tape;
262 		tape = strchr(host, ':');
263 		*tape++ = '\0';
264 #ifdef RDUMP
265 		if (index(tape, '\n')) {
266 		    (void)fprintf(stderr, "invalid characters in tape\n");
267 		    exit(X_STARTUP);
268 		}
269 		if (rmthost(host) == 0)
270 			exit(X_STARTUP);
271 #else
272 		(void)fprintf(stderr, "remote dump not enabled\n");
273 		exit(X_STARTUP);
274 #endif
275 	}
276 	(void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
277 
278 	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
279 		signal(SIGHUP, sig);
280 	if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
281 		signal(SIGTRAP, sig);
282 	if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
283 		signal(SIGFPE, sig);
284 	if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
285 		signal(SIGBUS, sig);
286 	if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
287 		signal(SIGSEGV, sig);
288 	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
289 		signal(SIGTERM, sig);
290 	if (signal(SIGINT, interrupt) == SIG_IGN)
291 		signal(SIGINT, SIG_IGN);
292 
293 	getfstab();		/* /etc/fstab snarfed */
294 	/*
295 	 *	disk can be either the full special file name,
296 	 *	the suffix of the special file name,
297 	 *	the special name missing the leading '/',
298 	 *	the file system name with or without the leading '/'.
299 	 */
300 	dt = fstabsearch(disk);
301 	if (dt != NULL) {
302 		disk = rawname(dt->fs_spec);
303 		(void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
304 		(void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
305 	} else {
306 		(void)strncpy(spcl.c_dev, disk, NAMELEN);
307 		(void)strncpy(spcl.c_filesys, "an unlisted file system",
308 		    NAMELEN);
309 	}
310 	spcl.c_dev[NAMELEN-1]='\0';
311 	spcl.c_filesys[NAMELEN-1]='\0';
312 	(void)strcpy(spcl.c_label, "none");
313 	(void)gethostname(spcl.c_host, NAMELEN);
314 	spcl.c_level = level - '0';
315 	spcl.c_type = TS_TAPE;
316 	if (!Tflag)
317 	        getdumptime();		/* /etc/dumpdates snarfed */
318 
319 	if (spcl.c_date == 0) {
320 		tmsg = "the epoch\n";
321 	} else {
322 		time_t t = _time64_to_time(spcl.c_date);
323 		tmsg = ctime(&t);
324 	}
325 	msg("Date of this level %c dump: %s", level, tmsg);
326 	if (spcl.c_ddate == 0) {
327 		tmsg = "the epoch\n";
328 	} else {
329 		time_t t = _time64_to_time(spcl.c_ddate);
330 		tmsg = ctime(&t);
331 	}
332  	msg("Date of last level %c dump: %s", lastlevel, tmsg);
333 	msg("Dumping %s ", disk);
334 	if (dt != NULL)
335 		msgtail("(%s) ", dt->fs_file);
336 	if (host)
337 		msgtail("to %s on host %s\n", tape, host);
338 	else
339 		msgtail("to %s\n", tape);
340 
341 	if ((diskfd = open(disk, O_RDONLY)) < 0)
342 		err(X_STARTUP, "Cannot open %s", disk);
343 	if (fstat(diskfd, &sb) != 0)
344 		err(X_STARTUP, "%s: stat", disk);
345 	if (S_ISDIR(sb.st_mode))
346 		errx(X_STARTUP, "%s: unknown file system", disk);
347 	sync();
348 	sblock = (struct fs *)sblock_buf;
349 	for (i = 0; sblock_try[i] != -1; i++) {
350 		bread(sblock_try[i] >> dev_bshift, (char *) sblock, SBLOCKSIZE);
351 		if ((sblock->fs_magic == FS_UFS1_MAGIC ||
352 		     (sblock->fs_magic == FS_UFS2_MAGIC &&
353 		      sblock->fs_sblockloc ==
354 			  numfrags(sblock, sblock_try[i]))) &&
355 		    sblock->fs_bsize <= MAXBSIZE &&
356 		    sblock->fs_bsize >= sizeof(struct fs))
357 			break;
358 	}
359 	if (sblock_try[i] == -1)
360 		quit("Cannot find file system superblock\n");
361 	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
362 	dev_bshift = ffs(dev_bsize) - 1;
363 	if (dev_bsize != (1 << dev_bshift))
364 		quit("dev_bsize (%ld) is not a power of 2", dev_bsize);
365 	tp_bshift = ffs(TP_BSIZE) - 1;
366 	if (TP_BSIZE != (1 << tp_bshift))
367 		quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
368 	maxino = sblock->fs_ipg * sblock->fs_ncg;
369 	mapsize = roundup(howmany(maxino, CHAR_BIT), TP_BSIZE);
370 	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
371 	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
372 	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
373 	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
374 
375 	nonodump = spcl.c_level < honorlevel;
376 
377 	passno = 1;
378 	setproctitle("%s: pass 1: regular files", disk);
379 	msg("mapping (Pass I) [regular files]\n");
380 	anydirskipped = mapfiles(maxino, &tapesize);
381 
382 	passno = 2;
383 	setproctitle("%s: pass 2: directories", disk);
384 	msg("mapping (Pass II) [directories]\n");
385 	while (anydirskipped) {
386 		anydirskipped = mapdirs(maxino, &tapesize);
387 	}
388 
389 	if (pipeout || unlimited) {
390 		tapesize += 10;	/* 10 trailer blocks */
391 		msg("estimated %ld tape blocks.\n", tapesize);
392 	} else {
393 		double fetapes;
394 
395 		if (blocksperfile)
396 			fetapes = (double) tapesize / blocksperfile;
397 		else if (cartridge) {
398 			/* Estimate number of tapes, assuming streaming stops at
399 			   the end of each block written, and not in mid-block.
400 			   Assume no erroneous blocks; this can be compensated
401 			   for with an artificially low tape size. */
402 			fetapes =
403 			(	  (double) tapesize	/* blocks */
404 				* TP_BSIZE	/* bytes/block */
405 				* (1.0/density)	/* 0.1" / byte " */
406 			  +
407 				  (double) tapesize	/* blocks */
408 				* (1.0/ntrec)	/* streaming-stops per block */
409 				* 15.48		/* 0.1" / streaming-stop " */
410 			) * (1.0 / tsize );	/* tape / 0.1" " */
411 		} else {
412 			/* Estimate number of tapes, for old fashioned 9-track
413 			   tape */
414 			int tenthsperirg = (density == 625) ? 3 : 7;
415 			fetapes =
416 			(	  (double) tapesize	/* blocks */
417 				* TP_BSIZE	/* bytes / block */
418 				* (1.0/density)	/* 0.1" / byte " */
419 			  +
420 				  (double) tapesize	/* blocks */
421 				* (1.0/ntrec)	/* IRG's / block */
422 				* tenthsperirg	/* 0.1" / IRG " */
423 			) * (1.0 / tsize );	/* tape / 0.1" " */
424 		}
425 		etapes = fetapes;		/* truncating assignment */
426 		etapes++;
427 		/* count the dumped inodes map on each additional tape */
428 		tapesize += (etapes - 1) *
429 			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
430 		tapesize += etapes + 10;	/* headers + 10 trailer blks */
431 		msg("estimated %ld tape blocks on %3.2f tape(s).\n",
432 		    tapesize, fetapes);
433 	}
434 
435         /*
436          * If the user only wants an estimate of the number of
437          * tapes, exit now.
438          */
439         if (just_estimate)
440                 exit(0);
441 
442 	/*
443 	 * Allocate tape buffer.
444 	 */
445 	if (!alloctape())
446 		quit(
447 	"can't allocate tape buffers - try a smaller blocking factor.\n");
448 
449 	startnewtape(1);
450 	(void)time((time_t *)&(tstart_writing));
451 	dumpmap(usedinomap, TS_CLRI, maxino - 1);
452 
453 	passno = 3;
454 	setproctitle("%s: pass 3: directories", disk);
455 	msg("dumping (Pass III) [directories]\n");
456 	dirty = 0;		/* XXX just to get gcc to shut up */
457 	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
458 		if (((ino - 1) % CHAR_BIT) == 0)	/* map is offset by 1 */
459 			dirty = *map++;
460 		else
461 			dirty >>= 1;
462 		if ((dirty & 1) == 0)
463 			continue;
464 		/*
465 		 * Skip directory inodes deleted and maybe reallocated
466 		 */
467 		dp = getino(ino, &mode);
468 		if (mode != IFDIR)
469 			continue;
470 		(void)dumpino(dp, ino);
471 	}
472 
473 	passno = 4;
474 	setproctitle("%s: pass 4: regular files", disk);
475 	msg("dumping (Pass IV) [regular files]\n");
476 	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
477 		if (((ino - 1) % CHAR_BIT) == 0)	/* map is offset by 1 */
478 			dirty = *map++;
479 		else
480 			dirty >>= 1;
481 		if ((dirty & 1) == 0)
482 			continue;
483 		/*
484 		 * Skip inodes deleted and reallocated as directories.
485 		 */
486 		dp = getino(ino, &mode);
487 		if (mode == IFDIR)
488 			continue;
489 		(void)dumpino(dp, ino);
490 	}
491 
492 	(void)time((time_t *)&(tend_writing));
493 	spcl.c_type = TS_END;
494 	for (i = 0; i < ntrec; i++)
495 		writeheader(maxino - 1);
496 	if (pipeout)
497 		msg("DUMP: %jd tape blocks\n", (intmax_t)spcl.c_tapea);
498 	else
499 		msg("DUMP: %jd tape blocks on %d volume%s\n",
500 		    (intmax_t)spcl.c_tapea, spcl.c_volume,
501 		    (spcl.c_volume == 1) ? "" : "s");
502 
503 	/* report dump performance, avoid division through zero */
504 	if (tend_writing - tstart_writing == 0)
505 		msg("finished in less than a second\n");
506 	else
507 		msg("finished in %d seconds, throughput %jd KBytes/sec\n",
508 		    tend_writing - tstart_writing, (intmax_t)(spcl.c_tapea /
509 		    (tend_writing - tstart_writing)));
510 
511 	putdumptime();
512 	trewind();
513 	broadcast("DUMP IS DONE!\a\a\n");
514 	msg("DUMP IS DONE\n");
515 	Exit(X_FINOK);
516 	/* NOTREACHED */
517 }
518 
519 static void
520 usage(void)
521 {
522 	fprintf(stderr,
523 		"usage: dump [-0123456789ac"
524 #ifdef KERBEROS
525 		"k"
526 #endif
527 		"nSu] [-B records] [-b blocksize] [-D dumpdates]\n"
528 		"            [-d density] [-f file] [-h level] [-s feet] "
529 		"[-T date] filesystem\n"
530 		"       dump -W | -w\n");
531 	exit(X_STARTUP);
532 }
533 
534 /*
535  * Pick up a numeric argument.  It must be nonnegative and in the given
536  * range (except that a vmax of 0 means unlimited).
537  */
538 static long
539 numarg(const char *meaning, long vmin, long vmax)
540 {
541 	char *p;
542 	long val;
543 
544 	val = strtol(optarg, &p, 10);
545 	if (*p)
546 		errx(1, "illegal %s -- %s", meaning, optarg);
547 	if (val < vmin || (vmax && val > vmax))
548 		errx(1, "%s must be between %ld and %ld", meaning, vmin, vmax);
549 	return (val);
550 }
551 
552 void
553 sig(int signo)
554 {
555 	switch(signo) {
556 	case SIGALRM:
557 	case SIGBUS:
558 	case SIGFPE:
559 	case SIGHUP:
560 	case SIGTERM:
561 	case SIGTRAP:
562 		if (pipeout)
563 			quit("Signal on pipe: cannot recover\n");
564 		msg("Rewriting attempted as response to unknown signal.\n");
565 		(void)fflush(stderr);
566 		(void)fflush(stdout);
567 		close_rewind();
568 		exit(X_REWRITE);
569 		/* NOTREACHED */
570 	case SIGSEGV:
571 		msg("SIGSEGV: ABORTING!\n");
572 		(void)signal(SIGSEGV, SIG_DFL);
573 		(void)kill(0, SIGSEGV);
574 		/* NOTREACHED */
575 	}
576 }
577 
578 char *
579 rawname(char *cp)
580 {
581 	static char rawbuf[MAXPATHLEN];
582 	char *dp;
583 	struct stat sb;
584 
585 	if (stat(cp, &sb) == 0) {
586 		/*
587 		 * If the name already refers to a raw device, return
588 		 * it immediately without tampering.
589 		 */
590 		if ((sb.st_mode & S_IFMT) == S_IFCHR)
591 			return (cp);
592 	}
593 
594 	dp = strrchr(cp, '/');
595 
596 	if (dp == NULL)
597 		return (NULL);
598 	*dp = '\0';
599 	(void)strlcpy(rawbuf, cp, MAXPATHLEN - 1);
600 	*dp = '/';
601 	(void)strlcat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
602 	(void)strlcat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
603 	return (rawbuf);
604 }
605 
606 /*
607  * obsolete --
608  *	Change set of key letters and ordered arguments into something
609  *	getopt(3) will like.
610  */
611 static void
612 obsolete(int *argcp, char **argvp[])
613 {
614 	int argc, flags;
615 	char *ap, **argv, *flagsp, **nargv, *p;
616 
617 	/* Setup. */
618 	argv = *argvp;
619 	argc = *argcp;
620 
621 	/* Return if no arguments or first argument has leading dash. */
622 	ap = argv[1];
623 	if (argc == 1 || *ap == '-')
624 		return;
625 
626 	/* Allocate space for new arguments. */
627 	if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
628 	    (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
629 		err(1, NULL);
630 
631 	*nargv++ = *argv;
632 	argv += 2;
633 
634 	for (flags = 0; *ap; ++ap) {
635 		switch (*ap) {
636 		case 'B':
637 		case 'b':
638 		case 'd':
639 		case 'f':
640 		case 'D':
641 		case 'h':
642 		case 's':
643 		case 'T':
644 			if (*argv == NULL) {
645 				warnx("option requires an argument -- %c", *ap);
646 				usage();
647 			}
648 			if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
649 				err(1, NULL);
650 			nargv[0][0] = '-';
651 			nargv[0][1] = *ap;
652 			(void)strcpy(&nargv[0][2], *argv);
653 			++argv;
654 			++nargv;
655 			break;
656 		default:
657 			if (!flags) {
658 				*p++ = '-';
659 				flags = 1;
660 			}
661 			*p++ = *ap;
662 			break;
663 		}
664 	}
665 
666 	/* Terminate flags. */
667 	if (flags) {
668 		*p = '\0';
669 		*nargv++ = flagsp;
670 	}
671 
672 	/* Copy remaining arguments. */
673 	while ((*nargv++ = *argv++));
674 
675 	/* Update argument count. */
676 	*argcp = nargv - *argvp - 1;
677 }
678