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