Debian Codegraph @

src/uk/me/parabola/imgfmt/sys/ImgHeader.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 26-Nov-2006
16 */
17 package uk.me.parabola.imgfmt.sys;
18
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.ByteOrder;
22 import java.util.Arrays;
23 import java.util.Calendar;
24 import java.util.Date;
25
26 import uk.me.parabola.imgfmt.FileSystemParam;
27 import uk.me.parabola.imgfmt.Utils;
28 import uk.me.parabola.imgfmt.app.labelenc.CharacterEncoder;
29 import uk.me.parabola.imgfmt.app.labelenc.CodeFunctions;
30 import uk.me.parabola.imgfmt.app.labelenc.EncodedText;
31 import uk.me.parabola.imgfmt.fs.ImgChannel;
32 import uk.me.parabola.log.Logger;
33
34 import static java.util.Arrays.asList;
35
36 /**
37 * The header at the very beginning of the .img filesystem. It has the
38 * same signature as a DOS partition table, although I don't know
39 * exactly how much the partition concepts are used.
40 *
41 * @author Steve Ratcliffe
42 */
43 class ImgHeader {
44 private static final Logger log = Logger.getLogger(ImgHeader.class);
45
46 // Offsets into the header.
47 private static final int OFF_XOR = 0x0;
48 private static final int OFF_VERSION = 0x8;
49 private static final int OFF_UPDATE_MONTH = 0xa;
50 private static final int OFF_UPDATE_YEAR = 0xb; // +1900 for val >= 0x63, +2000 for less
51 private static final int OFF_SUPP = 0xe; // Appears to be set for gmapsupp files
52 private static final int OFF_CHECKSUM = 0xf;
53 private static final int OFF_SIGNATURE = 0x10;
54 private static final int OFF_UNK_1 = 0x17;
55
56 // If this was a real boot sector these would be the meanings
57 private static final int OFF_SECTORS = 0x18;
58 private static final int OFF_HEADS = 0x1a;
59 private static final int OFF_CYLINDERS = 0x1c;
60
61 private static final int OFF_CREATION_DATE = 0x39;
62
63 // The block number where the directory starts.
64 private static final int OFF_DIRECTORY_START_BLOCK = 0x40;
65
66 private static final int OFF_MAP_FILE_INTENTIFIER = 0x41;
67 private static final int OFF_MAP_DESCRIPTION = 0x49; // 0x20 padded
68
69 private static final int OFF_HEADS2 = 0x5d;
70 private static final int OFF_SECTORS2 = 0x5f;
71
72 private static final int OFF_BLOCK_SIZE_EXPONENT1 = 0x61;
73 private static final int OFF_BLOCK_SIZE_EXPONENT2 = 0x62;
74 private static final int OFF_BLOCK_SIZE = 0x63;
75
76 // private static final int OFF_UKN_3 = 0x63;
77
78 private static final int OFF_MAP_NAME_CONT = 0x65;
79
80 // 'Partition table' offsets.
81 private static final int OFF_START_HEAD = 0x1bf;
82 private static final int OFF_START_SECTOR = 0x1c0;
83 private static final int OFF_START_CYLINDER = 0x1c1;
84 private static final int OFF_SYSTEM_TYPE = 0x1c2;
85 private static final int OFF_END_HEAD = 0x1c3;
86 private static final int OFF_END_SECTOR = 0x1c4;
87 private static final int OFF_END_CYLINDER = 0x1c5;
88 private static final int OFF_REL_SECTORS = 0x1c6;
89 private static final int OFF_NUMBER_OF_SECTORS = 0x1ca;
90 private static final int OFF_PARTITION_SIG = 0x1fe;
91
92 // Lengths of some of the fields
93 private static final int LEN_MAP_NAME_CONT = 30;
94 private static final int LEN_MAP_DESCRIPTION = 20;
95
96 private FileSystemParam fsParams;
97
98 private final ByteBuffer header = ByteBuffer.allocate(512);
99
100 private ImgChannel file;
101 private Date creationTime;
102
103 private int sectorsPerTrack;
104 private int headsPerCylinder;
105
106 // Signatures.
107 private static final byte[] FILE_ID = {
108 'G', 'A', 'R', 'M', 'I', 'N', '\0'};
109
110 private static final byte[] SIGNATURE = {
111 'D', 'S', 'K', 'I', 'M', 'G', '\0'};
112
113 private int numBlocks;
114
115 ImgHeader(ImgChannel chan) {
116 this.file = chan;
117 header.order(ByteOrder.LITTLE_ENDIAN);
118 }
119
120 /**
121 * Create a header from scratch.
122 * @param params File system parameters.
123 */
124 void createHeader(FileSystemParam params) {
125 this.fsParams = params;
126
127 header.put(OFF_XOR, (byte) 0);
128
129 // Set the block size. 2^(E1+E2) where E1 is always 9.
130 int exp = 9;
131
132 int bs = params.getBlockSize();
133 for (int i = 0; i < 32; i++) {
134 bs >>>= 1;
135 if (bs == 0) {
136 exp = i;
137 break;
138 }
139 }
140
141 if (exp < 9)
142 throw new IllegalArgumentException("block size too small");
143
144 header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9);
145 header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9));
146
147 header.position(OFF_SIGNATURE);
148 header.put(SIGNATURE);
149
150 header.position(OFF_MAP_FILE_INTENTIFIER);
151 header.put(FILE_ID);
152
153 header.put(OFF_UNK_1, (byte) 0x2);
154
155 // Actually this may not be the directory start block, I am guessing -
156 // always assume it is 2 anyway.
157 header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartEntry());
158
159 header.position(OFF_CREATION_DATE);
160 Utils.setCreationTime(header, creationTime);
161
162 setDirectoryStartEntry(params.getDirectoryStartEntry());
163
164 // Set the times.
165 Date date = new Date();
166 setCreationTime(date);
167 setUpdateTime(date);
168 setDescription(params.getMapDescription());
169 if (fsParams.isGmapsupp()) {
170 header.put(OFF_SUPP, (byte) (fsParams.isHideGmapsuppOnPC() ? 1: 0));
171 int prodVersion = fsParams.getProductVersion();
172 if (prodVersion >= 0) {
173 // value 100 means 1.00 */
174 int major = prodVersion / 100;
175 int minor = prodVersion % 100;
176 short version = (short) (major | (minor << 8));
177 header.putShort(OFF_VERSION, version);
178 }
179 }
180 // Checksum is not checked.
181 header.put(OFF_CHECKSUM, (byte) 0);
182 }
183
184 /**
185 * Write out the values associated with the partition sizes.
186 *
187 * @param blockSize Block size.
188 */
189 private void writeSizeValues(int blockSize) {
190 int endSector = (int) (((numBlocks+1L) * blockSize + 511) / 512);
191
192 // We have three maximum values for sectors, heads and cylinders. We attempt to find values
193 // for them that are larger than the
194 sectorsPerTrack = 32; // 6 bit value
195 headsPerCylinder = 128;
196 int cyls = 0x400;
197
198 // Try out various values of h, s and c until we find a combination that is large enough.
199 // I'm not entirely sure about the valid values, but it seems that only certain values work
200 // which is why we use values from a list.
201 // See: http://www.win.tue.nl/~aeb/partitions/partition_types-2.html for justification for the h list
202 out:
203 for (int h : asList(16, 32, 64, 128, 256)) {
204 for (int s : asList(4, 8, 16, 32)) {
205 for (int c : asList(0x20, 0x40, 0x80, 0x100, 0x200, 0x3ff)) {
206 log.info("shc=", s + "," + h + "," + c, "end=", endSector);
207 if (s * h * c > endSector) {
208 headsPerCylinder = h;
209 sectorsPerTrack = s;
210 cyls = c;
211 break out;
212 }
213 }
214 }
215 }
216
217 // This sectors, head, cylinders stuff appears to be used by mapsource
218 // and they have to be larger than the actual size of the map. It
219 // doesn't appear to have any effect on a garmin device or other software.
220 header.putShort(OFF_SECTORS, (short) sectorsPerTrack);
221 header.putShort(OFF_SECTORS2, (short) sectorsPerTrack);
222 header.putShort(OFF_HEADS, (short) headsPerCylinder);
223 header.putShort(OFF_HEADS2, (short) headsPerCylinder);
224 header.putShort(OFF_CYLINDERS, (short) cyls);
225
226 // Since there are only 2 bytes here it can overflow, if it
227 // does we replace it with 0xffff.
228 int blocks = (int) (endSector * 512L / blockSize);
229 char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks;
230 header.putChar(OFF_BLOCK_SIZE, shortBlocks);
231
232 header.put(OFF_PARTITION_SIG, (byte) 0x55);
233 header.put(OFF_PARTITION_SIG + 1, (byte) 0xaa);
234
235 // Partition starts at zero. This is 0,0,1 in CHS terms.
236 header.put(OFF_START_HEAD, (byte) 0);
237 header.put(OFF_START_SECTOR, (byte) 1);
238 header.put(OFF_START_CYLINDER, (byte) 0);
239
240 header.put(OFF_SYSTEM_TYPE, (byte) 0);
241
242 // Now calculate the CHS address of the last sector of the partition.
243 CHS chs = new CHS(endSector - 1);
244
245 header.put(OFF_END_HEAD, (byte) (chs.h));
246 header.put(OFF_END_SECTOR, (byte) ((chs.s) | ((chs.c >> 2) & 0xc0)));
247 header.put(OFF_END_CYLINDER, (byte) (chs.c & 0xff));
248
249 // Write the LBA block address of the beginning and end of the partition.
250 header.putInt(OFF_REL_SECTORS, 0);
251 header.putInt(OFF_NUMBER_OF_SECTORS, endSector);
252 log.info("number of blocks", endSector - 1);
253 }
254
255 void setHeader(ByteBuffer buf) {
256 buf.flip();
257 header.put(buf);
258
259 byte exp1 = header.get(OFF_BLOCK_SIZE_EXPONENT1);
260 byte exp2 = header.get(OFF_BLOCK_SIZE_EXPONENT2);
261 log.debug("header exponent", exp1, exp2);
262
263 fsParams = new FileSystemParam();
264 fsParams.setBlockSize(1 << (exp1 + exp2));
265 fsParams.setDirectoryStartEntry(header.get(OFF_DIRECTORY_START_BLOCK));
266
267 StringBuffer sb = new StringBuffer();
268 sb.append(Utils.bytesToString(buf, OFF_MAP_DESCRIPTION, LEN_MAP_DESCRIPTION));
269 sb.append(Utils.bytesToString(buf, OFF_MAP_NAME_CONT, LEN_MAP_NAME_CONT));
270
271 fsParams.setMapDescription(sb.toString().trim());
272
273 byte h = header.get(OFF_END_HEAD);
274 byte sc1 = header.get(OFF_END_SECTOR);
275 byte sc2 = header.get(OFF_END_CYLINDER);
276 CHS chs = new CHS();
277 chs.setFromPartition(h, sc1, sc2);
278 int lba = chs.toLba();
279 log.info("partition sectors", lba);
280 // ... more to do
281 }
282
283 void setFile(ImgChannel file) {
284 this.file = file;
285 }
286
287 FileSystemParam getParams() {
288 return fsParams;
289 }
290
291 /**
292 * Sync the header to disk.
293 * @throws IOException If an error occurs during writing.
294 */
295 public void sync() throws IOException {
296 setUpdateTime(new Date());
297
298 writeSizeValues(fsParams.getBlockSize());
299
300 header.rewind();
301 file.position(0);
302 file.write(header);
303 file.position(fsParams.getDirectoryStartEntry() * 512L);
304 }
305
306 /**
307 * Set the update time.
308 * @param date The date to use.
309 */
310 protected void setUpdateTime(Date date) {
311 Calendar cal = Calendar.getInstance();
312 cal.setTime(date);
313
314 header.put(OFF_UPDATE_YEAR, toYearCode(cal.get(Calendar.YEAR)));
315 header.put(OFF_UPDATE_MONTH, (byte) (cal.get(Calendar.MONTH)+1));
316 }
317
318 /**
319 * Set the description. It is spread across two areas in the header.
320 *
321 * It appears that the description has to be in ascii.
322 *
323 * @param desc The description.
324 */
325 protected void setDescription(String desc) {
326 // Force the description to be in ascii.
327 CodeFunctions funcs = CodeFunctions.createEncoderForLBL(0, 0);
328 CharacterEncoder encoder = funcs.getEncoder();
329 EncodedText enc = encoder.encodeText(desc);
330
331 byte[] ctext = enc.getCtext();
332 int len = enc.getLength() - 1;
333 if (len > 50)
334 throw new IllegalArgumentException("Description is too long (max 50)");
335
336 byte[] part1 = new byte[LEN_MAP_DESCRIPTION];
337 Arrays.fill(part1, (byte) ' ');
338
339 byte[] part2 = new byte[LEN_MAP_NAME_CONT];
340 Arrays.fill(part2, (byte) ' ');
341
342 if (ctext != null) {
343 if (len > LEN_MAP_DESCRIPTION) {
344 System.arraycopy(ctext, 0, part1, 0, LEN_MAP_DESCRIPTION);
345 System.arraycopy(ctext, LEN_MAP_DESCRIPTION, part2, 0, len - LEN_MAP_DESCRIPTION);
346 } else {
347 System.arraycopy(ctext, 0, part1, 0, len);
348 }
349 }
350
351 header.position(OFF_MAP_DESCRIPTION);
352 header.put(part1);
353
354 header.position(OFF_MAP_NAME_CONT);
355 header.put(part2);
356
357 header.put((byte) 0); // really?
358 }
359
360 /**
361 * Convert to the one byte code that is used for the year.
362 * If the year is in the 1900, then subtract 1900 and add the result to 0x63,
363 * else subtract 2000.
364 * Actually looks simpler, just subtract 1900..
365 * @param y The year in real-world format eg 2006.
366 * @return A one byte code representing the year.
367 */
368 private static byte toYearCode(int y) {
369 return (byte) (y - 1900);
370 }
371
372 protected void setDirectoryStartEntry(int directoryStartEntry) {
373 header.put(OFF_DIRECTORY_START_BLOCK, (byte) directoryStartEntry);
374 fsParams.setDirectoryStartEntry(directoryStartEntry);
375 }
376
377 protected void setCreationTime(Date date) {
378 this.creationTime = date;
379 }
380
381 public void setNumBlocks(int numBlocks) {
382 this.numBlocks = numBlocks;
383 }
384
385 public void hideGmapsuppOnPC (boolean b) {
386 header.put(OFF_SUPP, (byte) (fsParams.isGmapsupp() && b ? 1: 0));
387 }
388
389 /**
390 * Represent a block number in the chs format.
391 *
392 * Note that this class uses the headsPerCylinder and sectorsPerTrack values
393 * from the enclosing class.
394 *
395 * @see <a href="http://en.wikipedia.org/wiki/Logical_Block_Addressing">Logical block addressing</a>
396 */
397 private class CHS {
398 private int h;
399 private int s;
400 private int c;
401
402 private CHS() {
403 }
404
405 public CHS(int lba) {
406 toChs(lba);
407 }
408
409 /**
410 * Calculate the CHS values from the the given logical block address.
411 * @param lba Input logical block address.
412 */
413 private void toChs(int lba) {
414 h = (lba / sectorsPerTrack) % headsPerCylinder;
415 s = (lba % sectorsPerTrack) + 1;
416 c = lba / (sectorsPerTrack * headsPerCylinder);
417 }
418
419 /**
420 * Set from a partition table entry.
421 *
422 * The cylinder is 10 bits and is split between the top 2 bit of the sector
423 * value and its own byte.
424 *
425 * @param h The h value.
426 * @param sc1 The s value (6 bits) and top 2 bits of c.
427 * @param sc2 The bottom 8 bits of c.
428 */
429 public void setFromPartition(byte h, byte sc1, byte sc2) {
430 this.h = h;
431 this.s = (sc1 & 0x3f) + ((sc2 >> 2) & 0xc0);
432 this.c = sc2 & 0xff;
433 }
434
435 public int toLba() {
436 return (c * headsPerCylinder + h) * sectorsPerTrack + (s - 1);
437 }
438 }
439 }