3 # SlugImage : Manipulate NSLU2 firmware images
4 # Dwayne Fontenot (jacques)
8 # Copyright (c) 2004, 2006, Dwayne Fontenot & Rod Whitby
11 # Redistribution and use in source and binary forms, with or without
12 # modification, are permitted provided that the following conditions
15 # Redistributions of source code must retain the above copyright
16 # notice, this list of conditions and the following disclaimer.
17 # Redistributions in binary form must reproduce the above copyright
18 # notice, this list of conditions and the following disclaimer in the
19 # documentation and/or other materials provided with the distribution.
20 # Neither the name of the NSLU2-Linux Development Team nor the names
21 # of its contributors may be used to endorse or promote products
22 # derived from this software without specific prior written
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 # POSSIBILITY OF SUCH DAMAGE.
42 use Getopt
::Long
qw(:config no_ignore_case);
47 my($flash_start) = 0x50000000;
48 my($flash_len) = 0x00800000;
49 my($block_size) = 0x00020000;
50 my($kernel_offset) = 0x00060000;
51 my($kernel_size) = 0x00100000;
52 my($ramdisk_offset) = 0x00160000;
55 # The last 70 bytes of the SercommRedBootTrailer (i.e. excluding MAC
56 # address). Needed to create an image with an empty RedBoot partition
57 # since the Sercomm upgrade tool checks for this trailer.
58 # http://www.nslu2-linux.org/wiki/Info/SercommRedBootTrailer
59 my @sercomm_redboot_trailer = (0x4573, 0x4372, 0x4d6f, 0x006d, 0x0001,
60 0x0400, 0x3170, 0x5895, 0x0010, 0x0000, 0x0000, 0x0000, 0x0000,
61 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
62 0x0000, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0003, 0x2300,
63 0x0063, 0x0000, 0x7320, 0x7245, 0x6f43, 0x6d4d);
65 # There's a 16 byte Sercomm trailer at the end of the flash. It is used
66 # by RedBoot to detect a Sercomm flash layout and to configure the
67 # Sercomm upgrade system.
68 # http://www.nslu2-linux.org/wiki/Info/SercommFlashTrailer
69 my @sercomm_flash_trailer = (0x0100, 0x0000, 0x6323, 0xf790, 0x5265,
70 0x4f63, 0x4d6d, 0xb400);
72 # Take $data, and pad it out to $total_len bytes, appending 0xff's.
74 my($data,$total_len) = @_;
76 # 0xFF is used to pad, as it's the erase value of the flash.
77 my($pad_char) = pack("C",0xff);
78 my($pad_len) = $total_len - length($data);
80 # A request for negative padding is indicative of a logic error ...
81 if (length($data) > $total_len) {
82 die sprintf("padBytes error: data (%d) is longer than total_len (%d)", length($data), $total_len);
85 return $data . ($pad_char x
$pad_len);
88 # Return the next multiple of block_size larger than or equal to $data_len.
93 return (($data_len - 1) / $block_size) * $block_size + $block_size;
96 # Return the number of block_size blocks required to hold $data_len.
101 return (($data_len - 1) / $block_size) + 1;
104 # Pack the name, address, size and optional skip regions of a partition entry into binary form.
105 sub createPartitionEntry
{
106 my($name, $flash_base, $size, $skips) = @_;
109 my($zero_long) = 0x0000;
111 # Pack the partition entry according to the format that RedBoot (and the MTD partition parsing code) requires.
112 $entry = pack("a16N5x212N2",$name,$flash_base,$zero_long,$size,$zero_long,$zero_long,$zero_long,$zero_long);
114 # Optionally put a skip header into the padding area.
115 if (defined $skips) {
116 my $i = scalar(@
$skips);
117 foreach my $region (@
$skips) {
118 substr($entry, -8 - 12*$i, 12) =
119 pack("a4N2", "skip", $region->{'offset'}, $region->{'size'});
127 # Parse partition entry and return anon array ref [$name, $offset, $size, $skip] or return 0 on partition terminator.
128 sub parsePartitionEntry
{
129 my($partition_entry) = @_;
131 my($entry_len) = 0x100;
132 length($partition_entry) eq $entry_len or die "parsePartitionEntry: partition entry length is not $entry_len!\n";
134 # Unpack the partition table entry, saving those values in which we are interested.
135 my($name, $flash_base, $size, $dummy_long, $padding, $skips);
136 ($name, $flash_base, $dummy_long, $size, $dummy_long, $dummy_long, $padding, $dummy_long, $dummy_long) =
137 unpack("a16N5a212N2",$partition_entry);
139 # A partition entry starting with 0xFF terminates the table.
140 if (unpack("C", $name) eq 0xff) {
141 # %%% FIXME: This should only skip, not terminate. %%%
142 $debug and print "Found terminator for <FIS directory>\n";
146 # Remove trailing nulls from the partition name.
149 # Extract the skip regions out of the padding area.
150 $padding =~ s/^\000+//;
151 $padding =~ s/\000*skip(........)\000*/$1/g;
152 $padding =~ s/\000+$//;
154 # Store the skip regions in an array for later use.
155 while (length($padding)) {
157 ($region->{'offset'}, $region->{'size'}) =
158 unpack("N2", $padding);
159 $debug and printf("Found skip region at 0x%05X, size 0x%05X\n",
160 $region->{'offset'}, $region->{'size'});
161 push(@
$skips, $region);
162 $padding = substr($padding,8);
165 return [$name, $flash_base - $flash_start, $size, $skips];
168 # Return partition table from data is one exists, otherwise return 0.
169 sub findPartitionTable
{
172 unpack("a7", $data_buf) eq 'RedBoot' or return 0;
173 return substr($data_buf, 0, 0x1000)
176 # Parse partition table and return array of anonymous array references ([$name, $offset, $size, $skips], ...).
177 sub parsePartitionTable
{
178 my($partition_table) = @_;
180 my(@partitions, $fields_ref);
181 my($entry_len) = 0x100;
182 my($partition_count) = 0;
184 # Loop through the fixed size partition table entries, and store the entries in @partitions.
185 # %%% FIXME: This doesn't handle the case of a completely full partition table. %%%
186 while ($fields_ref = parsePartitionEntry
(substr($partition_table, $partition_count * $entry_len, $entry_len))) {
187 $debug and printf("Found <%s> at 0x%08X (%s)%s\n", $fields_ref->[0], $fields_ref->[1],
188 ($fields_ref->[2] >= $block_size ?
189 sprintf("%d blocks", numBlocks
($fields_ref->[2])) :
190 sprintf("0x%05X bytes", $fields_ref->[2])),
191 (defined $fields_ref->[3] ?
194 map { sprintf("0x%05X/0x%05X", $_->{'offset'},$_->{'size'}) }
195 @
{$fields_ref->[3]})) :
197 $partitions[$partition_count++] = $fields_ref;
202 # Create an empty jffs2 block.
204 return padBytes
(pack("N3", 0x19852003, 0x0000000c, 0xf060dc98), $block_size);
207 # Write out $data to $filename,
209 my($data, $filename) = @_;
211 open FILE
,">$filename" or die "Can't open file \"$filename\": $!\n";
213 if (defined($data)) { print FILE
$data;}
215 close FILE
or die "Can't close file \"$filename\": $!\n";
218 # Not used at the moment.
220 my($product_id) = 0x0001;
221 my($protocol_id) = 0x0000;
222 my($firmware_version) = 0x2325;
223 my($unknown1) = 0x90f7;
224 my($magic_number) = 'eRcOmM';
225 my($unknown2) = 0x00b9;
227 return pack("n4a6n",$product_id,$protocol_id,$firmware_version,$unknown1,$magic_number,$unknown2);
230 # Print the contents of the Sercomm RedBoot trailer.
231 sub printRedbootTrailer
{
232 my($redboot_data) = @_;
234 my($correct_redboot_len) = 0x40000;
235 my($redboot_data_len) = length($redboot_data);
237 if ($redboot_data_len != $correct_redboot_len) {
238 printf("Redboot length (0x%08X) is not 0x%08X\n", $redboot_data_len, $correct_redboot_len);
242 # The trailer is the last 80 bytes of the redboot partition.
243 my($redboot_trailer) = substr($redboot_data, -80);
245 writeOut
($redboot_trailer, 'RedbootTrailer');
247 my($mac_addr0, $mac_addr1, $mac_addr2, $unknown, $prefix, $ver_ctrl, $down_ctrl, $hid, $hver, $prodid, $prodidmask,
248 $protid, $protidmask, $funcid, $funcidmask, $fver, $cseg, $csize, $postfix) =
249 unpack("n3Na7n2a32n10a7",$redboot_trailer);
251 printf("MAC address is %04X%04X%04X\n", $mac_addr0, $mac_addr1, $mac_addr2);
252 printf("unknown: %08X\n", $unknown);
253 printf("%s:%04X:%04X:%s\n", $prefix, $ver_ctrl, $down_ctrl, $postfix);
254 printf("VerControl: %04X\nDownControl: %04X\n", $ver_ctrl, $down_ctrl);
255 printf("hid: %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X %04X\n", unpack("n16", $hid));
256 printf("Hver: %04X\nProdID: %04X\nProtID: %04X\nFuncID: %04X\nFver: %04X\nCseg: %04X\nCsize: %04X\n",
257 $hver, $prodid, $protid, $funcid, $fver, $cseg, $csize);
260 # remove the optional Loader partition
261 sub removeOptionalLoader
{
262 my($partitions_ref) = @_;
267 if (not defined $index) {
268 if ($_->{'name'} eq "Loader") {
275 defined $index or die "Cannot find the Loader partition\n";
277 splice(@
$partitions_ref, $index, 1);
279 # Set fixed offsets and sizes for Kernel and Ramdisk
281 if ($_->{'name'} eq 'Kernel') {
282 $_->{'offset'} = $kernel_offset;
283 $_->{'size'} = $kernel_size;
284 $_->{'variable'} = 0;
286 if ($_->{'name'} eq 'Ramdisk') {
287 $_->{'offset'} = $ramdisk_offset;
295 # populate @partitions based on the firmware's partition table
296 sub spliceFirmwarePartitions
{
297 my($firmware_buf, $partitions_ref) = @_;
299 # we know that partition table, if it exists, begins at start of 'FIS directory' and has max length 0x1000
300 my($partition_table);
302 $_->{'name'} eq 'FIS directory' and
303 $partition_table = findPartitionTable
(substr($firmware_buf, $_->{'offset'}, $_->{'size'}));
306 # return 0 here if no partition table in FIS directory
307 return if not $partition_table;
309 my @new_partitions = parsePartitionTable
($partition_table);
311 # Remove the optional second stage bootloader if it is not found in the FIS directory.
312 if (not grep { $_->[0] eq 'Loader' } @new_partitions) {
313 removeOptionalLoader
($partitions_ref);
316 my($partition_count) = 0;
320 # Skip pseudo partitions.
321 while (($partition_count < scalar(@
$partitions_ref)) and
322 $partitions_ref->[$partition_count]->{'pseudo'}) {
323 $debug and printf("Skipped <%s> (pseudo partition)\n", $partitions_ref->[$partition_count]->{'name'});
327 # If we are in a variable area, and we haven't reached the end of it,
328 # then splice in another partition for use by the later code.
329 if ($splice and ($partitions_ref->[$partition_count]->{'name'} ne $_->[0])) {
330 $debug and printf("Splicing new partition <%s> before <%s>\n",
331 $_->[0], $partitions_ref->[$partition_count]->{'name'});
332 splice(@
{$partitions_ref}, $partition_count, 0, ({'name' => "",'variable'=>1,'header'=>0}));
335 my $partition = $partitions_ref->[$partition_count];
337 # Variable partitions can be overridden by the real FIS directory
338 if ($partition->{'variable'}) {
340 # Only override the filename if the partition name is not set or doesn't match
341 if ($partition->{'name'} ne $_->[0]) {
343 if (length($partition->{'name'})) {
344 $debug and printf("Overwriting <%s> with <%s>\n",
345 $partitions_ref->[$partition_count]->{'name'}, $_->[0]);
348 $partition->{'name'} = $_->[0];
349 $partition->{'file'} = $_->[0];
352 # Set the offset, size and skips based on the real partition table
353 $partition->{'offset'} = $_->[1];
354 $partition->{'size'} = $_->[2];
355 $partition->{'skips'} = $_->[3];
357 $debug and printf("Locating <%s> at 0x%08X (%s)\n",
358 $partition->{'name'}, $partition->{'offset'},
359 ($partition->{'size'} >= $block_size ?
360 sprintf("%d blocks", numBlocks
($partition->{'size'})) :
361 sprintf("0x%05X bytes", $partition->{'size'})));
366 # Fixed partitions cannot be overridden
368 ($partition->{'name'} eq $_->[0]) or
369 die "Unexpected partition <",$_->[0],"> (expecting <",$partition->{'name'},">)\n";
371 $debug and printf("Locating <%s> at 0x%08X (%s)\n",
372 $partition->{'name'}, $partition->{'offset'},
373 ($partition->{'size'} >= $block_size ?
374 sprintf("%d blocks", numBlocks
($partition->{'size'})) :
375 sprintf("0x%05X bytes", $partition->{'size'})));
387 # Read in an 8MB firmware file, and store the data into @partitions.
388 # Note that the data is only stored in a partition if 'offset' and 'size' are defined,
389 # and it does not already have data stored in it.
391 my($filename, $partitions_ref) = @_;
394 my($total_length) = 0x800000;
396 open FILE
,$filename or die "Can't find firmware image \"$filename\": $!\n";
397 read FILE
,$firmware_buf,$total_length or die "Can't read $total_length bytes from \"$filename\": $!\n";
398 close FILE
or die "Can't close \"$filename\": $!\n";
400 $debug and printf("Read 0x%08X bytes from \"%s\"\n", length($firmware_buf), $filename);
402 spliceFirmwarePartitions
($firmware_buf, $partitions_ref);
404 # Read the parts of the firmware file into the partitions table.
406 if (defined $_->{'offset'} and defined $_->{'size'}) {
408 if (defined $_->{'data'}) {
409 $debug and printf("Not overwriting data in <%s>\n", $_->{'name'});
413 # Slurp up the data, based on whether a header is present or not
414 if ($_->{'header'}) {
416 # Read the length, and grab the data based on the length.
417 my($data_len) = unpack("N", substr($firmware_buf, $_->{'offset'}));
419 # A length of 0xFFFFFFFF means that the area is not initialised
420 if ($data_len != 0xFFFFFFFF) {
421 $debug and printf("Found header size of 0x%08X bytes for <%s>\n", $data_len, $_->{'name'});
422 $_->{'data'} = substr($firmware_buf, $_->{'offset'} + $_->{'header'}, $data_len);
427 # Grab the whole partition, using the maximum size.
428 $_->{'data'} = substr($firmware_buf, $_->{'offset'}, $_->{'size'});
431 # If skip regions are defined, remove them from the data.
432 if (defined $_->{'skips'}) {
434 foreach my $region (@
{$_->{'skips'}}) {
435 if (($region->{'offset'} > 0) or
436 not ($_->{'header'} > 0)) {
437 $debug and printf("Removing 0x%05X bytes from offset 0x%05X\n",
438 $region->{'size'}, $region->{'offset'});
439 $region->{'data'} = substr($_->{'data'}, $region->{'offset'} - $removed, $region->{'size'}, '');
441 $removed += $region->{'size'};
445 $quiet or defined $_->{'data'} and printf("Read %s into <%s>\n",
446 (length($_->{'data'}) >= $block_size ?
447 sprintf("%d blocks", numBlocks
(length($_->{'data'}))) :
448 sprintf("0x%05X bytes", length($_->{'data'}))), $_->{'name'});
454 # Write the partition data stored in memory out into the files associated with each.
455 sub writeOutFirmwareParts
{
456 my(@partitions) = @_;
458 # Write out the parts of the firmware file.
461 # We can only write if 'data' and 'file' are defined.
462 if (defined $_->{'file'} and defined $_->{'data'} and length($_->{'data'})) {
463 writeOut
($_->{'data'}, $_->{'file'});
464 $quiet or printf("Wrote 0x%08X bytes from <%s> into \"%s\"\n",
465 length($_->{'data'}), $_->{'name'}, $_->{'file'});
468 $debug and printf("Skipping <%s> (%s)\n", $_->{'name'},
469 (not defined $_->{'file'}) ?
470 "no filename specified" :
479 # Read in the partition data from the files associated with each and store in memory.
480 sub readInFirmwareParts
{
481 my(@partitions) = (@_);
483 undef $/; # we want to slurp
487 my $file = $_->{'file'};
489 open FILE
,$file or die "Can't find firmware part \"$file\": $!\n";
492 $_->{'data'} = <FILE
>;
495 close FILE
or die "Can't close file \"$file\": $!\n";
497 # Optionally byteswap the data
498 if ($_->{'byteswap'}) {
499 # Byte swap the data (which has to be padded to a multiple of 4 bytes).
500 $_->{'data'} = pack("N*", unpack("V*", $_->{'data'}.pack("CCC", 0)));
503 # Keep track of the actual size.
506 if ($_->{'header'}) {
507 if ($_->{'pseudo'}) {
508 $size = $_->{'header'} + length($_->{'data'});
511 $size = paddedSize
($_->{'header'} + length($_->{'data'}));
514 elsif (not $_->{'pseudo'}) {
515 $size = paddedSize
(length($_->{'data'}));
518 $size = length($_->{'data'});
521 # Check to make sure the file contents are not too large.
522 if (defined $_->{'size'} and ($size > $_->{'size'})) {
523 die sprintf("Ran out of flash space in <%s> - %s too large.\n", $_->{'name'},
524 sprintf("0x%05X bytes", ($size - $_->{'size'})));
527 # If the partition does not have a fixed size, the calculate the size.
528 if (not defined $_->{'size'}) {
529 $_->{'size'} = $size;
532 # Keep the user appraised ...
533 $quiet or printf("Read 0x%08X bytes from \"%s\" into <%s> (%s / %s)%s\n",
534 length($_->{'data'}), $_->{'file'}, $_->{'name'},
535 ($size >= $block_size ?
536 sprintf("%d blocks", numBlocks
($size)) :
537 sprintf("0x%05X bytes", $size)),
538 ($_->{'size'} >= $block_size ?
539 sprintf("%d blocks", numBlocks
($_->{'size'})) :
540 sprintf("0x%05X bytes", $_->{'size'})),
541 ($_->{'byteswap'} ?
" (byte-swapped)" : ""));
549 # layoutPartitions : this function must be ugly - it needs to verify RedBoot, SysConf, Kernel, Ramdisk, and
550 # FIS directory partitions exist, are in the correct order, and do not have more data than can fit in
551 # their lengths (fixed for all but Ramdisk, which has a minimum length of one block).
552 # If Rootdisk and/or Userdisk exist, it must also verify that their block padded lengths are not
553 # too great for the available space.
554 # input : an array of hashes, some of which are populated with data
555 # output: same reference with start and size (partition not data) also populated. this populated structure
556 # can then be passed to buildPartitionTable() to generate the actual partition table data
557 sub layoutPartitions
{
558 my(@partitions) = @_;
560 # Find the last variable size partition, and save a pointer to it for later use
562 my $directory_offset;
563 my $curdisk = $partitions[0];
565 if (not defined $lastdisk) {
566 if ($_->{'name'} eq "FIS directory") {
567 $lastdisk = $curdisk;
568 $directory_offset = $_->{'offset'};
576 $lastdisk or die "Couldn't find the last variable size partition\n";
578 $debug and printf("Last variable size partition is <%s>\n", $lastdisk->{'name'});
581 # here we go through the $partitions array ref and fill in all the values
584 # This points to where the next partition should be placed.
585 my $pointer = $flash_start;
589 $debug and printf("Pointer is 0x%08X\n", $pointer);
591 # If this is the last variable size partition, then fill the rest of the space.
592 if ($_->{'name'} eq $lastdisk->{'name'}) {
593 $_->{'size'} = paddedSize
($directory_offset + $flash_start - $pointer);
594 $debug and printf("Padding last variable partition <%s> to 0x%08X bytes\n", $_->{'name'}, $_->{'size'});
597 # Handle requests for partition creation first.
598 if (defined $_->{'size'} and not defined $_->{'data'} and ($_->{'name'} ne "FIS directory")) {
600 # A zero size is a request to fill all available space.
601 if ($_->{'size'} == 0) {
602 # Grab the start of the FIS directory, and use all the space up to there.
603 $_->{'size'} = paddedSize
($directory_offset + $flash_start - $pointer);
605 # Create an empty partition of the requested size.
606 $_->{'data'} = padBytes
("", $_->{'size'});
608 $debug and printf("Creating empty partition <%s> of 0x%08X bytes\n", $_->{'name'}, $_->{'size'});
611 if (not defined $_->{'offset'}) {
612 # Check to make sure that the requested size is not too large.
613 if (($pointer + $_->{'size'}) > ($flash_start + $directory_offset)) {
614 die "Ran out of flash space in <", $_->{'name'}, ">\n";
618 # Check to make sure that the requested size is not too large.
619 if (($_->{'offset'} + $_->{'size'}) > ($flash_start + $directory_offset)) {
620 die "Ran out of flash space in <", $_->{'name'}, ">\n";
625 # Then handle known partitions, and allocate them.
626 if (defined $_->{'size'}) {
628 # Determine the start and offset of the current partition.
629 if (defined $_->{'offset'}) {
630 $_->{'start'} = $flash_start + $_->{'offset'};
633 # If offset is not defined, then calculate it.
635 $_->{'start'} = $pointer;
636 $_->{'offset'} = $_->{'start'} - $flash_start;
639 my $size = defined $_->{'data'} ?
length($_->{'data'}) : 0;
641 # Add skip regions for the partitions with headers.
642 if ($_->{'header'} > 0) {
643 # Define the skip region for the initial Sercomm header.
644 push(@
{$_->{'skips'}},
645 { 'offset' => 0, 'size' => $_->{'header'}, 'data' => undef });
646 # Allow for the Sercomm header to be prepended to the data.
647 $size += $_->{'header'};
650 # Determine if the partition requires a Sercomm skip region.
651 if (($_->{'offset'} < $ramdisk_offset) and
652 (($_->{'offset'} + $size) > $ramdisk_offset)) {
653 # Define the skip region for the inline Sercomm header.
654 push(@
{$_->{'skips'}},
655 { 'offset' => ($ramdisk_offset - $_->{'offset'}), 'size' => 16,
656 'data' => pack("N4", $block_size) });
657 # Allow for the Sercomm header to be inserted in the data.
661 # Extend to another block if required.
662 if ($size > $_->{'size'}) {
663 $_->{'size'} = $size;
664 printf("Extending partition <%s> to 0x%08X bytes\n", $_->{'name'}, $_->{'size'});
667 # Keep the user appraised ...
668 $debug and printf("Allocated <%s> from 0x%08X to 0x%08X (%s / %s)\n",
669 $_->{'name'}, $_->{'start'}, $_->{'start'} + $_->{'size'},
670 ($size >= $block_size ?
671 sprintf("%d blocks", numBlocks
($size)) :
672 sprintf("0x%05X bytes", $size)),
673 ($_->{'size'} >= $block_size ?
674 sprintf("%d blocks", numBlocks
($_->{'size'})) :
675 sprintf("0x%05X bytes", $_->{'size'})));
677 # Check to make sure we have not run out of room.
678 if (($_->{'start'} + $_->{'size'}) > ($flash_start + $flash_len)) {
679 die "Ran out of flash space in <", $_->{'name'}, ">\n";
682 $debug and printf("Moving pointer from 0x%08X to 0x%08X (0x%08X + 0x%08X)\n",
683 $pointer, paddedSize
($_->{'start'} + $_->{'size'}),
684 $_->{'start'}, $_->{'size'});
686 # Move the pointer up, in preparation for the next partition.
687 $pointer = paddedSize
($_->{'start'} + $_->{'size'});
696 sub buildPartitionTable
{
697 my(@partitions) = @_;
699 my($flash_start) = 0x50000000;
700 my($partition_data) = '';
704 # Collate the partition data for all known partitions.
705 if (not $_->{'pseudo'} and defined $_->{'offset'} and defined $_->{'size'}) {
707 # Pack and append the binary table entry for this partition.
708 $partition_data .= createPartitionEntry
($_->{'name'}, $_->{'offset'} + $flash_start,
709 $_->{'size'}, $_->{'skips'});
711 # If this is the FIS directory, then write the partition table data into it.
712 if ($_->{'name'} eq "FIS directory") {
713 # Explicitly terminate the partition data.
714 $partition_data .= pack("C",0xff) x
0x100;
715 $_->{'data'} = padBytes
($partition_data, $_->{'size'});
718 my $size = length($_->{'data'});
720 # Keep the user appraised ...
721 $debug and printf("Table entry <%s> from 0x%08X to 0x%08X (%s / %s)%s\n",
722 $_->{'name'}, $_->{'start'}, $_->{'start'} + $_->{'size'},
723 ($size >= $block_size ?
724 sprintf("%d blocks", numBlocks
($size)) :
725 sprintf("0x%05X bytes", $size)),
726 ($_->{'size'} >= $block_size ?
727 sprintf("%d blocks", numBlocks
($_->{'size'})) :
728 sprintf("0x%05X bytes", $_->{'size'})),
729 (defined $_->{'skips'} ?
730 sprintf("\nTable entry <%s> skip %s", $_->{'name'},
732 map { sprintf("0x%08X to 0x%08X", $_->{'offset'},
733 $_->{'offset'} + $_->{'size'} - 1) }
739 $debug and print "No table entry required for <", $_->{'name'}, ">\n";
747 sub writeOutFirmware
{
748 my($filename, @partitions) = @_;
750 # Clear the image to start.
755 # We can only write a partition if it has an offset, a size, and some data to write.
756 if (defined $_->{'offset'} and defined $_->{'size'} and defined $_->{'data'}) {
758 # Keep track of the end of the image.
759 my $end_point = length($image_buf);
761 # If the next partition is well past the end of the current image, then pad it.
762 if ($_->{'offset'} > $end_point) {
763 $image_buf .= padBytes
("", $_->{'offset'} - $end_point);
764 $quiet or printf("Padded %s before <%s> in \"%s\"\n",
765 ((length($image_buf) - $end_point) >= $block_size ?
766 sprintf("%d blocks", numBlocks
(length($image_buf) - $end_point)) :
767 sprintf("0x%05X bytes", length($image_buf) - $end_point)),
768 $_->{'name'}, $filename);
771 # If the next parition is before the end of the current image, then rewind.
772 elsif ($_->{'offset'} < $end_point) {
773 $debug and printf("Rewound %s before <%s> in \"%s\"\n",
774 (($end_point - $_->{'offset'}) >= $block_size ?
775 sprintf("%d blocks", numBlocks
($end_point - $_->{'offset'})) :
776 sprintf("0x%05X bytes", $end_point - $_->{'offset'})),
777 $_->{'name'}, $filename);
778 # if (($end_point - $_->{'offset'}) >= $block_size) {
779 # die "Allocation error: rewound a full block or more ...\n";
783 # If skip regions are defined, add them to the data.
784 if (defined $_->{'skips'}) {
786 foreach my $region (@
{$_->{'skips'}}) {
787 if (($region->{'offset'} > 0) or
788 not ($_->{'header'} > 0)) {
789 $debug and printf("Inserted 0x%05X bytes (at offset 0x%05X) into <%s>\n",
790 $region->{'size'}, $region->{'offset'}, $_->{'name'});
792 $region->{'offset'} + $added - $_->{'header'},
793 0, $region->{'data'});
794 $added += $region->{'size'};
799 # Splice the data into the image at the appropriate place, padding as required.
800 substr($image_buf, $_->{'offset'}, $_->{'size'},
802 padBytes
(pack("N4",length($_->{'data'})).$_->{'data'}, $_->{'size'}) :
803 padBytes
($_->{'data'}, $_->{'size'}));
805 # Keep the user appraised ...
806 $quiet or printf("Wrote %s (0x%08X to 0x%08X) from <%s> into \"%s\"\n",
807 ($_->{'size'} >= $block_size ?
808 sprintf("%2d blocks", numBlocks
($_->{'size'})) :
809 sprintf("0x%05X bytes", $_->{'size'})),
810 $_->{'offset'}, $_->{'offset'}+$_->{'size'}, $_->{'name'}, $filename);
813 # If we are not able to write a partition, then give debug information about why.
815 $debug and printf("Skipping <%s> (%s)\n", $_->{'name'},
816 (not defined $_->{'offset'}) ?
"no offset defined" :
817 ((not defined $_->{'size'}) ?
"no size defined" :
818 "no data available"));
823 # Write the image to the specified file.
824 writeOut
($image_buf, $filename);
829 # checkPartitionTable: sanity check partition table - for testing but might evolve into setting @partitions
830 # so that we can write out jffs2 partitions from a read image
831 # currently not nearly paranoid enough
832 sub checkPartitionTable
{
838 my($name, $flash_base, $size, $done, $dummy_long, $padding);
840 $entry = substr($data, $pointer, 0x100);
842 ($name,$flash_base,$dummy_long,$size,$dummy_long,$dummy_long,$padding,$dummy_long,$dummy_long) = unpack("a16N5x212N2",$entry);
844 $debug and printf("pointer: %d\tname: %s%sflash_base: 0x%08X\tsize: 0x%08X\n",
845 $pointer, $name, (" " x
(16 - length($name))), $flash_base, $size);
847 $debug and printf("terminator: 0x%08X\n", unpack("C", substr($data, $pointer, 1)));
848 if (unpack("C", substr($data, $pointer, 1)) eq 0xff) {
854 sub printPartitions
{
855 my(@partitions) = @_;
857 my($offset, $size, $skips);
859 # defined $_->{'size'} ? $size = $_->{'size'} : $size = undef;
861 if (defined $_->{'size'}) {
862 $size = $_->{'size'};
867 if (defined $_->{'offset'}) {
868 $offset = $_->{'offset'};
873 if (defined $_->{'skips'}) {
874 $skips = $_->{'skips'};
879 printf("%s%s", $_->{'name'}, (" " x
(16 - length($_->{'name'}))));
880 if (defined $offset) { printf("0x%08X\t", $offset); } else { printf("(undefined)\t"); };
881 if (defined $size) { printf("0x%08X", $size); } else { printf("(undefined)"); };
882 if (defined $skips) {
885 map { sprintf("0x%05X/0x%05X", $_->{'offset'}, $_->{'size'}); }
892 sub defaultPartitions
{
894 return ({'name'=>'RedBoot', 'file'=>'RedBoot',
895 'offset'=>0x00000000, 'size'=>0x00040000,
896 'variable'=>0, 'header'=>0, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
897 {'name'=>'EthAddr', 'file'=>undef,
898 'offset'=>0x0003ffb0, 'size'=>0x00000006,
899 'variable'=>0, 'header'=>0, 'pseudo'=>1, 'data'=>undef, 'byteswap'=>0},
900 {'name'=>'SysConf', 'file'=>'SysConf',
901 'offset'=>0x00040000, 'size'=>0x00020000,
902 'variable'=>0, 'header'=>0, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
903 {'name'=>'Loader', 'file'=>'apex.bin',
904 'offset'=>undef, 'size'=>undef,
905 'variable'=>1, 'header'=>16, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
906 {'name'=>'Kernel', 'file'=>'vmlinuz',
907 'offset'=>undef, 'size'=>undef,
908 'variable'=>1, 'header'=>16, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
909 {'name'=>'Ramdisk', 'file'=>'ramdisk.gz',
910 'offset'=>undef, 'size'=>undef,
911 'variable'=>1, 'header'=>16, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
912 {'name'=>'FIS directory', 'file'=>undef,
913 'offset'=>0x007e0000, 'size'=>0x00020000,
914 'variable'=>0, 'header'=>0, 'pseudo'=>0, 'data'=>undef, 'byteswap'=>0},
915 {'name'=>'Loader config', 'file'=>undef,
916 'offset'=>0x007f8000, 'size'=>0x00004000,
917 'variable'=>0, 'header'=>0, 'pseudo'=>1, 'data'=>undef, 'byteswap'=>0},
918 {'name'=>'Microcode', 'file'=>'NPE-B',
919 'offset'=>0x007fc000, 'size'=>0x00003ff0,
920 'variable'=>0, 'header'=>16, 'pseudo'=>1, 'data'=>undef, 'byteswap'=>0},
921 {'name'=>'Trailer', 'file'=>'Trailer',
922 'offset'=>0x007ffff0, 'size'=>0x00000010,
923 'variable'=>0, 'header'=>0, 'pseudo'=>1, 'data'=>undef, 'byteswap'=>0});
926 # Main routine starts here ...
928 my($unpack, $pack, $little, $input, $output, $redboot);
929 my($kernel, $sysconf, $ramdisk, $fisdir);
930 my($microcode, $trailer, $ethaddr, $loader);
933 # Remove temporary files
934 for my $file (@cleanup) {
939 if (!GetOptions
("d|debug" => \
$debug,
940 "q|quiet" => \
$quiet,
941 "u|unpack" => \
$unpack,
943 "l|little" => \
$little,
944 "i|input=s" => \
$input,
945 "o|output=s" => \
$output,
946 "b|redboot=s" => \
$redboot,
947 "k|kernel=s" => \
$kernel,
948 "s|sysconf=s" => \
$sysconf,
949 "r|ramdisk=s" => \
$ramdisk,
950 "f|fisdir=s" => \
$fisdir,
951 "m|microcode=s" => \
$microcode,
952 "t|trailer=s" => \
$trailer,
953 "e|ethaddr=s" => \
$ethaddr,
954 "L|loader=s" => \
$loader,
955 ) or (not defined $pack and not defined $unpack)) {
956 print "Usage: slugimage <options>\n";
958 print " [-d|--debug] Turn on debugging output\n";
959 print " [-q|--quiet] Turn off status messages\n";
960 print " [-u|--unpack] Unpack a firmware image\n";
961 print " [-p|--pack] Pack a firmware image\n";
962 print " [-l|--little] Convert Kernel and Ramdisk to little-endian\n";
963 print " [-i|--input] <file> Input firmware image filename\n";
964 print " [-o|--output] <file> Output firmware image filename\n";
965 print " [-b|--redboot] <file> Input/Output RedBoot filename\n";
966 print " [-s|--sysconf] <file> Input/Output SysConf filename\n";
967 print " [-L|--loader] <file> Second stage boot loader filename\n";
968 print " [-k|--kernel] <file> Input/Ouptut Kernel filename\n";
969 print " [-r|--ramdisk] <file> Input/Output Ramdisk filename(s)\n";
970 print " [-f|--fisdir] <file> Input/Output FIS directory filename\n";
971 print " [-m|--microcode] <file> Input/Output Microcode filename\n";
972 print " [-t|--trailer] <file> Input/Output Trailer filename\n";
973 print " [-e|--ethaddr] <AABBCCDDEEFF> Set the Ethernet address\n";
975 # %%% TODO %%% Document --ramdisk syntax
980 my(@partitions) = defaultPartitions
();
983 die "Output filename must be specified\n" unless defined $output;
985 # If we're creating an image and no RedBoot, SysConf partition is
986 # explicitly specified, simply write an empty one as the upgrade tools
987 # don't touch RedBoot and SysConf anyway. If no Trailer is specified,
989 if (not defined $redboot and not -e
"RedBoot") {
991 open TMP
, ">$redboot" or die "Cannot open file $redboot: $!";
992 push @cleanup, $redboot;
993 # The RedBoot partition is 256 * 1024 = 262144; the trailer we add
995 print TMP
"\0"x
(262144-70);
996 # Upgrade tools check for an appropriate Sercomm trailer.
997 for my $i (@sercomm_redboot_trailer) {
998 print TMP
pack "S", $i;
1002 if (not defined $sysconf and not -e
"SysConf") {
1003 $sysconf = tmpnam
();
1004 open TMP
, ">$sysconf" or die "Cannot open file $sysconf: $!";
1005 push @cleanup, $sysconf;
1006 # The SysConf partition is 128 * 1024 = 131072
1007 print TMP
"\0"x131072
;
1010 if (not defined $trailer and not -e
"Trailer") {
1011 $trailer = tmpnam
();
1012 open TMP
, ">$trailer" or die "Cannot open file $trailer: $!";
1013 push @cleanup, $trailer;
1014 for my $i (@sercomm_flash_trailer) {
1015 print TMP
pack "S", $i;
1020 # If the microcode was not specified, then don't complain that it's missing.
1021 if (not defined $microcode and not -e
"NPE-B") {
1022 map { ($_->{'name'} eq 'Microcode') && ($_->{'file'} = undef); } @partitions;
1026 # Go through the partition options, and set the names and files in @partitions
1027 if (defined $redboot) { map { ($_->{'name'} eq 'RedBoot') && ($_->{'file'} = $redboot); } @partitions; }
1028 if (defined $sysconf) { map { ($_->{'name'} eq 'SysConf') && ($_->{'file'} = $sysconf); } @partitions; }
1029 if (defined $loader) { map { ($_->{'name'} eq 'Loader') && ($_->{'file'} = $loader); } @partitions; }
1030 if (defined $kernel) { map { ($_->{'name'} eq 'Kernel') && ($_->{'file'} = $kernel); } @partitions; }
1031 if (defined $fisdir) { map { ($_->{'name'} eq 'FIS directory') && ($_->{'file'} = $fisdir); } @partitions; }
1032 if (defined $microcode) { map { ($_->{'name'} eq 'Microcode') && ($_->{'file'} = $microcode); } @partitions; }
1033 if (defined $trailer) { map { ($_->{'name'} eq 'Trailer') && ($_->{'file'} = $trailer); } @partitions; }
1035 if (defined $little) {
1037 if (($_->{'name'} eq 'Loader') or
1038 ($_->{'name'} eq 'Kernel') or
1039 ($_->{'name'} eq 'Ramdisk')) {
1040 $_->{'byteswap'} = 1;
1045 if (defined $ethaddr) {
1047 if ($_->{'name'} eq 'EthAddr') {
1049 if (($ethaddr !~ m/^[0-9A-Fa-f]+$/) or (length($ethaddr) != 12)) {
1050 die "Invalid ethernet address specification: '".$ethaddr."'\n";
1052 $_->{'data'} = pack("H12", $ethaddr);
1057 if (defined $ramdisk) {
1059 # A single filename is used for the ramdisk filename
1060 if ($ramdisk !~ m/[:,]/) {
1061 map { ($_->{'name'} eq 'Ramdisk') && ($_->{'file'} = $ramdisk); } @partitions;
1064 # otherwise, it's a list of name:file mappings
1066 my @mappings = split(',', $ramdisk);
1068 # Find the index of the Ramdisk entry
1072 if (not defined $index) {
1073 if ($_->{'name'} eq "Ramdisk") {
1080 defined $index or die "Cannot find the Ramdisk partition\n";
1082 # Replace the Ramdisk entry with the new mappings
1083 splice(@partitions, $index, 1, map {
1085 # Preserve the information from the ramdisk entry
1086 my %entry = %{$partitions[$index]};
1089 ($_ =~ m/^([^:]+):([^:]+)(:([^:]+))?$/) or die "Invalid syntax in --ramdisk\n";
1090 $entry{'name'} = $1; $entry{'file'} = $2; my $size = $4;
1092 # If the mapping is not for the ramdisk, then undefine its attributes
1093 if ($entry{'name'} ne 'Ramdisk') {
1094 $entry{'offset'} = undef;
1095 $entry{'size'} = undef;
1096 $entry{'variable'} = 1;
1097 $entry{'header'} = 0;
1098 $entry{'pseudo'} = 0;
1099 $entry{'data'} = undef;
1100 $entry{'byteswap'} = 0;
1103 # Support specification of the number of blocks for empty jffs2
1104 if ($entry{'file'} =~ m/^[0-9]+$/) {
1105 $size = $entry{'file'};
1106 $entry{'file'} = undef;
1109 # If the user has specified a size, then respect their wishes
1110 if (defined $size) {
1111 $entry{'size'} = $size * $block_size;
1112 # Create an empty partition of the requested size.
1113 $entry{'data'} = padBytes
("", $entry{'size'});
1114 if ($entry{'header'}) {
1115 $entry{'data'} = padBytes
("", $entry{'size'} - $entry{'header'});
1125 # Read in the firmware image
1128 print "Initial partition map:\n";
1129 printPartitions
(@partitions);
1132 my $result = readInFirmware
($input, \
@partitions);
1135 print "After reading firmware:\n";
1136 printPartitions
(@partitions);
1140 # Unpack the firmware if requested
1142 die "Input filename must be specified\n" unless defined $input;
1145 # ($_->{'name'} eq 'FIS directory') and @partitions = checkPartitionTable($_->{'data'});
1148 writeOutFirmwareParts
(@partitions);
1152 # Pack the firmware if requested
1155 if (!defined $loader) {
1156 removeOptionalLoader
(\
@partitions);
1160 print "Initial partition map:\n";
1161 printPartitions
(@partitions);
1164 my $result = readInFirmwareParts
(@partitions);
1167 print "after readInFirmwareParts():\n";
1168 printPartitions
(@partitions);
1170 # ($_->{'name'} eq 'RedBoot') && (printRedbootTrailer($_->{'data'}));
1174 layoutPartitions
(@partitions);
1177 print "after layoutPartitions():\n";
1178 printPartitions
(@partitions);
1181 buildPartitionTable
(@partitions);
1184 print "after buildPartitionTable():\n";
1185 printPartitions
(@partitions);
1189 # if ($_->{'name'} eq 'FIS directory') {
1190 # $lastblock = $_->{'data'};
1194 # print "checkPartitionTable():\n";
1195 # checkPartitionTable($lastblock);
1198 writeOutFirmware
($output, @partitions);
This page took 0.193894 seconds and 5 git commands to generate.