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