checksum.pl 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/perl
  2. use strict;
  3. use integer;
  4. my $o;
  5. my $infile;
  6. my $outfile;
  7. my $patchfile;
  8. my $length;
  9. while (defined($o = shift @ARGV)) {
  10. if ($o =~ /^-/) {
  11. if ($o eq '-o') {
  12. $outfile = shift @ARGV;
  13. } elsif ($o eq '-p') {
  14. $patchfile = shift @ARGV;
  15. } elsif ($o eq '-l') {
  16. $length = shift @ARGV;
  17. } else {
  18. last; # Error
  19. }
  20. } else {
  21. $infile = $o;
  22. last;
  23. }
  24. }
  25. if (!defined($infile) || scalar @ARGV) {
  26. die "Usage: $0 [-o outfile][-p patchfile][-l length] infile\n";
  27. }
  28. sub nextblock($$$) {
  29. my($block,$len,$limit) = @_;
  30. my $bytes = $block;
  31. if (defined($limit) && $limit - $len < $bytes) {
  32. $bytes = $limit - $len;
  33. }
  34. return $bytes;
  35. }
  36. open(my $in, '<', $infile) or die "$0: $infile: $!\n";
  37. binmode $in;
  38. my $data;
  39. my $sum = 0;
  40. my $len = 0;
  41. my $blocklen;
  42. while (($blocklen = nextblock(4096, $len, $length)) &&
  43. read($in, $data, $blocklen) == $blocklen) {
  44. foreach my $w (unpack("V*", $data)) {
  45. $sum = ($sum + $w) & 0xffffffff;
  46. }
  47. $len += $blocklen;
  48. }
  49. close($in);
  50. if (defined($outfile)) {
  51. my $out;
  52. if ($outfile =~ /^-?$/) {
  53. open($out, '>&', \*STDOUT);
  54. } else {
  55. open($out, '>', $outfile);
  56. }
  57. die "$0: $outfile: $!\n" unless defined($out);
  58. my $outfile_c = uc($outfile) || 'SDRAM_SUM_H';
  59. $outfile_c =~ s/[\W_]+/_/g;
  60. print $out "#ifndef $outfile_c\n";
  61. print $out "#define $outfile_c\n";
  62. printf $out "#define SDRAM_SUM 0x%08x\n", $sum;
  63. print $out "#endif\n";
  64. close($out);
  65. }
  66. if (defined($patchfile)) {
  67. my $pf;
  68. open($pf, '+<', $patchfile) or die "$0: $patchfile: $!\n";
  69. binmode $pf;
  70. seek($pf, 8, 0) or die "$0: $patchfile: $!\n";
  71. print $pf pack("V", $sum);
  72. close($pf);
  73. }