1#!/usr/bin/env perl 2# 3# srecimage.pl - script to convert a binary image into srec 4# Copyright (c) 2015 - Jo-Philipp Wich <jow@openwrt.org> 5# 6# This script is in the public domain. 7 8use strict; 9 10my ($input, $output, $offset) = @ARGV; 11 12if (!defined($input) || !-f $input || !defined($output) || 13 !defined($offset) || $offset !~ /^(0x)?[a-fA-F0-9]+$/) { 14 die "Usage: $0 <input file> <output file> <load address>\n"; 15} 16 17sub srec 18{ 19 my ($type, $addr, $data, $len) = @_; 20 my @addrtypes = qw(%04X %04X %06X %08X %08X %04X %06X %08X %06X %04X); 21 my $addrstr = sprintf $addrtypes[$type], $addr; 22 23 $len = length($data) if ($len <= 0); 24 $len += 1 + (length($addrstr) / 2); 25 26 my $sum = $len; 27 28 foreach my $byte (unpack('C*', pack('H*', $addrstr)), unpack('C*', $data)) 29 { 30 $sum += $byte; 31 } 32 33 return sprintf "S%d%02X%s%s%02X\r\n", 34 $type, $len, $addrstr, uc(unpack('H*', $data)), ~($sum & 0xFF) & 0xFF; 35} 36 37 38open(IN, '<:raw', $input) || die "Unable to open $input: $!\n"; 39open(OUT, '>:raw', $output) || die "Unable to open $output: $!\n"; 40 41my ($basename) = $output =~ m!([^/]+)$!; 42 43print OUT srec(0, 0, $basename, 0); 44 45my $off = hex($offset); 46my $len; 47 48while (defined($len = read(IN, my $buf, 16)) && $len > 0) 49{ 50 print OUT srec(3, $off, $buf, $len); 51 $off += $len; 52} 53 54print OUT srec(7, hex($offset), "", 0); 55 56close OUT; 57close IN; 58