Home | History | Annotate | Download | only in mksdcard
      1 /* mksdcard.c
      2 **
      3 ** Copyright 2007, The Android Open Source Project
      4 **
      5 ** Redistribution and use in source and binary forms, with or without
      6 ** modification, are permitted provided that the following conditions are met:
      7 **     * Redistributions of source code must retain the above copyright
      8 **       notice, this list of conditions and the following disclaimer.
      9 **     * Redistributions in binary form must reproduce the above copyright
     10 **       notice, this list of conditions and the following disclaimer in the
     11 **       documentation and/or other materials provided with the distribution.
     12 **     * Neither the name of Google Inc. nor the names of its contributors may
     13 **       be used to endorse or promote products derived from this software
     14 **       without specific prior written permission.
     15 **
     16 ** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
     17 ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18 ** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19 ** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21 ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22 ** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24 ** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25 ** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26 */
     27 
     28 /* a simple and portable program used to generate a blank FAT32 image file
     29  *
     30  * usage: mksdcard [-l label] <size> <filename>
     31  */
     32 
     33 #include <time.h>
     34 #include <stdio.h>
     35 #include <stdlib.h>
     36 #include <string.h>
     37 #include <errno.h>
     38 #include <unistd.h>
     39 
     40 /* believe me, you *don't* want to change these constants !! */
     41 #define  BYTES_PER_SECTOR    512
     42 #define  RESERVED_SECTORS    32
     43 #define  BACKUP_BOOT_SECTOR  6
     44 #define  NUM_FATS            2
     45 
     46 /* sectors_per_disk is encoded as a signed int */
     47 #define MAX_SECTORS_PER_DISK 0x7FFFFFFF
     48 #define MAX_DISK_SIZE ((Wide)MAX_SECTORS_PER_DISK * BYTES_PER_SECTOR)
     49 
     50 typedef long long      Wide;   /* might be something else if you don't use GCC */
     51 typedef unsigned char  Byte;
     52 typedef Byte*          Bytes;
     53 
     54 #define  BYTE_(p,i)      (((Bytes)(p))[(i)])
     55 
     56 #define  POKEB(p,v)     BYTE_(p,0) = (Byte)(v)
     57 #define  POKES(p,v)   ( BYTE_(p,0) = (Byte)(v), BYTE_(p,1) = (Byte)((v) >> 8) )
     58 #define  POKEW(p,v)   ( BYTE_(p,0) = (Byte)(v), BYTE_(p,1) = (Byte)((v) >> 8), BYTE_(p,2) = (Byte)((v) >> 16), BYTE_(p,3) = (Byte)((v) >> 24) )
     59 
     60 static Byte  s_boot_sector   [ BYTES_PER_SECTOR ];   /* boot sector */
     61 static Byte  s_fsinfo_sector [ BYTES_PER_SECTOR ];   /* FS Info sector */
     62 static Byte  s_fat_head      [ BYTES_PER_SECTOR ];   /* first FAT sector */
     63 static Byte  s_zero_sector   [ BYTES_PER_SECTOR ];   /* empty sector */
     64 
     65 /* this is the date and time when creating the disk */
     66 static int
     67 get_serial_id( void )
     68 {
     69     unsigned short  lo, hi, mid;
     70     time_t          now = time(NULL);
     71     struct tm       tm  = gmtime( &now )[0];
     72 
     73     lo  = (unsigned short)(tm.tm_mday + ((tm.tm_mon+1) << 8) + (tm.tm_sec << 8));
     74     hi  = (unsigned short)(tm.tm_min + (tm.tm_hour << 8) + (tm.tm_year + 1900));
     75 
     76     return lo + (hi << 16);
     77 }
     78 
     79 static int
     80 get_sectors_per_cluster( Wide  disk_size )
     81 {
     82     Wide  disk_MB = disk_size/(1024*1024);
     83 
     84     if (disk_MB < 260)
     85         return 1;
     86 
     87     if (disk_MB < 8192)
     88         return 4;
     89 
     90     if (disk_MB < 16384)
     91         return 8;
     92 
     93     if (disk_MB < 32768)
     94         return 16;
     95 
     96     return 32;
     97 }
     98 
     99 static int
    100 get_sectors_per_fat( Wide  disk_size, int  sectors_per_cluster )
    101 {
    102     Wide   divider;
    103 
    104     /* weird computation from MS - see fatgen103.doc for details */
    105     disk_size -= RESERVED_SECTORS * BYTES_PER_SECTOR;  /* don't count 32 reserved sectors */
    106     disk_size /= BYTES_PER_SECTOR;       /* disk size in sectors */
    107     divider = ((256 * sectors_per_cluster) + NUM_FATS) / 2;
    108 
    109     return (int)( (disk_size + (divider-1)) / divider );
    110 }
    111 
    112 static void
    113 boot_sector_init( Bytes  boot, Bytes  info, Wide   disk_size, const char*  label )
    114 {
    115     int   sectors_per_cluster = get_sectors_per_cluster(disk_size);
    116     int   sectors_per_fat    = get_sectors_per_fat(disk_size, sectors_per_cluster);
    117     int   sectors_per_disk   = (int)(disk_size / BYTES_PER_SECTOR);
    118     int   serial_id          = get_serial_id();
    119     int   free_count;
    120 
    121     if (label == NULL)
    122         label = "SDCARD";
    123 
    124     POKEB(boot, 0xeb);
    125     POKEB(boot+1, 0x5a);
    126     POKEB(boot+2, 0x90);
    127     strcpy( (char*)boot + 3, "MSWIN4.1" );
    128     POKES( boot + 0x0b, BYTES_PER_SECTOR );    /* sector size */
    129     POKEB( boot + 0xd, sectors_per_cluster );  /* sectors per cluster */
    130     POKES( boot + 0xe, RESERVED_SECTORS );     /* reserved sectors before first FAT */
    131     POKEB( boot + 0x10, NUM_FATS );            /* number of FATs */
    132     POKES( boot + 0x11, 0 );                   /* max root directory entries for FAT12/FAT16, 0 for FAT32 */
    133     POKES( boot + 0x13, 0 );                   /* total sectors, 0 to use 32-bit value at offset 0x20 */
    134     POKEB( boot + 0x15, 0xF8 );                /* media descriptor, 0xF8 == hard disk */
    135     POKES( boot + 0x16, 0 );                   /* Sectors per FAT for FAT12/16, 0 for FAT32 */
    136     POKES( boot + 0x18, 9 );                   /* Sectors per track (whatever) */
    137     POKES( boot + 0x1a, 2 );                   /* Number of heads (whatever) */
    138     POKEW( boot + 0x1c, 0 );                   /* Hidden sectors */
    139     POKEW( boot + 0x20, sectors_per_disk );    /* Total sectors */
    140 
    141     /* extension */
    142     POKEW( boot + 0x24, sectors_per_fat );       /* Sectors per FAT */
    143     POKES( boot + 0x28, 0 );         /* FAT flags */
    144     POKES( boot + 0x2a, 0 );         /* version */
    145     POKEW( boot + 0x2c, 2 );         /* cluster number of root directory start */
    146     POKES( boot + 0x30, 1 );         /* sector number of FS information sector */
    147     POKES( boot + 0x32, BACKUP_BOOT_SECTOR );         /* sector number of a copy of this boot sector */
    148     POKEB( boot + 0x40, 0x80 );      /* physical drive number */
    149     POKEB( boot + 0x42, 0x29 );      /* extended boot signature ?? */
    150     POKEW( boot + 0x43, serial_id ); /* serial ID */
    151     strncpy( (char*)boot + 0x47, label, 11 );  /* Volume Label */
    152     memcpy( boot + 0x52, "FAT32   ", 8 );  /* FAT system type, padded with 0x20 */
    153 
    154     POKEB( boot + BYTES_PER_SECTOR-2, 0x55 );    /* boot sector signature */
    155     POKEB( boot + BYTES_PER_SECTOR-1, 0xAA );
    156 
    157     /* FSInfo sector */
    158     free_count = sectors_per_disk - 32 - 2*sectors_per_fat;
    159 
    160     POKEW( info + 0,   0x41615252 );
    161     POKEW( info + 484, 0x61417272 );
    162     POKEW( info + 488, free_count );   /* number of free clusters */
    163     POKEW( info + 492, 3 );            /* next free clusters, 0-1 reserved, 2 is used for the root dir */
    164     POKEW( info + 508, 0xAA550000 );
    165 }
    166 
    167 static void
    168 fat_init( Bytes  fat )
    169 {
    170     POKEW( fat,     0x0ffffff8 );  /* reserve cluster 1, media id in low byte */
    171     POKEW( fat + 4, 0x0fffffff );  /* reserve cluster 2 */
    172     POKEW( fat + 8, 0x0fffffff );  /* end of clust chain for root dir */
    173 }
    174 
    175 
    176 static int
    177 write_sector( FILE*  file, Bytes  sector )
    178 {
    179     int result = fwrite( sector, 1, BYTES_PER_SECTOR, file ) != BYTES_PER_SECTOR;
    180     if (result) {
    181       fprintf(stderr, "Failed to write sector of %d bytes: %s\n", BYTES_PER_SECTOR, strerror(errno));
    182     }
    183     return result;
    184 }
    185 
    186 static int
    187 write_empty( FILE*   file, Wide  count )
    188 {
    189     static  Byte  empty[256*1024];
    190     memset(empty, 0, sizeof(empty));
    191 
    192     count *= BYTES_PER_SECTOR;
    193     while (count > 0) {
    194         int  len = sizeof(empty);
    195         if (len > count)
    196           len = count;
    197         if ( fwrite( empty, 1, len, file ) != (size_t)len ) {
    198             fprintf(stderr, "Failed to write %d bytes: %s\n", len, strerror(errno));
    199             return 1;
    200         }
    201 
    202         count -= len;
    203     }
    204     return 0;
    205 }
    206 
    207 static void usage (void)
    208 {
    209     fprintf(stderr, "mksdcard: create a blank FAT32 image to be used with the Android emulator\n" );
    210     fprintf(stderr, "usage: mksdcard [-l label] <size> <file>\n\n");
    211     fprintf(stderr, "  if <size> is a simple integer, it specifies a size in bytes\n" );
    212     fprintf(stderr, "  if <size> is an integer followed by 'K', it specifies a size in KiB\n" );
    213     fprintf(stderr, "  if <size> is an integer followed by 'M', it specifies a size in MiB\n" );
    214     fprintf(stderr, "  if <size> is an integer followed by 'G', it specifies a size in GiB\n" );
    215     fprintf(stderr, "\nMinimum size is 9M. The Android emulator cannot use smaller images.\n" );
    216     fprintf(stderr, "Maximum size is %lld bytes, %lldK, %lldM or %lldG\n",
    217             MAX_DISK_SIZE, MAX_DISK_SIZE >> 10, MAX_DISK_SIZE >> 20, MAX_DISK_SIZE >> 30);
    218     exit(1);
    219 }
    220 
    221 int  main( int argc, char**  argv )
    222 {
    223     Wide   disk_size;
    224     int    sectors_per_fat;
    225     int    sectors_per_disk;
    226     char*  end;
    227     const char*  label = NULL;
    228     FILE*  f = NULL;
    229 
    230     for ( ; argc > 1 && argv[1][0] == '-'; argc--, argv++ )
    231     {
    232         char*  arg = argv[1] + 1;
    233         switch (arg[0]) {
    234             case 'l':
    235                 if (arg[1] != 0)
    236                     arg += 2;
    237                 else {
    238                     argc--;
    239                     argv++;
    240                     if (argc <= 1)
    241                         usage();
    242                     arg = argv[1];
    243                 }
    244                 label = arg;
    245                 break;
    246 
    247             default:
    248                 usage();
    249         }
    250     }
    251 
    252     if (argc != 3)
    253         usage();
    254 
    255     disk_size = strtoll( argv[1], &end, 10 );
    256     if (disk_size <= 0 || errno == EINVAL || errno == ERANGE) {
    257         fprintf(stderr, "Invalid argument size '%s'\n\n", argv[1]);
    258         usage();
    259     }
    260 
    261     if (*end == 'K')
    262         disk_size *= 1024;
    263     else if (*end == 'M')
    264         disk_size *= 1024*1024;
    265     else if (*end == 'G')
    266         disk_size *= 1024*1024*1024;
    267 
    268     if (disk_size < 9*1024*1024) {
    269         fprintf(stderr, "Invalid argument: size '%s' is too small.\n\n", argv[1]);
    270         usage();
    271     } else if (disk_size > MAX_DISK_SIZE) {
    272         fprintf(stderr, "Invalid argument: size '%s' is too large.\n\n", argv[1]);
    273         usage();
    274     }
    275 
    276     sectors_per_disk = disk_size / BYTES_PER_SECTOR;
    277     sectors_per_fat  = get_sectors_per_fat( disk_size, get_sectors_per_cluster( disk_size ) );
    278 
    279     boot_sector_init( s_boot_sector, s_fsinfo_sector, disk_size, NULL );
    280     fat_init( s_fat_head );
    281 
    282     f = fopen( argv[2], "wb" );
    283     if ( !f ) {
    284       fprintf(stderr, "Could not create file '%s': %s\n", argv[2], strerror(errno));
    285       goto FailWrite;
    286     }
    287 
    288    /* here's the layout:
    289     *
    290     *  boot_sector
    291     *  fsinfo_sector
    292     *  empty
    293     *  backup boot sector
    294     *  backup fsinfo sector
    295     *  RESERVED_SECTORS - 4 empty sectors (if backup sectors), or RESERVED_SECTORS - 2 (if no backup)
    296     *  first fat
    297     *  second fat
    298     *  zero sectors
    299    */
    300 
    301     if ( write_sector( f, s_boot_sector ) ) goto FailWrite;
    302     if ( write_sector( f, s_fsinfo_sector ) ) goto FailWrite;
    303     if ( BACKUP_BOOT_SECTOR > 0 ) {
    304         if ( write_empty( f, BACKUP_BOOT_SECTOR - 2 ) ) goto FailWrite;
    305         if ( write_sector( f, s_boot_sector ) ) goto FailWrite;
    306         if ( write_sector( f, s_fsinfo_sector ) ) goto FailWrite;
    307         if ( write_empty( f, RESERVED_SECTORS - 2 - BACKUP_BOOT_SECTOR ) ) goto FailWrite;
    308     }
    309     else if ( write_empty( f, RESERVED_SECTORS - 2 ) ) goto FailWrite;
    310 
    311     if ( write_sector( f, s_fat_head ) ) goto FailWrite;
    312     if ( write_empty( f, sectors_per_fat-1 ) ) goto FailWrite;
    313 
    314     if ( write_sector( f, s_fat_head ) ) goto FailWrite;
    315     if ( write_empty( f, sectors_per_fat-1 ) ) goto FailWrite;
    316 
    317     if ( write_empty( f, sectors_per_disk - RESERVED_SECTORS - 2*sectors_per_fat ) ) goto FailWrite;
    318 
    319     fclose(f);
    320     return 0;
    321 
    322 FailWrite:
    323     if (f != NULL) {
    324       fclose(f);
    325       unlink( argv[2] );
    326       fprintf(stderr, "File '%s' was not created.\n", argv[2]);
    327     }
    328     return 1;
    329 }
    330