xref: /freebsd/sbin/dump/main.c (revision c4f6a2a9e1b1879b618c436ab4f56ff75c73a0f5)
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 <signal.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <timeconv.h>
68 #include <unistd.h>
69 
70 #include "dump.h"
71 #include "pathnames.h"
72 
73 int	notify = 0;	/* notify operator flag */
74 int	blockswritten = 0;	/* number of blocks written on current tape */
75 int	tapeno = 0;	/* current tape number */
76 int	density = 0;	/* density in bytes/0.1" " <- this is for hilit19 */
77 int	ntrec = NTREC;	/* # tape blocks in each tape record */
78 int	cartridge = 0;	/* Assume non-cartridge tape */
79 int	dokerberos = 0;	/* Use Kerberos authentication */
80 long	dev_bsize = 1;	/* recalculated below */
81 long	blocksperfile;	/* output blocks per file */
82 char	*host = NULL;	/* remote host (if any) */
83 
84 /*
85  * Possible superblock locations ordered from most to least likely.
86  */
87 static int sblock_try[] = SBLOCKSEARCH;
88 
89 static long numarg(const char *, long, long);
90 static void obsolete(int *, char **[]);
91 static void usage(void) __dead2;
92 
93 int
94 main(int argc, char *argv[])
95 {
96 	struct stat sb;
97 	ino_t ino;
98 	int dirty;
99 	union dinode *dp;
100 	struct	fstab *dt;
101 	char *map;
102 	int ch, mode;
103 	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
104 	int just_estimate = 0;
105 	ino_t maxino;
106 	char *tmsg;
107 
108 	spcl.c_date = _time_to_time64(time(NULL));
109 
110 	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
111 	if ((tape = getenv("TAPE")) == NULL)
112 		tape = _PATH_DEFTAPE;
113 	dumpdates = _PATH_DUMPDATES;
114 	temp = _PATH_DTMP;
115 	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
116 		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
117 	level = '0';
118 
119 	if (argc < 2)
120 		usage();
121 
122 	obsolete(&argc, &argv);
123 #ifdef KERBEROS
124 #define optstring "0123456789aB:b:cd:f:h:kns:ST:uWwD:"
125 #else
126 #define optstring "0123456789aB:b:cd:f:h:ns:ST:uWwD:"
127 #endif
128 	while ((ch = getopt(argc, argv, optstring)) != -1)
129 #undef optstring
130 		switch (ch) {
131 		/* dump level */
132 		case '0': case '1': case '2': case '3': case '4':
133 		case '5': case '6': case '7': case '8': case '9':
134 			level = ch;
135 			break;
136 
137 		case 'a':		/* `auto-size', Write to EOM. */
138 			unlimited = 1;
139 			break;
140 
141 		case 'B':		/* blocks per output file */
142 			blocksperfile = numarg("number of blocks per file",
143 			    1L, 0L);
144 			break;
145 
146 		case 'b':		/* blocks per tape write */
147 			ntrec = numarg("number of blocks per write",
148 			    1L, 1000L);
149 			break;
150 
151 		case 'c':		/* Tape is cart. not 9-track */
152 			cartridge = 1;
153 			break;
154 
155 		case 'd':		/* density, in bits per inch */
156 			density = numarg("density", 10L, 327670L) / 10;
157 			if (density >= 625 && !bflag)
158 				ntrec = HIGHDENSITYTREC;
159 			break;
160 
161 		case 'f':		/* output file */
162 			tape = optarg;
163 			break;
164 
165 		case 'D':
166 			dumpdates = optarg;
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 file system\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 	if (spcl.c_date == 0) {
319 		tmsg = "the epoch\n";
320 	} else {
321 		time_t t = _time64_to_time(spcl.c_date);
322 		tmsg = ctime(&t);
323 	}
324 	msg("Date of this level %c dump: %s", level, tmsg);
325 	if (spcl.c_ddate == 0) {
326 		tmsg = "the epoch\n";
327 	} else {
328 		time_t t = _time64_to_time(spcl.c_ddate);
329 		tmsg = ctime(&t);
330 	}
331  	msg("Date of last level %c dump: %s", lastlevel, tmsg);
332 	msg("Dumping %s ", disk);
333 	if (dt != NULL)
334 		msgtail("(%s) ", dt->fs_file);
335 	if (host)
336 		msgtail("to %s on host %s\n", tape, host);
337 	else
338 		msgtail("to %s\n", tape);
339 
340 	if ((diskfd = open(disk, O_RDONLY)) < 0)
341 		err(X_STARTUP, "Cannot open %s", disk);
342 	if (fstat(diskfd, &sb) != 0)
343 		err(X_STARTUP, "%s: stat", disk);
344 	if (S_ISDIR(sb.st_mode))
345 		errx(X_STARTUP, "%s: unknown file system", disk);
346 	sync();
347 	sblock = (struct fs *)sblock_buf;
348 	for (i = 0; sblock_try[i] != -1; i++) {
349 		bread(sblock_try[i] >> dev_bshift, (char *) sblock, SBLOCKSIZE);
350 		if ((sblock->fs_magic == FS_UFS1_MAGIC ||
351 		     (sblock->fs_magic == FS_UFS2_MAGIC &&
352 		      sblock->fs_sblockloc ==
353 			  numfrags(sblock, sblock_try[i]))) &&
354 		    sblock->fs_bsize <= MAXBSIZE &&
355 		    sblock->fs_bsize >= sizeof(struct fs))
356 			break;
357 	}
358 	if (sblock_try[i] == -1)
359 		quit("Cannot find file system superblock\n");
360 	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
361 	dev_bshift = ffs(dev_bsize) - 1;
362 	if (dev_bsize != (1 << dev_bshift))
363 		quit("dev_bsize (%ld) is not a power of 2", dev_bsize);
364 	tp_bshift = ffs(TP_BSIZE) - 1;
365 	if (TP_BSIZE != (1 << tp_bshift))
366 		quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
367 	maxino = sblock->fs_ipg * sblock->fs_ncg;
368 	mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
369 	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
370 	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
371 	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
372 	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
373 
374 	nonodump = spcl.c_level < honorlevel;
375 
376 	passno = 1;
377 	setproctitle("%s: pass 1: regular files", disk);
378 	msg("mapping (Pass I) [regular files]\n");
379 	anydirskipped = mapfiles(maxino, &tapesize);
380 
381 	passno = 2;
382 	setproctitle("%s: pass 2: directories", disk);
383 	msg("mapping (Pass II) [directories]\n");
384 	while (anydirskipped) {
385 		anydirskipped = mapdirs(maxino, &tapesize);
386 	}
387 
388 	if (pipeout || unlimited) {
389 		tapesize += 10;	/* 10 trailer blocks */
390 		msg("estimated %ld tape blocks.\n", tapesize);
391 	} else {
392 		double fetapes;
393 
394 		if (blocksperfile)
395 			fetapes = (double) tapesize / blocksperfile;
396 		else if (cartridge) {
397 			/* Estimate number of tapes, assuming streaming stops at
398 			   the end of each block written, and not in mid-block.
399 			   Assume no erroneous blocks; this can be compensated
400 			   for with an artificially low tape size. */
401 			fetapes =
402 			(	  (double) tapesize	/* blocks */
403 				* TP_BSIZE	/* bytes/block */
404 				* (1.0/density)	/* 0.1" / byte " */
405 			  +
406 				  (double) tapesize	/* blocks */
407 				* (1.0/ntrec)	/* streaming-stops per block */
408 				* 15.48		/* 0.1" / streaming-stop " */
409 			) * (1.0 / tsize );	/* tape / 0.1" " */
410 		} else {
411 			/* Estimate number of tapes, for old fashioned 9-track
412 			   tape */
413 			int tenthsperirg = (density == 625) ? 3 : 7;
414 			fetapes =
415 			(	  (double) tapesize	/* blocks */
416 				* TP_BSIZE	/* bytes / block */
417 				* (1.0/density)	/* 0.1" / byte " */
418 			  +
419 				  (double) tapesize	/* blocks */
420 				* (1.0/ntrec)	/* IRG's / block */
421 				* tenthsperirg	/* 0.1" / IRG " */
422 			) * (1.0 / tsize );	/* tape / 0.1" " */
423 		}
424 		etapes = fetapes;		/* truncating assignment */
425 		etapes++;
426 		/* count the dumped inodes map on each additional tape */
427 		tapesize += (etapes - 1) *
428 			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
429 		tapesize += etapes + 10;	/* headers + 10 trailer blks */
430 		msg("estimated %ld tape blocks on %3.2f tape(s).\n",
431 		    tapesize, fetapes);
432 	}
433 
434         /*
435          * If the user only wants an estimate of the number of
436          * tapes, exit now.
437          */
438         if (just_estimate)
439                 exit(0);
440 
441 	/*
442 	 * Allocate tape buffer.
443 	 */
444 	if (!alloctape())
445 		quit(
446 	"can't allocate tape buffers - try a smaller blocking factor.\n");
447 
448 	startnewtape(1);
449 	(void)time((time_t *)&(tstart_writing));
450 	dumpmap(usedinomap, TS_CLRI, maxino - 1);
451 
452 	passno = 3;
453 	setproctitle("%s: pass 3: directories", disk);
454 	msg("dumping (Pass III) [directories]\n");
455 	dirty = 0;		/* XXX just to get gcc to shut up */
456 	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
457 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
458 			dirty = *map++;
459 		else
460 			dirty >>= 1;
461 		if ((dirty & 1) == 0)
462 			continue;
463 		/*
464 		 * Skip directory inodes deleted and maybe reallocated
465 		 */
466 		dp = getino(ino, &mode);
467 		if (mode != IFDIR)
468 			continue;
469 		(void)dumpino(dp, ino);
470 	}
471 
472 	passno = 4;
473 	setproctitle("%s: pass 4: regular files", disk);
474 	msg("dumping (Pass IV) [regular files]\n");
475 	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
476 		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
477 			dirty = *map++;
478 		else
479 			dirty >>= 1;
480 		if ((dirty & 1) == 0)
481 			continue;
482 		/*
483 		 * Skip inodes deleted and reallocated as directories.
484 		 */
485 		dp = getino(ino, &mode);
486 		if (mode == IFDIR)
487 			continue;
488 		(void)dumpino(dp, ino);
489 	}
490 
491 	(void)time((time_t *)&(tend_writing));
492 	spcl.c_type = TS_END;
493 	for (i = 0; i < ntrec; i++)
494 		writeheader(maxino - 1);
495 	if (pipeout)
496 		msg("DUMP: %jd tape blocks\n", (intmax_t)spcl.c_tapea);
497 	else
498 		msg("DUMP: %jd tape blocks on %d volume%s\n",
499 		    (intmax_t)spcl.c_tapea, spcl.c_volume,
500 		    (spcl.c_volume == 1) ? "" : "s");
501 
502 	/* report dump performance, avoid division through zero */
503 	if (tend_writing - tstart_writing == 0)
504 		msg("finished in less than a second\n");
505 	else
506 		msg("finished in %d seconds, throughput %jd KBytes/sec\n",
507 		    tend_writing - tstart_writing, (intmax_t)(spcl.c_tapea /
508 		    (tend_writing - tstart_writing)));
509 
510 	putdumptime();
511 	trewind();
512 	broadcast("DUMP IS DONE!\a\a\n");
513 	msg("DUMP IS DONE\n");
514 	Exit(X_FINOK);
515 	/* NOTREACHED */
516 }
517 
518 static void
519 usage(void)
520 {
521 	fprintf(stderr,
522 		"usage: dump [-0123456789ac"
523 #ifdef KERBEROS
524 		"k"
525 #endif
526 		"nSu] [-B records] [-b blocksize] [-D dumpdates]\n"
527 		"            [-d density] [-f file ] [-h level] [-s feet] "
528 		"[-T date] file system\n"
529 		"       dump [-W | -w]\n");
530 	exit(X_STARTUP);
531 }
532 
533 /*
534  * Pick up a numeric argument.  It must be nonnegative and in the given
535  * range (except that a vmax of 0 means unlimited).
536  */
537 static long
538 numarg(const char *meaning, long vmin, long vmax)
539 {
540 	char *p;
541 	long val;
542 
543 	val = strtol(optarg, &p, 10);
544 	if (*p)
545 		errx(1, "illegal %s -- %s", meaning, optarg);
546 	if (val < vmin || (vmax && val > vmax))
547 		errx(1, "%s must be between %ld and %ld", meaning, vmin, vmax);
548 	return (val);
549 }
550 
551 void
552 sig(int signo)
553 {
554 	switch(signo) {
555 	case SIGALRM:
556 	case SIGBUS:
557 	case SIGFPE:
558 	case SIGHUP:
559 	case SIGTERM:
560 	case SIGTRAP:
561 		if (pipeout)
562 			quit("Signal on pipe: cannot recover\n");
563 		msg("Rewriting attempted as response to unknown signal.\n");
564 		(void)fflush(stderr);
565 		(void)fflush(stdout);
566 		close_rewind();
567 		exit(X_REWRITE);
568 		/* NOTREACHED */
569 	case SIGSEGV:
570 		msg("SIGSEGV: ABORTING!\n");
571 		(void)signal(SIGSEGV, SIG_DFL);
572 		(void)kill(0, SIGSEGV);
573 		/* NOTREACHED */
574 	}
575 }
576 
577 char *
578 rawname(char *cp)
579 {
580 	static char rawbuf[MAXPATHLEN];
581 	char *dp;
582 	struct stat sb;
583 
584 	if (stat(cp, &sb) == 0) {
585 		/*
586 		 * If the name already refers to a raw device, return
587 		 * it immediately without tampering.
588 		 */
589 		if ((sb.st_mode & S_IFMT) == S_IFCHR)
590 			return (cp);
591 	}
592 
593 	dp = strrchr(cp, '/');
594 
595 	if (dp == NULL)
596 		return (NULL);
597 	*dp = '\0';
598 	(void)strlcpy(rawbuf, cp, MAXPATHLEN - 1);
599 	*dp = '/';
600 	(void)strlcat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
601 	(void)strlcat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
602 	return (rawbuf);
603 }
604 
605 /*
606  * obsolete --
607  *	Change set of key letters and ordered arguments into something
608  *	getopt(3) will like.
609  */
610 static void
611 obsolete(int *argcp, char **argvp[])
612 {
613 	int argc, flags;
614 	char *ap, **argv, *flagsp, **nargv, *p;
615 
616 	/* Setup. */
617 	argv = *argvp;
618 	argc = *argcp;
619 
620 	/* Return if no arguments or first argument has leading dash. */
621 	ap = argv[1];
622 	if (argc == 1 || *ap == '-')
623 		return;
624 
625 	/* Allocate space for new arguments. */
626 	if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
627 	    (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
628 		err(1, NULL);
629 
630 	*nargv++ = *argv;
631 	argv += 2;
632 
633 	for (flags = 0; *ap; ++ap) {
634 		switch (*ap) {
635 		case 'B':
636 		case 'b':
637 		case 'd':
638 		case 'f':
639 		case 'D':
640 		case 'h':
641 		case 's':
642 		case 'T':
643 			if (*argv == NULL) {
644 				warnx("option requires an argument -- %c", *ap);
645 				usage();
646 			}
647 			if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
648 				err(1, NULL);
649 			nargv[0][0] = '-';
650 			nargv[0][1] = *ap;
651 			(void)strcpy(&nargv[0][2], *argv);
652 			++argv;
653 			++nargv;
654 			break;
655 		default:
656 			if (!flags) {
657 				*p++ = '-';
658 				flags = 1;
659 			}
660 			*p++ = *ap;
661 			break;
662 		}
663 	}
664 
665 	/* Terminate flags. */
666 	if (flags) {
667 		*p = '\0';
668 		*nargv++ = flagsp;
669 	}
670 
671 	/* Copy remaining arguments. */
672 	while ((*nargv++ = *argv++));
673 
674 	/* Update argument count. */
675 	*argcp = nargv - *argvp - 1;
676 }
677