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 typedef long long      Wide;   /* might be something else if you don't use GCC */
     47 typedef unsigned char  Byte;
     48 typedef Byte*          Bytes;
     49 
     50 #define  BYTE_(p,i)      (((Bytes)(p))[(i)])
     51 
     52 #define  POKEB(p,v)     BYTE_(p,0) = (Byte)(v)
     53 #define  POKES(p,v)   ( BYTE_(p,0) = (Byte)(v), BYTE_(p,1) = (Byte)((v) >> 8) )
     54 #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) )
     55 
     56 static Byte  s_boot_sector   [ BYTES_PER_SECTOR ];       /* boot sector */
     57 static Byte  s_fsinfo_sector [ BYTES_PER_SECTOR ];   /* FS Info sector */
     58 static Byte  s_fat_head      [ BYTES_PER_SECTOR ];        /* first FAT sector */
     59 static Byte  s_zero_sector   [ BYTES_PER_SECTOR ];     /* empty sector */
     60 
     61 /* this is the date and time when creating the disk */
     62 static int
     63 get_serial_id( void )
     64 {
     65     unsigned short  lo, hi, mid;
     66     time_t          now = time(NULL);
     67     struct tm       tm  = gmtime( &now )[0];
     68 
     69     lo  = (unsigned short)(tm.tm_mday + ((tm.tm_mon+1) << 8) + (tm.tm_sec << 8));
     70     hi  = (unsigned short)(tm.tm_min + (tm.tm_hour << 8) + (tm.tm_year + 1900));
     71 
     72     return lo + (hi << 16);
     73 }
     74 
     75 static int
     76 get_sectors_per_cluster( Wide  disk_size )
     77 {
     78     Wide  disk_MB = disk_size/(1024*1024);
     79 
     80     if (disk_MB < 260)
     81         return 1;
     82 
     83     if (disk_MB < 8192)
     84         return 4;
     85 
     86     if (disk_MB < 16384)
     87         return 8;
     88 
     89     if (disk_MB < 32768)
     90         return 16;
     91 
     92     return 32;
     93 }
     94 
     95 static int
     96 get_sectors_per_fat( Wide  disk_size, int  sectors_per_cluster )
     97 {
     98     Wide   divider;
     99 
    100     /* weird computation from MS - see fatgen103.doc for details */
    101     disk_size -= RESERVED_SECTORS * BYTES_PER_SECTOR;  /* don't count 32 reserved sectors */
    102     disk_size /= BYTES_PER_SECTOR;       /* disk size in sectors */
    103     divider = ((256 * sectors_per_cluster) + NUM_FATS) / 2;
    104 
    105     return (int)( (disk_size + (divider-1)) / divider );
    106 }
    107 
    108 static void
    109 boot_sector_init( Bytes  boot, Bytes  info, Wide   disk_size, const char*  label )
    110 {
    111     int   sectors_per_cluster = get_sectors_per_cluster(disk_size);
    112     int   sectors_per_fat    = get_sectors_per_fat(disk_size, sectors_per_cluster);
    113     int   sectors_per_disk   = (int)(disk_size / BYTES_PER_SECTOR);
    114     int   serial_id          = get_serial_id();
    115     int   free_count;
    116 
    117     if (label == NULL)
    118         label = "SDCARD";
    119 
    120     POKEB(boot, 0xeb);
    121     POKEB(boot+1, 0x5a);
    122     POKEB(boot+2, 0x90);
    123     strcpy( (char*)boot + 3, "MSWIN4.1" );
    124     POKES( boot + 0x0b, BYTES_PER_SECTOR );    /* sector size */
    125     POKEB( boot + 0xd, sectors_per_cluster );  /* sectors per cluster */
    126     POKES( boot + 0xe, RESERVED_SECTORS );     /* reserved sectors before first FAT */
    127     POKEB( boot + 0x10, NUM_FATS );            /* number of FATs */
    128     POKES( boot + 0x11, 0 );                   /* max root directory entries for FAT12/FAT16, 0 for FAT32 */
    129     POKES( boot + 0x13, 0 );                   /* total sectors, 0 to use 32-bit value at offset 0x20 */
    130     POKEB( boot + 0x15, 0xF8 );                /* media descriptor, 0xF8 == hard disk */
    131     POKES( boot + 0x16, 0 );                   /* Sectors per FAT for FAT12/16, 0 for FAT32 */
    132     POKES( boot + 0x18, 9 );                   /* Sectors per track (whatever) */
    133     POKES( boot + 0x1a, 2 );                   /* Number of heads (whatever) */
    134     POKEW( boot + 0x1c, 0 );                   /* Hidden sectors */
    135     POKEW( boot + 0x20, sectors_per_disk );    /* Total sectors */
    136 
    137     /* extension */
    138     POKEW( boot + 0x24, sectors_per_fat );       /* Sectors per FAT */
    139     POKES( boot + 0x28, 0 );         /* FAT flags */
    140     POKES( boot + 0x2a, 0 );         /* version */
    141     POKEW( boot + 0x2c, 2 );         /* cluster number of root directory start */
    142     POKES( boot + 0x30, 1 );         /* sector number of FS information sector */
    143     POKES( boot + 0x32, BACKUP_BOOT_SECTOR );         /* sector number of a copy of this boot sector */
    144     POKEB( boot + 0x40, 0x80 );      /* physical drive number */
    145     POKEB( boot + 0x42, 0x29 );      /* extended boot signature ?? */
    146     POKEW( boot + 0x43, serial_id ); /* serial ID */
    147     strncpy( (char*)boot + 0x47, label, 11 );  /* Volume Label */
    148     memcpy( boot + 0x52, "FAT32   ", 8 );  /* FAT system type, padded with 0x20 */
    149 
    150     POKEB( boot + BYTES_PER_SECTOR-2, 0x55 );    /* boot sector signature */
    151     POKEB( boot + BYTES_PER_SECTOR-1, 0xAA );
    152 
    153     /* FSInfo sector */
    154     free_count = sectors_per_disk - 32 - 2*sectors_per_fat;
    155 
    156     POKEW( info + 0,   0x41615252 );
    157     POKEW( info + 484, 0x61417272 );
    158     POKEW( info + 488, free_count );   /* number of free clusters */
    159     POKEW( info + 492, 3 );            /* next free clusters, 0-1 reserved, 2 is used for the root dir */
    160     POKEW( info + 508, 0xAA550000 );
    161 }
    162 
    163 static void
    164 fat_init( Bytes  fat )
    165 {
    166     POKEW( fat,     0x0ffffff8 );  /* reserve cluster 1, media id in low byte */
    167     POKEW( fat + 4, 0x0fffffff );  /* reserve cluster 2 */
    168     POKEW( fat + 8, 0x0fffffff );  /* end of clust chain for root dir */
    169 }
    170 
    171 
    172 static int
    173 write_sector( FILE*  file, Bytes  sector )
    174 {
    175     return fwrite( sector, 1, 512, file ) != 512;
    176 }
    177 
    178 static int
    179 write_empty( FILE*   file, Wide  count )
    180 {
    181     static  Byte  empty[64*1024];
    182 
    183     count *= 512;
    184     while (count > 0) {
    185         int  len = sizeof(empty);
    186         if (len > count)
    187             len = count;
    188 
    189         if ( fwrite( empty, 1, len, file ) != (size_t)len )
    190             return 1;
    191 
    192         count -= len;
    193     }
    194     return 0;
    195 }
    196 
    197 static void usage (void)
    198 {
    199     fprintf(stderr, "mksdcard: create a blank FAT32 image to be used with the Android emulator\n" );
    200     fprintf(stderr, "usage: mksdcard [-l label] <size> <file>\n\n");
    201     fprintf(stderr, "  if <size> is a simple integer, it specifies a size in bytes\n" );
    202     fprintf(stderr, "  if <size> is an integer followed by 'K', it specifies a size in KiB\n" );
    203     fprintf(stderr, "  if <size> is an integer followed by 'M', it specifies a size in MiB\n" );
    204     exit(1);
    205 }
    206 
    207 int  main( int argc, char**  argv )
    208 {
    209     Wide   disk_size;
    210     int    sectors_per_fat;
    211     int    sectors_per_disk;
    212     char*  end;
    213     const char*  label = NULL;
    214     FILE*  f;
    215 
    216     for ( ; argc > 1 && argv[1][0] == '-'; argc--, argv++ )
    217     {
    218         char*  arg = argv[1] + 1;
    219         switch (arg[0]) {
    220             case 'l':
    221                 if (arg[1] != 0)
    222                     arg += 2;
    223                 else {
    224                     argc--;
    225                     argv++;
    226                     if (argc <= 1)
    227                         usage();
    228                     arg = argv[1];
    229                 }
    230                 label = arg;
    231                 break;
    232 
    233             default:
    234                 usage();
    235         }
    236     }
    237 
    238     if (argc != 3)
    239         usage();
    240 
    241     disk_size = strtol( argv[1], &end, 10 );
    242     if (disk_size == 0 && errno == EINVAL)
    243         usage();
    244 
    245     if (*end == 'K')
    246         disk_size *= 1024;
    247     else if (*end == 'M')
    248         disk_size *= 1024*1024;
    249 
    250     if (disk_size < 8*1024*1024)
    251         fprintf(stderr, "### WARNING : SD Card images < 8 MB cannot be used with the Android emulator\n");
    252 
    253     sectors_per_disk = disk_size / 512;
    254     sectors_per_fat  = get_sectors_per_fat( disk_size, get_sectors_per_cluster( disk_size ) );
    255 
    256     boot_sector_init( s_boot_sector, s_fsinfo_sector, disk_size, NULL );
    257     fat_init( s_fat_head );
    258 
    259     f = fopen( argv[2], "wb" );
    260     if ( !f ) {
    261         fprintf(stderr, "could not create file '%s', aborting...\n", argv[2] );
    262     }
    263 
    264    /* here's the layout:
    265     *
    266     *  boot_sector
    267     *  fsinfo_sector
    268     *  empty
    269     *  backup boot sector
    270     *  backup fsinfo sector
    271     *  RESERVED_SECTORS - 4 empty sectors (if backup sectors), or RESERVED_SECTORS - 2 (if no backup)
    272     *  first fat
    273     *  second fat
    274     *  zero sectors
    275    */
    276 
    277     if ( write_sector( f, s_boot_sector ) )  goto FailWrite;
    278     if ( write_sector( f, s_fsinfo_sector ) ) goto FailWrite;
    279     if ( BACKUP_BOOT_SECTOR > 0 ) {
    280         if ( write_empty( f, BACKUP_BOOT_SECTOR - 2 ) ) goto FailWrite;
    281         if ( write_sector( f, s_boot_sector ) ) goto FailWrite;
    282         if ( write_sector( f, s_fsinfo_sector ) ) goto FailWrite;
    283         if ( write_empty( f, RESERVED_SECTORS - 2 - BACKUP_BOOT_SECTOR ) ) goto FailWrite;
    284     }
    285     else
    286         if ( write_empty( f, RESERVED_SECTORS - 2 ) ) goto FailWrite;
    287 
    288     if ( write_sector( f, s_fat_head ) ) goto FailWrite;
    289     if ( write_empty( f, sectors_per_fat-1 ) ) goto FailWrite;
    290 
    291     if ( write_sector( f, s_fat_head ) ) goto FailWrite;
    292     if ( write_empty( f, sectors_per_fat-1 ) ) goto FailWrite;
    293 
    294     if ( write_empty( f, sectors_per_disk - RESERVED_SECTORS - 2*sectors_per_fat ) ) goto FailWrite;
    295 
    296     fclose(f);
    297     return 0;
    298 
    299 FailWrite:
    300     fprintf(stderr, "could not write to '%s', aborting...\n", argv[2] );
    301     unlink( argv[2] );
    302     fclose(f);
    303     return 1;
    304 }
    305