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