Merge commit 'pam/disklib-fixes'
[profile/ivi/syslinux.git] / utils / mkdiskimage.in
1 #!/usr/bin/perl
2 ## -----------------------------------------------------------------------
3 ##
4 ##   Copyright 2002-2008 H. Peter Anvin - All Rights Reserved
5 ##   Copyright 2009 Intel Corporation; author: H. Peter Anvin
6 ##
7 ##   This program is free software; you can redistribute it and/or modify
8 ##   it under the terms of the GNU General Public License as published by
9 ##   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
10 ##   Boston MA 02111-1307, USA; either version 2 of the License, or
11 ##   (at your option) any later version; incorporated herein by reference.
12 ##
13 ## -----------------------------------------------------------------------
14
15 #
16 # Creates a blank MS-DOS formatted hard disk image
17 #
18
19 use bytes;
20 use integer;
21 use Fcntl;
22 use Errno;
23 use Cwd;
24 use IO::Handle;                 # For flush()
25
26 sub absolute_path($) {
27     my($f) = @_;
28     my($c);
29
30     return $f if ( $f =~ /^\// );
31     $c = cwd();
32     $c = '' if ( $c eq '/' );
33     return $c.'/'.$f;
34 }
35
36 sub is_linux() {
37     return !!eval '{ '.
38         'use POSIX; '.
39         '($sysname, $nodename, $release, $version, $machine) = POSIX::uname(); '.
40         "return \$sysname eq \'Linux\'; }";
41 }
42
43 sub get_random() {
44     # Get a 32-bit random number
45     my $rfd, $rnd;
46     my $rid;
47
48     if (open($rfd, "< /dev/urandom\0") && read($rfd, $rnd, 4) == 4) {
49         $rid = unpack("V", $rnd);
50     }
51
52     close($rfd) if (defined($rfd));
53     return $rid if (defined($rid));
54
55     # This sucks but is better than nothing...
56     return ($$+time()) & 0xffffffff;
57 }
58
59 sub get_hex_data() {
60     my $mbr = '';
61     my $line, $byte;
62     while ( $line = <DATA> ) {
63         chomp $line;
64         last if ($line eq '*');
65         foreach $byte ( split(/\s+/, $line) ) {
66             $mbr .= chr(hex($byte));
67         }
68     }
69     return $mbr;
70 }
71
72 $is_linux = is_linux();
73 if ( $is_linux ) {
74     # IOCTL numbers
75     $BLKRRPART    = 0x125f;
76     $BLKGETSIZE   = 0x1260;
77 }
78
79 %opt = ();
80 @args = ();
81
82 while (defined($a = shift(@ARGV))) {
83     if ( $a =~ /^\-/ ) {
84         foreach $o ( split(//, substr($a,1)) ) {
85             $opt{$o} = 1;
86             if ($o eq 'i') {
87                 $id = shift(@ARGV);
88             }
89         }
90     } else {
91         push(@args, $a);
92     }
93 }
94
95 ($file,$c,$h,$s) = @args;
96 $c += 0;  $h += 0;  $s += 0;
97
98 $pentry = 1;
99 $pentry = 2 if ( $opt{'2'} );
100 $pentry = 3 if ( $opt{'3'} );
101 $pentry = 4 if ( $opt{'4'} );
102
103 if ( $opt{'z'} ) {
104     $h = $h || 64;
105     $s = $s || 32;
106 }
107
108 if ( $opt{'M'} && $h && $s ) {
109     # Specify size in megabytes, not in cylinders
110     $c = ($c*1024*2)/($h*$s);
111 }
112
113 $is_open = 0;
114
115 if ( $c == 0 && $file ne '' ) {
116     $len = 0;
117     if ( sysopen(OUTPUT, $file, O_RDWR, 0666) ) {
118         $is_open = 1;
119
120         if ( (@filestat = stat(OUTPUT)) && S_ISREG($filestat[2]) ) {
121             $len = $filestat[7] >> 9;
122         } elsif ( $is_linux && S_ISBLK($filestat[2]) ) {
123             $blksize = pack("L!", 0);
124             if ( ioctl(OUTPUT, $BLKGETSIZE, $blksize) == 0 ) {
125                 $len = unpack("L!", $blksize); # In 512-byte sectors!
126             }
127         }
128     }
129
130     if ( !$len ) {
131         print STDERR "$0: $file: don't know how to determine the size of this device\n";
132         exit 1;
133     }
134
135     $c = $len/($h*$s);
136 }
137
138 if ( $file eq '' || $c < 1 || $h < 1 || $h > 256 || $s < 1 || $s > 63 ) {
139     print STDERR "Usage: $0 [-doFMz4][-i id] file c h s (max: 1024 256 63)\n";
140     print STDERR "    -d    add DOSEMU header\n";
141     print STDERR "    -o    print filesystem offset to stdout\n";
142     print STDERR "    -F    format partition as FAT32\n";
143     print STDERR "    -M    \"c\" argument is megabytes, calculate cylinders\n";
144     print STDERR "    -z    use zipdisk geometry (h=64 s=32)\n";
145     print STDERR "    -4    use partition entry 4 (standard for zipdisks)\n";
146     print STDERR "    -i    specify the MBR ID\n";
147     exit 1;
148 }
149
150 if ($c > 1024) {
151     print STDERR "Warning: more than 1024 cylinders ($c).\n";
152     print STDERR "Not all BIOSes will be able to boot this device.\n";
153     $cc = 1024;
154 } else {
155     $cc = $c;
156 }
157
158 $cylsize = $h*$s*512;
159
160 if ( !$is_open ) {
161     sysopen(OUTPUT, $file, O_CREAT|O_RDWR|O_TRUNC, 0666)
162         or die "$0: Cannot open: $file\n";
163 }
164 binmode OUTPUT;
165
166 # Print out DOSEMU header, if requested
167 if ( $opt{'d'} ) {
168     $emuhdr = "DOSEMU\0" . pack("VVVV", $h, $s, $c, 128);
169     $emuhdr .= "\0" x (128 - length($emuhdr));
170     print OUTPUT $emuhdr;
171 }
172
173 # Print the MBR and partition table
174 $mbr = get_hex_data();
175 if ( length($mbr) > 440 ) {
176     die "$0: Bad MBR code\n";
177 }
178
179 $mbr .= "\0" x (440 - length($mbr));
180 if (defined($id)) {
181     $id = to_int($id);
182 } else {
183     $id = get_random();
184 }
185 $mbr .= pack("V", $id);         # Offset 440: MBR ID
186 $mbr .= "\0\0";                 # Offset 446: actual partition table
187
188 print OUTPUT $mbr;
189
190 # Print partition table
191 $psize = $c*$h*$s-$s;
192 $bhead   = ($h > 1) ? 1 : 0;
193 $bsect   = 1;
194 $bcyl    = ($h > 1) ? 0 : 1;
195 $ehead   = $h-1;
196 $esect   = $s + ((($cc-1) & 0x300) >> 2);
197 $ecyl    = ($cc-1) & 0xff;
198 if ( $c > 1024 ) {
199     $fstype = 0x0e;
200 } elsif ( $psize > 65536 ) {
201     $fstype = 0x06;
202 } else {
203     $fstype = 0x04;
204 }
205 for ( $i = 1 ; $i <= 4 ; $i++ ) {
206     if ( $i == $pentry ) {
207         print OUTPUT pack("CCCCCCCCVV", 0x80, $bhead, $bsect, $bcyl, $fstype,
208                           $ehead, $esect, $ecyl, $s, $psize);
209     } else {
210         print OUTPUT "\0" x 16;
211     }
212 }
213 print OUTPUT "\x55\xaa";
214
215 # Output blank file
216 $totalsize = $c*$h*$s;
217 $tracks    = $c*$h;
218
219 $track = "\0" x (512*$s);
220
221 # Print fractional track
222 print OUTPUT "\0" x (512 * ($s-1));
223
224 for ( $i = 1 ; $i < $tracks ; $i++ ) {
225     print OUTPUT $track;
226 }
227
228 # Print mtools temp file
229 $n = 0;
230 while ( !defined($tmpdir) ) {
231     $tmpdir = "/tmp/mkdiskimage.$$.".($n++);
232     if ( !mkdir($tmpdir, 0700) ) {
233         die "$0: Failed to make temp directory: $tmpdir\n"
234             if ( $! != EEXIST );
235         undef $tmpdir;
236     }
237 }
238
239 $cfgfile = $tmpdir.'/mtools.conf';
240 $imglink = $tmpdir.'/disk.img';
241 die "$0: Failed to create symlink $imglink\n"
242     if ( !symlink(absolute_path($file), $imglink) );
243
244 $header_size = ($opt{'d'} ? 128 : 0);
245
246 # Start of filesystem
247 $offset = $s*512 + $header_size;
248
249 # Start of partition table entry
250 $pstart = $header_size + 446 + 16*($pentry-1);
251
252 open(MCONFIG, "> ${cfgfile}") or die "$0: Cannot make mtools config\n";
253 print MCONFIG "drive z:\n";
254 print MCONFIG "file=\"${imglink}\"\n";
255 print MCONFIG "cylinders=${c}\n";
256 print MCONFIG "heads=${h}\n";
257 print MCONFIG "sectors=${s}\n";
258 print MCONFIG "offset=${offset}\n";
259 print MCONFIG "mformat_only\n";
260 close(MCONFIG);
261
262 # Output the filesystem offset to stdout if appropriate
263 if ( $opt{'o'} ) {
264     print $offset, "\n";
265 }
266
267 $ENV{'MTOOLSRC'} = $cfgfile;
268 if ( $opt{'F'} ) {
269     system('mformat', '-F', 'z:');
270 } else {
271     system('mformat', 'z:');
272 }
273
274 # Clean up in /tmp
275 unlink($cfgfile);
276 unlink($imglink);
277 rmdir($tmpdir);
278
279 # MTOOLS doesn't write the bsHiddenSecs field correctly
280 seek(OUTPUT, $offset + 0x1c, 0);
281 print OUTPUT pack("V", ($offset-$header_size)>>9);
282
283 # Set the partition type
284 if ( $opt{'F'} ) {
285     if ( $c > 1024 ) {
286         $fstype = 0x0c;         # FAT32 LBA
287     } else {
288         $fstype = 0x0b;
289     }
290 } else {
291     if ( $c > 1024 ) {
292         $fstype = 0x0e;         # FAT16 LBA
293     } elsif ( $psize > 65536 ) {
294         $fstype = 0x06;         # FAT16 > 32MB
295     } else {
296         $fstype = 0x04;         # FAT16 <= 32MB
297     }
298     seek(OUTPUT, $offset + 0x36, 0);
299     read(OUTPUT, $fsname, 8);
300
301     # FAT12: adjust partition type
302     if ( $fsname eq 'FAT12   ' ) {
303         $fstype = 0x01;         # FAT12
304     }
305 }
306 seek(OUTPUT, $pstart+4, 0);
307 print OUTPUT pack("C", $fstype);
308
309 flush OUTPUT;
310
311 # Just in case this is a block device, try to flush the partition table
312 if ( $is_linux ) {
313     ioctl(OUTPUT, $BLKRRPART, 0);
314 };
315
316 exit 0;
317 __END__