aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

mkfs.fat.c (29539B)


      1 /*	$OpenBSD: newfs_msdos.c,v 1.30 2025/09/17 16:07:57 deraadt Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998 Robert Nordier
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in
     14  *    the documentation and/or other materials provided with the
     15  *    distribution.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
     18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
     21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
     25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
     27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     28  */
     29 
     30 #if defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX)
     31 #undef _POSIX_C_SOURCE
     32 #endif
     33 
     34 #include "diskutil.h"
     35 #include "util.h"
     36 
     37 #include <ctype.h>
     38 #include <errno.h>
     39 #include <fcntl.h>
     40 #include <limits.h>
     41 #include <stdint.h>
     42 #include <stdlib.h>
     43 #include <sys/stat.h>
     44 #include <sys/time.h>
     45 #include <time.h>
     46 #include <unistd.h>
     47 
     48 #if defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX)
     49 #include <sys/param.h>
     50 #include <sys/disklabel.h>
     51 #include <sys/dkio.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/mount.h>
     54 #elif defined(__linux__) && !defined(ARUU_FORCE_POSIX)
     55 #include <linux/hdreg.h>
     56 #include <sys/ioctl.h>
     57 #endif
     58 
     59 #ifndef howmany
     60 #define howmany(x, y) (((x) + (y) - 1) / (y))
     61 #endif
     62 #ifndef powerof2
     63 #define powerof2(x) ((x) && !((x) & ((x) - 1)))
     64 #endif
     65 
     66 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
     67 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
     68 
     69 #define MAXU16 0xffff /* maximum unsigned 16-bit quantity */
     70 #define BPN    4      /* bits per nibble */
     71 #define NPB    2      /* nibbles per byte */
     72 
     73 #define DOSMAGIC 0xaa55    /* DOS magic number */
     74 #define MINBPS   512       /* minimum bytes per sector */
     75 #define MAXSPC   128       /* maximum sectors per cluster */
     76 #define MAXNFT   16        /* maximum number of FATs */
     77 #define DEFBLK   4096      /* default block size */
     78 #define DEFBLK16 2048      /* default block size FAT16 */
     79 #define DEFRDE   512       /* default root directory entries */
     80 #define RESFTE   2         /* reserved FAT entries */
     81 #define MINCLS12 1         /* minimum FAT12 clusters */
     82 #define MINCLS16 0xff5     /* minimum FAT16 clusters */
     83 #define MINCLS32 0xfff5    /* minimum FAT32 clusters */
     84 #define MAXCLS12 0xff4     /* maximum FAT12 clusters */
     85 #define MAXCLS16 0xfff4    /* maximum FAT16 clusters */
     86 #define MAXCLS32 0xffffff4 /* maximum FAT32 clusters */
     87 
     88 #define mincls(fat) ((fat) == 12 ? MINCLS12 : (fat) == 16 ? MINCLS16 : MINCLS32)
     89 
     90 #define maxcls(fat) ((fat) == 12 ? MAXCLS12 : (fat) == 16 ? MAXCLS16 : MAXCLS32)
     91 
     92 #define mk1(p, x) (p) = (uint8_t)(x)
     93 
     94 #define mk2(p, x) (p)[0] = (uint8_t)(x), (p)[1] = (uint8_t)((x) >> 010)
     95 
     96 #define mk4(p, x)                                                                                  \
     97   (p)[0] = (uint8_t)(x), (p)[1] = (uint8_t)((x) >> 010), (p)[2] = (uint8_t)((x) >> 020),           \
     98   (p)[3] = (uint8_t)((x) >> 030)
     99 
    100 #define argto1(arg, lo, msg) argtou(arg, lo, 0xff, msg)
    101 #define argto2(arg, lo, msg) argtou(arg, lo, 0xffff, msg)
    102 #define argto4(arg, lo, msg) argtou(arg, lo, 0xffffffff, msg)
    103 #define argtox(arg, lo, msg) argtou(arg, lo, UINT_MAX, msg)
    104 
    105 struct bs {
    106   uint8_t jmp[3]; /* bootstrap entry point */
    107   uint8_t oem[8]; /* OEM name and version */
    108 };
    109 
    110 struct bsbpb {
    111   uint8_t bps[2];  /* bytes per sector */
    112   uint8_t spc;     /* sectors per cluster */
    113   uint8_t res[2];  /* reserved sectors */
    114   uint8_t nft;     /* number of FATs */
    115   uint8_t rde[2];  /* root directory entries */
    116   uint8_t sec[2];  /* total sectors */
    117   uint8_t mid;     /* media descriptor */
    118   uint8_t spf[2];  /* sectors per FAT */
    119   uint8_t spt[2];  /* sectors per track */
    120   uint8_t hds[2];  /* drive heads */
    121   uint8_t hid[4];  /* hidden sectors */
    122   uint8_t bsec[4]; /* big total sectors */
    123 };
    124 
    125 struct bsxbpb {
    126   uint8_t bspf[4];  /* big sectors per FAT */
    127   uint8_t xflg[2];  /* FAT control flags */
    128   uint8_t vers[2];  /* file system version */
    129   uint8_t rdcl[4];  /* root directory start cluster */
    130   uint8_t infs[2];  /* file system info sector */
    131   uint8_t bkbs[2];  /* backup boot sector */
    132   uint8_t rsvd[12]; /* reserved */
    133 };
    134 
    135 struct bsx {
    136   uint8_t drv;       /* drive number */
    137   uint8_t rsvd;      /* reserved */
    138   uint8_t sig;       /* extended boot signature */
    139   uint8_t volid[4];  /* volume ID number */
    140   uint8_t label[11]; /* volume label */
    141   uint8_t type[8];   /* file system type */
    142 };
    143 
    144 struct de {
    145   uint8_t namext[11]; /* name and extension */
    146   uint8_t attr;       /* attributes */
    147   uint8_t rsvd[10];   /* reserved */
    148   uint8_t time[2];    /* creation time */
    149   uint8_t date[2];    /* creation date */
    150   uint8_t clus[2];    /* starting cluster */
    151   uint8_t size[4];    /* size */
    152 };
    153 
    154 struct bpb {
    155   unsigned int bps;  /* bytes per sector */
    156   unsigned int spc;  /* sectors per cluster */
    157   unsigned int res;  /* reserved sectors */
    158   unsigned int nft;  /* number of FATs */
    159   unsigned int rde;  /* root directory entries */
    160   unsigned int sec;  /* total sectors */
    161   unsigned int mid;  /* media descriptor */
    162   unsigned int spf;  /* sectors per FAT */
    163   unsigned int spt;  /* sectors per track */
    164   unsigned int hds;  /* drive heads */
    165   unsigned int hid;  /* hidden sectors */
    166   unsigned int bsec; /* big total sectors */
    167   unsigned int bspf; /* big sectors per FAT */
    168   unsigned int rdcl; /* root directory start cluster */
    169   unsigned int infs; /* file system info sector */
    170   unsigned int bkbs; /* backup boot sector */
    171 };
    172 
    173 static struct {
    174   const char *name;
    175   struct bpb  bpb;
    176 } stdfmt[] = {
    177     {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, 0, 0, 0, 0, 0, 0}},
    178     {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, 0, 0, 0, 0, 0, 0}},
    179     {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, 0, 0, 0, 0, 0, 0}},
    180     {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, 0, 0, 0, 0, 0, 0}},
    181     {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, 0, 0, 0, 0, 0, 0}},
    182     {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, 0, 0, 0, 0, 0, 0}},
    183     {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, 0, 0, 0, 0, 0, 0}},
    184     {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, 0, 0, 0, 0, 0, 0}}
    185 };
    186 
    187 static uint8_t bootcode[] = {0xfa,             /* cli		    */
    188                              0x31, 0xc0,       /* xor	   ax,ax    */
    189                              0x8e, 0xd0,       /* mov	   ss,ax    */
    190                              0xbc, 0x00, 0x7c, /* mov	   sp,7c00h */
    191                              0xfb,             /* sti		    */
    192                              0x8e, 0xd8,       /* mov	   ds,ax    */
    193                              0xe8, 0x00, 0x00, /* call    $ + 3    */
    194                              0x5e,             /* pop	   si	    */
    195                              0x83, 0xc6, 0x19, /* add	   si,+19h  */
    196                              0xbb, 0x07, 0x00, /* mov	   bx,0007h */
    197                              0xfc,             /* cld		    */
    198                              0xac,             /* lodsb	    */
    199                              0x84, 0xc0,       /* test    al,al    */
    200                              0x74, 0x06,       /* jz	   $ + 8    */
    201                              0xb4, 0x0e,       /* mov	   ah,0eh   */
    202                              0xcd, 0x10,       /* int	   10h	    */
    203                              0xeb, 0xf5,       /* jmp	   $ - 9    */
    204                              0x30, 0xe4,       /* xor	   ah,ah    */
    205                              0xcd, 0x16,       /* int	   16h	    */
    206                              0xcd, 0x19,       /* int	   19h	    */
    207                              0x0d, 0x0a, 'N',  'o', 'n', '-',  's',  'y',  's', 't', 'e', 'm',
    208                              ' ',  'd',  'i',  's', 'k', 0x0d, 0x0a, 'P',  'r', 'e', 's', 's',
    209                              ' ',  'a',  'n',  'y', ' ', 'k',  'e',  'y',  ' ', 't', 'o', ' ',
    210                              'r',  'e',  'b',  'o', 'o', 't',  0x0d, 0x0a, 0};
    211 
    212 static void         gettarget(int, const char *, int, struct bpb *);
    213 static void         getstdfmt(const char *, struct bpb *);
    214 static void         print_bpb(struct bpb *);
    215 static unsigned int argtou(const char *, unsigned int, unsigned int, const char *);
    216 static int          oklabel(const char *);
    217 static void         mklabel(uint8_t *, const char *);
    218 static void         setstr(uint8_t *, const char *, size_t);
    219 static void __attribute__((noreturn)) usage(void);
    220 
    221 /*
    222  * Construct a FAT12, FAT16, or FAT32 file system.
    223  */
    224 int
    225 main(int argc, char *argv[])
    226 {
    227   const char    *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL;
    228   unsigned int   opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0, opt_e = 0;
    229   unsigned int   opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0, opt_o = 0, opt_r = 0;
    230   unsigned int   opt_s = 0, opt_u = 0;
    231   int            opt_N = 0, Iflag = 0, mflag = 0, oflag = 0;
    232   char           buf[PATH_MAX];
    233   struct stat    sb;
    234   struct timeval tv;
    235   struct bpb     bpb;
    236   struct tm     *tm;
    237   struct bs     *bs;
    238   struct bsbpb  *bsbpb;
    239   struct bsxbpb *bsxbpb;
    240   struct bsx    *bsx;
    241   struct de     *de;
    242   uint8_t       *img;
    243   const char    *bname, *fname, *arg;
    244   ssize_t        n;
    245   time_t         now;
    246   unsigned int   fat, bss, rds, cls, dir, lsn, x, x1, x2;
    247   uint64_t       capacity, bits;
    248   int            fd, fd1, flags;
    249 
    250 #if defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX)
    251   if (pledge("stdio rpath wpath disklabel", NULL) == -1)
    252     eprintf("pledge:");
    253 #endif
    254 
    255   ARGBEGIN
    256   {
    257     case 'N':
    258       opt_N = 1;
    259       break;
    260     case 'B':
    261       opt_B = EARGF(usage());
    262       break;
    263     case 'F':
    264       arg   = EARGF(usage());
    265       opt_F = strtonum(arg, 1, INT_MAX, NULL);
    266       if (!(opt_F == 12 || opt_F == 16 || opt_F == 32))
    267         eprintf("%s: bad FAT type\n", arg);
    268       break;
    269     case 'I':
    270       opt_I = argto4(EARGF(usage()), 0, "volume ID");
    271       Iflag = 1;
    272       break;
    273     case 'n':
    274     case 'L':
    275       arg = EARGF(usage());
    276       if (!oklabel(arg))
    277         eprintf("%s: bad volume label\n", arg);
    278       opt_L = arg;
    279       break;
    280     case 'O':
    281       arg = EARGF(usage());
    282       if (strlen(arg) > 8)
    283         eprintf("%s: bad OEM string\n", arg);
    284       opt_O = arg;
    285       break;
    286     case 'S':
    287       opt_S = argto2(EARGF(usage()), 1, "bytes/sector");
    288       break;
    289     case 'a':
    290       opt_a = argto4(EARGF(usage()), 1, "sectors/FAT");
    291       break;
    292     case 'b':
    293       opt_b = argtox(EARGF(usage()), 1, "block size");
    294       opt_c = 0;
    295       break;
    296     case 'c':
    297       opt_c = argto1(EARGF(usage()), 1, "sectors/cluster");
    298       opt_b = 0;
    299       break;
    300     case 'e':
    301       opt_e = argto2(EARGF(usage()), 1, "directory entries");
    302       break;
    303     case 'f':
    304       opt_f = EARGF(usage());
    305       break;
    306     case 'h':
    307       opt_h = argto2(EARGF(usage()), 1, "drive heads");
    308       break;
    309     case 'i':
    310       opt_i = argto2(EARGF(usage()), 1, "info sector");
    311       break;
    312     case 'k':
    313       opt_k = argto2(EARGF(usage()), 1, "backup sector");
    314       break;
    315     case 'm':
    316       opt_m = argto1(EARGF(usage()), 0, "media descriptor");
    317       mflag = 1;
    318       break;
    319     case 'A':
    320       opt_n = argto1(EARGF(usage()), 1, "number of FATs");
    321       break;
    322     case 'o':
    323       opt_o = argto4(EARGF(usage()), 0, "hidden sectors");
    324       oflag = 1;
    325       break;
    326     case 'q': /* Compat with newfs -q */
    327       break;
    328     case 'r':
    329       opt_r = argto2(EARGF(usage()), 1, "reserved sectors");
    330       break;
    331     case 's':
    332       opt_s = argto4(EARGF(usage()), 1, "file system size");
    333       break;
    334     case 't': /* Compat with newfs -t */
    335       (void)EARGF(usage());
    336       break;
    337     case 'u':
    338       opt_u = argto2(EARGF(usage()), 1, "sectors/track");
    339       break;
    340     default:
    341       usage();
    342   }
    343   ARGEND
    344   if (argc != 1)
    345     usage();
    346   fname = argv[0];
    347   flags = opt_N ? O_RDONLY : O_RDWR;
    348 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
    349   /* The kernel refuses a writable claim on a mounted block device. */
    350   if (!opt_N)
    351     flags |= O_EXCL;
    352 #endif
    353   fd = open(fname, flags | O_NONBLOCK);
    354   if (fd < 0)
    355     eprintf("%s:", fname);
    356   memset(&bpb, 0, sizeof(bpb));
    357   if (opt_f) {
    358     getstdfmt(opt_f, &bpb);
    359     bpb.bsec = bpb.sec;
    360     bpb.sec  = 0;
    361     bpb.bspf = bpb.spf;
    362     bpb.spf  = 0;
    363   }
    364   if (opt_h)
    365     bpb.hds = opt_h;
    366   if (opt_u)
    367     bpb.spt = opt_u;
    368   if (opt_S)
    369     bpb.bps = opt_S;
    370   if (opt_s)
    371     bpb.bsec = opt_s;
    372   gettarget(fd, fname, opt_N, &bpb);
    373   if (oflag)
    374     bpb.hid = opt_o;
    375   if (!powerof2(bpb.bps))
    376     eprintf("bytes/sector (%u) is not a power of 2\n", bpb.bps);
    377   if (bpb.bps < MINBPS)
    378     eprintf("bytes/sector (%u) is too small; minimum is %u\n", bpb.bps, MINBPS);
    379   if (!(fat = opt_F)) {
    380     if (opt_f)
    381       fat = 12;
    382     else if (!opt_e && (opt_i || opt_k))
    383       fat = 32;
    384   }
    385   if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
    386     eprintf(
    387         "-%c is not a legal FAT%s option\n",
    388         fat == 32 ? 'e'
    389         : opt_i   ? 'i'
    390                   : 'k',
    391         fat == 32 ? "32" : "12/16"
    392     );
    393   if (opt_f && fat == 32)
    394     bpb.rde = 0;
    395   if (opt_b) {
    396     if (!powerof2(opt_b))
    397       eprintf("block size (%u) is not a power of 2\n", opt_b);
    398     if (opt_b < bpb.bps)
    399       eprintf("block size (%u) is too small; minimum is %u\n", opt_b, bpb.bps);
    400     if (opt_b > bpb.bps * MAXSPC)
    401       eprintf("block size (%u) is too large; maximum is %u\n", opt_b, bpb.bps * MAXSPC);
    402     bpb.spc = opt_b / bpb.bps;
    403   }
    404   if (opt_c) {
    405     if (!powerof2(opt_c))
    406       eprintf("sectors/cluster (%u) is not a power of 2\n", opt_c);
    407     bpb.spc = opt_c;
    408   }
    409   if (opt_r)
    410     bpb.res = opt_r;
    411   if (opt_n) {
    412     if (opt_n > MAXNFT)
    413       eprintf("number of FATs (%u) is too large; maximum is %u\n", opt_n, MAXNFT);
    414     bpb.nft = opt_n;
    415   }
    416   if (opt_e)
    417     bpb.rde = opt_e;
    418   if (mflag) {
    419     if (opt_m < 0xf0)
    420       eprintf("illegal media descriptor (%#x)\n", opt_m);
    421     bpb.mid = opt_m;
    422   }
    423   if (opt_a)
    424     bpb.bspf = opt_a;
    425   if (opt_i)
    426     bpb.infs = opt_i;
    427   if (opt_k)
    428     bpb.bkbs = opt_k;
    429   bss   = 1;
    430   bname = NULL;
    431   fd1   = -1;
    432   if (opt_B) {
    433     bname = opt_B;
    434     if (!strchr(bname, '/')) {
    435       if (snprintf(buf, sizeof buf, "/boot/%s", bname) >= (int)sizeof buf)
    436         eprintf("bootstrap path too long\n");
    437       bname = buf;
    438     }
    439     if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
    440       eprintf("%s:", bname);
    441     if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps || sb.st_size < bpb.bps
    442         || sb.st_size > bpb.bps * MAXU16)
    443       eprintf("%s: inappropriate file type or format\n", bname);
    444     bss = sb.st_size / bpb.bps;
    445   }
    446   if (!bpb.nft)
    447     bpb.nft = 2;
    448   if (!fat) {
    449     if (bpb.bsec
    450         < (bpb.res ? bpb.res : bss)
    451               + howmany(
    452                     (RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) * ((bpb.spc ? 16 : 12) / BPN),
    453                     bpb.bps * NPB
    454                 ) * bpb.nft
    455               + howmany(bpb.rde ? bpb.rde : DEFRDE, bpb.bps / sizeof(struct de))
    456               + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)
    457                     * (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
    458       fat = 12;
    459     else if (
    460         bpb.rde
    461         || bpb.bsec < (bpb.res ? bpb.res : bss)
    462                           + howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft
    463                           + howmany(DEFRDE, bpb.bps / sizeof(struct de))
    464                           + (MAXCLS16 + 1) * (bpb.spc ? bpb.spc : howmany(8192, bpb.bps))
    465     )
    466       fat = 16;
    467     else
    468       fat = 32;
    469   }
    470   x = bss;
    471   if (fat == 32) {
    472     if (!bpb.infs) {
    473       if (x == MAXU16 || x == bpb.bkbs)
    474         eprintf("no room for info sector\n");
    475       bpb.infs = x;
    476     }
    477     if (bpb.infs != MAXU16 && bpb.infs < bss)
    478       eprintf("info sector would overwrite bootstrap\n");
    479     if (bpb.infs != MAXU16 && x <= bpb.infs)
    480       x = bpb.infs + 1;
    481     if (!bpb.bkbs) {
    482       if (x == MAXU16)
    483         eprintf("no room for backup sector\n");
    484       bpb.bkbs = x;
    485     } else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
    486       eprintf("backup sector would overwrite info sector\n");
    487     if (bpb.bkbs != MAXU16) {
    488       if (bpb.bkbs < bss
    489           || (bpb.infs != MAXU16 && bpb.infs >= bpb.bkbs && bpb.infs < bpb.bkbs + bss))
    490         eprintf("overlapping backup bootstrap\n");
    491       x = MAXIMUM(x, bpb.bkbs + bss);
    492       if (bpb.infs != MAXU16)
    493         x = MAXIMUM(x, bpb.bkbs + bpb.infs + 1);
    494       if (x > MAXU16)
    495         eprintf("backup exceeds reserved area\n");
    496     }
    497   }
    498   if (!bpb.res)
    499     bpb.res = fat == 32 ? MAXIMUM(x, MAXIMUM(16384 / bpb.bps, 4)) : x;
    500   else if (bpb.res < x)
    501     eprintf("too few reserved sectors\n");
    502   if (fat != 32) {
    503     if (!bpb.rde)
    504       bpb.rde = MAXIMUM(DEFRDE, bpb.bps / sizeof(struct de));
    505     if (bpb.rde % (bpb.bps / sizeof(struct de)))
    506       eprintf("root directory must occupy whole sectors\n");
    507   }
    508   rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
    509   if (!bpb.spc) {
    510     unsigned int minfat   = howmany((RESFTE + mincls(fat)) * (fat / BPN), bpb.bps * NPB);
    511     uint64_t     metadata = bpb.res + rds + (uint64_t)bpb.nft * (bpb.bspf ? bpb.bspf : minfat);
    512 
    513     /* A small EFI partition may need clusters below the default 4 KiB. */
    514     bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
    515     while (bpb.spc > 1 && metadata + (uint64_t)mincls(fat) * bpb.spc > bpb.bsec)
    516       bpb.spc >>= 1;
    517     while (bpb.spc < MAXSPC
    518            && bpb.res + howmany((RESFTE + maxcls(fat)) * (fat / BPN), bpb.bps * NPB) * bpb.nft + rds
    519                       + (uint64_t)(maxcls(fat) + 1) * bpb.spc
    520                   <= bpb.bsec)
    521       bpb.spc <<= 1;
    522   }
    523   if (fat != 32 && bpb.bspf > MAXU16)
    524     eprintf("too many sectors/FAT for FAT12/16\n");
    525   x1 = bpb.res + rds;
    526   if (x1 >= bpb.bsec)
    527     eprintf("metadata exceeds filesystem size\n");
    528   /* The FAT must cover the data clusters plus its two reserved entries.
    529    * Each sector added to a FAT also removes one sector per copy from data. */
    530   bits = ((uint64_t)bpb.bsec - x1 + RESFTE * bpb.spc) * fat;
    531   x    = bpb.spc * bpb.bps * 8 + bpb.nft * fat;
    532   x2   = howmany(bits, x);
    533   x    = howmany((uint64_t)(RESFTE + maxcls(fat)) * fat, bpb.bps * 8);
    534   if (!bpb.bspf)
    535     bpb.bspf = MINIMUM(x2, x);
    536   if (x1 + (uint64_t)bpb.bspf * bpb.nft >= bpb.bsec)
    537     eprintf("metadata exceeds filesystem size\n");
    538   x1 += bpb.bspf * bpb.nft;
    539   cls      = (bpb.bsec - x1) / bpb.spc;
    540   capacity = (uint64_t)bpb.bspf * bpb.bps * 8 / fat - RESFTE;
    541   capacity = MINIMUM(capacity, maxcls(fat));
    542   if (cls > capacity) {
    543     cls      = capacity;
    544     bpb.bsec = x1 + cls * bpb.spc;
    545     weprintf("warning: FAT limits filesystem to %u sectors\n", bpb.bsec);
    546   }
    547   if (cls < mincls(fat))
    548     eprintf("%u clusters too few for FAT%u, need %u\n", cls, fat, mincls(fat));
    549   printf(
    550       "%s: %u sector%s in %u FAT%u cluster%s "
    551       "(%u bytes/cluster)\n",
    552       fname,
    553       cls * bpb.spc,
    554       cls * bpb.spc == 1 ? "" : "s",
    555       cls,
    556       fat,
    557       cls == 1 ? "" : "s",
    558       bpb.bps * bpb.spc
    559   );
    560   if (!bpb.mid)
    561     bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
    562   if (fat == 32)
    563     bpb.rdcl = RESFTE;
    564   if ((uint64_t)bpb.hid + bpb.bsec <= MAXU16) {
    565     bpb.sec  = bpb.bsec;
    566     bpb.bsec = 0;
    567   }
    568   if (fat != 32) {
    569     bpb.spf  = bpb.bspf;
    570     bpb.bspf = 0;
    571   }
    572   print_bpb(&bpb);
    573   if (!opt_N) {
    574     if (gettimeofday(&tv, NULL) < 0)
    575       eprintf("gettimeofday:");
    576     now = tv.tv_sec;
    577     if ((tm = localtime(&now)) == NULL)
    578       eprintf("Invalid time\n");
    579 
    580     img = emalloc(bpb.bps);
    581     dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
    582     for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
    583       x = lsn;
    584       if (opt_B && fat == 32 && bpb.bkbs != MAXU16 && bss <= bpb.bkbs && x >= bpb.bkbs) {
    585         x -= bpb.bkbs;
    586         if (!x && lseek(fd1, 0, SEEK_SET))
    587           eprintf("%s:", bname);
    588       }
    589       if (opt_B && x < bss) {
    590         if ((n = read(fd1, img, bpb.bps)) == -1)
    591           eprintf("%s:", bname);
    592         if (n != bpb.bps)
    593           eprintf("%s: can't read sector %u\n", bname, x);
    594       } else
    595         memset(img, 0, bpb.bps);
    596       if (!lsn || (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
    597         x1    = sizeof(struct bs);
    598         bsbpb = (struct bsbpb *)(img + x1);
    599         mk2(bsbpb->bps, bpb.bps);
    600         mk1(bsbpb->spc, bpb.spc);
    601         mk2(bsbpb->res, bpb.res);
    602         mk1(bsbpb->nft, bpb.nft);
    603         mk2(bsbpb->rde, bpb.rde);
    604         mk2(bsbpb->sec, bpb.sec);
    605         mk1(bsbpb->mid, bpb.mid);
    606         mk2(bsbpb->spf, bpb.spf);
    607         mk2(bsbpb->spt, bpb.spt);
    608         mk2(bsbpb->hds, bpb.hds);
    609         mk4(bsbpb->hid, bpb.hid);
    610         mk4(bsbpb->bsec, bpb.bsec);
    611         x1 += sizeof(struct bsbpb);
    612         if (fat == 32) {
    613           bsxbpb = (struct bsxbpb *)(img + x1);
    614           mk4(bsxbpb->bspf, bpb.bspf);
    615           mk2(bsxbpb->xflg, 0);
    616           mk2(bsxbpb->vers, 0);
    617           mk4(bsxbpb->rdcl, bpb.rdcl);
    618           mk2(bsxbpb->infs, bpb.infs);
    619           mk2(bsxbpb->bkbs, bpb.bkbs);
    620           x1 += sizeof(struct bsxbpb);
    621         }
    622         bsx = (struct bsx *)(img + x1);
    623         mk1(bsx->sig, 0x29);
    624         if (Iflag)
    625           x = opt_I;
    626         else
    627           x = (((unsigned int)(1 + tm->tm_mon) << 8 | (unsigned int)tm->tm_mday)
    628                + ((unsigned int)tm->tm_sec << 8 | (unsigned int)(tv.tv_usec / 10)))
    629                   << 16
    630               | ((unsigned int)(1900 + tm->tm_year)
    631                  + ((unsigned int)tm->tm_hour << 8 | (unsigned int)tm->tm_min));
    632         mk4(bsx->volid, x);
    633         mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
    634         setstr(bsx->type, fat == 12 ? "FAT12" : fat == 16 ? "FAT16" : "FAT32", sizeof(bsx->type));
    635         if (!opt_B) {
    636           x1 += sizeof(struct bsx);
    637           bs = (struct bs *)img;
    638           mk1(bs->jmp[0], 0xeb);
    639           mk1(bs->jmp[1], x1 - 2);
    640           mk1(bs->jmp[2], 0x90);
    641           setstr(bs->oem, opt_O ? opt_O : "BSD  4.4", sizeof(bs->oem));
    642           memcpy(img + x1, bootcode, sizeof(bootcode));
    643           mk2(img + MINBPS - 2, DOSMAGIC);
    644         }
    645       } else if (
    646           fat == 32 && bpb.infs != MAXU16
    647           && (lsn == bpb.infs || (bpb.bkbs != MAXU16 && lsn == bpb.bkbs + bpb.infs))
    648       ) {
    649         mk4(img, 0x41615252);
    650         mk4(img + MINBPS - 28, 0x61417272);
    651         mk4(img + MINBPS - 24, cls - 1);
    652         mk4(img + MINBPS - 20, bpb.rdcl + 1);
    653         mk2(img + MINBPS - 2, DOSMAGIC);
    654       } else if (
    655           lsn >= bpb.res && lsn < dir && !((lsn - bpb.res) % (bpb.spf ? bpb.spf : bpb.bspf))
    656       ) {
    657         mk1(img[0], bpb.mid);
    658         for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
    659           mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
    660       } else if (lsn == dir && opt_L) {
    661         de = (struct de *)img;
    662         mklabel(de->namext, opt_L);
    663         mk1(de->attr, 0x08);
    664         x = (unsigned int)tm->tm_hour << 11 | (unsigned int)tm->tm_min << 5
    665             | (unsigned int)tm->tm_sec >> 1;
    666         mk2(de->time, x);
    667         x = (unsigned int)(tm->tm_year - 80) << 9 | (unsigned int)(tm->tm_mon + 1) << 5
    668             | (unsigned int)tm->tm_mday;
    669         mk2(de->date, x);
    670       }
    671       if ((n = writeall(fd, img, bpb.bps)) == -1)
    672         eprintf("%s:", fname);
    673       if (n != bpb.bps)
    674         eprintf("%s: can't write sector %u\n", fname, lsn);
    675     }
    676     free(img);
    677     if (fsync(fd) < 0)
    678       eprintf("%s:", fname);
    679   }
    680   if (fd1 >= 0)
    681     close(fd1);
    682   if (close(fd) < 0)
    683     eprintf("%s:", fname);
    684   return fshut(stdout, "<stdout>");
    685 }
    686 
    687 /* Fill the BPB from the opened partition or the length of an existing image. */
    688 static void
    689 gettarget(int fd, const char *path, int dry, struct bpb *bpb)
    690 {
    691   struct stat     st;
    692   struct BlockDev dev = {.fd = fd};
    693   uint64_t        sectors, start = 0;
    694 
    695   if (fstat(fd, &st) < 0)
    696     eprintf("%s:", path);
    697   if (S_ISREG(st.st_mode)) {
    698     dev.size     = st.st_size;
    699     dev.sec_size = MINBPS;
    700 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
    701   } else if (S_ISBLK(st.st_mode)) {
    702     struct hd_geometry geo;
    703 
    704     blockdev_sys_size(&dev);
    705     if (ioctl(fd, HDIO_GETGEO, &geo) == 0) {
    706       start = (uint64_t)geo.start * 512;
    707       if (!bpb->spt)
    708         bpb->spt = geo.sectors;
    709       if (!bpb->hds)
    710         bpb->hds = geo.heads;
    711     }
    712 #elif defined(__FreeBSD__) && !defined(ARUU_FORCE_POSIX)
    713   } else if (S_ISCHR(st.st_mode)) {
    714     blockdev_sys_size(&dev);
    715 #elif defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX)
    716   } else if (S_ISCHR(st.st_mode)) {
    717     struct disklabel dl;
    718     struct statfs   *mp;
    719     size_t           part = DISKPART(st.st_rdev);
    720     int              n;
    721 
    722     if (ioctl(fd, DIOCGDINFO, &dl) < 0)
    723       eprintf("%s: disklabel:", path);
    724     if (part >= dl.d_npartitions)
    725       eprintf("%s: partition unavailable\n", path);
    726     if (!dry) {
    727       struct stat raw;
    728       char        name[PATH_MAX];
    729 
    730       if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
    731         eprintf("getmntinfo:");
    732       for (; n--; mp++) {
    733         if (strncmp(mp->f_mntfromname, "/dev/", 5))
    734           continue;
    735         if (snprintf(name, sizeof name, "/dev/r%s", mp->f_mntfromname + 5) >= (int)sizeof name)
    736           eprintf("mounted device name too long\n");
    737         if (stat(name, &raw) == 0 && S_ISCHR(raw.st_mode)
    738             && (raw.st_rdev == st.st_rdev
    739                 || (part == RAW_PART && DISKLABELDEV(raw.st_rdev) == DISKLABELDEV(st.st_rdev))))
    740           eprintf("%s is mounted on %s\n", path, mp->f_mntonname);
    741       }
    742     }
    743     dev.sec_size = dl.d_secsize;
    744     dev.size     = DL_GETPSIZE(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize;
    745     start        = DL_GETPOFFSET(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize;
    746     if (!bpb->spt && dl.d_nsectors <= 63)
    747       bpb->spt = dl.d_nsectors;
    748     if (!bpb->hds && dl.d_ntracks <= MAXU16)
    749       bpb->hds = dl.d_ntracks;
    750 #endif
    751   } else {
    752     eprintf("%s: unsupported file type\n", path);
    753   }
    754   (void)dry;
    755   if (!dev.sec_size || !dev.size)
    756     eprintf("%s: cannot determine a nonzero target size\n", path);
    757   if (!bpb->bps)
    758     bpb->bps = dev.sec_size;
    759   if (bpb->bps < dev.sec_size || bpb->bps > MAXU16)
    760     eprintf("%s: invalid sector size %u\n", path, bpb->bps);
    761   sectors = dev.size / bpb->bps;
    762   if (start / bpb->bps <= UINT32_MAX)
    763     bpb->hid = start / bpb->bps;
    764   if (!bpb->mid && !S_ISREG(st.st_mode))
    765     bpb->mid = 0xf8;
    766   if (!bpb->bsec) {
    767     if (sectors > UINT32_MAX)
    768       eprintf("%s: too many sectors for FAT\n", path);
    769     bpb->bsec = sectors;
    770   }
    771   if (!bpb->bsec || bpb->bsec > sectors)
    772     eprintf("%s: filesystem does not fit on target\n", path);
    773   if (!bpb->spt)
    774     bpb->spt = 63;
    775   if (!bpb->hds)
    776     bpb->hds = 255;
    777 }
    778 
    779 /*
    780  * Get a standard format.
    781  */
    782 static void
    783 getstdfmt(const char *fmt, struct bpb *bpb)
    784 {
    785   unsigned int x, i;
    786 
    787   x = sizeof(stdfmt) / sizeof(stdfmt[0]);
    788   for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++)
    789     continue;
    790   if (i == x)
    791     eprintf("%s: unknown standard format\n", fmt);
    792   *bpb = stdfmt[i].bpb;
    793 }
    794 
    795 /*
    796  * Print out BPB values.
    797  */
    798 static void
    799 print_bpb(struct bpb *bpb)
    800 {
    801   printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res, bpb->nft);
    802   if (bpb->rde)
    803     printf(" rde=%u", bpb->rde);
    804   if (bpb->sec)
    805     printf(" sec=%u", bpb->sec);
    806   printf(" mid=%#x", bpb->mid);
    807   if (bpb->spf)
    808     printf(" spf=%u", bpb->spf);
    809   printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
    810   if (bpb->bsec)
    811     printf(" bsec=%u", bpb->bsec);
    812   if (!bpb->spf) {
    813     printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
    814     printf(" infs=");
    815     printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
    816     printf(" bkbs=");
    817     printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
    818   }
    819   printf("\n");
    820 }
    821 
    822 /*
    823  * Convert and check a numeric option argument.
    824  */
    825 static unsigned int
    826 argtou(const char *arg, unsigned int lo, unsigned int hi, const char *msg)
    827 {
    828   char         *s;
    829   unsigned long x;
    830 
    831   errno = 0;
    832   x     = strtoul(arg, &s, 0);
    833   if (errno || !*arg || *arg == '-' || isspace((unsigned char)*arg) || *s || x < lo || x > hi)
    834     eprintf("%s: bad %s\n", arg, msg);
    835   return x;
    836 }
    837 
    838 /*
    839  * Check a volume label.
    840  */
    841 static int
    842 oklabel(const char *src)
    843 {
    844   int c = 0, i;
    845 
    846   for (i = 0; i <= 11; i++) {
    847     c = (unsigned char)*src++;
    848     if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
    849       break;
    850   }
    851   return i && !c;
    852 }
    853 
    854 /*
    855  * Make a volume label.
    856  */
    857 static void
    858 mklabel(uint8_t *dest, const char *src)
    859 {
    860   int c, i;
    861 
    862   for (i = 0; i < 11; i++) {
    863     c       = *src ? toupper((unsigned char)*src++) : ' ';
    864     *dest++ = !i && c == 0xe5 ? 5 : c;
    865   }
    866 }
    867 
    868 /*
    869  * Copy string, padding with spaces.
    870  */
    871 static void
    872 setstr(uint8_t *dest, const char *src, size_t len)
    873 {
    874   while (len--)
    875     *dest++ = *src ? *src++ : ' ';
    876 }
    877 
    878 /*
    879  * Print usage message.
    880  */
    881 static void __attribute__((noreturn))
    882 usage(void)
    883 {
    884   eprintf(
    885       "usage: %s "
    886       "[-N] [-a FAT-size] [-B boot] [-b block-size]\n"
    887       "\t[-c cluster-size] [-e dirents] [-F FAT-type] [-f format]\n"
    888       "\t[-h heads] [-I volid] [-i info] [-k backup] [-L label]\n"
    889       "\t[-m media] [-n label] [-A FATs] [-O OEM] [-o hidden] [-r reserved]\n"
    890       "\t[-S sector-size] [-s total] [-u track-size] device-or-image\n",
    891       argv0
    892   );
    893 }