srecimage.pl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. use strict;
  8. my ($input, $output, $offset) = @ARGV;
  9. if (!defined($input) || !-f $input || !defined($output) ||
  10. !defined($offset) || $offset !~ /^(0x)?[a-fA-F0-9]+$/) {
  11. die "Usage: $0 <input file> <output file> <load address>\n";
  12. }
  13. sub srec
  14. {
  15. my ($type, $addr, $data, $len) = @_;
  16. my @addrtypes = qw(%04X %04X %06X %08X %08X %04X %06X %08X %06X %04X);
  17. my $addrstr = sprintf $addrtypes[$type], $addr;
  18. $len = length($data) if ($len <= 0);
  19. $len += 1 + (length($addrstr) / 2);
  20. my $sum = $len;
  21. foreach my $byte (unpack('C*', pack('H*', $addrstr)), unpack('C*', $data))
  22. {
  23. $sum += $byte;
  24. }
  25. return sprintf "S%d%02X%s%s%02X\r\n",
  26. $type, $len, $addrstr, uc(unpack('H*', $data)), ~($sum & 0xFF) & 0xFF;
  27. }
  28. open(IN, '<:raw', $input) || die "Unable to open $input: $!\n";
  29. open(OUT, '>:raw', $output) || die "Unable to open $output: $!\n";
  30. my ($basename) = $output =~ m!([^/]+)$!;
  31. print OUT srec(0, 0, $basename, 0);
  32. my $off = hex($offset);
  33. my $len;
  34. while (defined($len = read(IN, my $buf, 16)) && $len > 0)
  35. {
  36. print OUT srec(3, $off, $buf, $len);
  37. $off += $len;
  38. }
  39. print OUT srec(7, hex($offset), "", 0);
  40. close OUT;
  41. close IN;