18c2ecf20Sopenharmony_ci#! /usr/bin/perl -w
28c2ecf20Sopenharmony_ci# SPDX-License-Identifier: GPL-2.0
38c2ecf20Sopenharmony_ci
48c2ecf20Sopenharmony_ci
58c2ecf20Sopenharmony_ci# convert an Intel HEX file into a set of C records usable by the firmware
68c2ecf20Sopenharmony_ci# loading code in usb-serial.c (or others)
78c2ecf20Sopenharmony_ci
88c2ecf20Sopenharmony_ci# accepts the .hex file(s) on stdin, a basename (to name the initialized
98c2ecf20Sopenharmony_ci# array) as an argument, and prints the .h file to stdout. Typical usage:
108c2ecf20Sopenharmony_ci#  perl ezusb_convert.pl foo <foo.hex >fw_foo.h
118c2ecf20Sopenharmony_ci
128c2ecf20Sopenharmony_ci
138c2ecf20Sopenharmony_cimy $basename = $ARGV[0];
148c2ecf20Sopenharmony_cidie "no base name specified" unless $basename;
158c2ecf20Sopenharmony_ci
168c2ecf20Sopenharmony_ciwhile (<STDIN>) {
178c2ecf20Sopenharmony_ci    # ':' <len> <addr> <type> <len-data> <crc> '\r'
188c2ecf20Sopenharmony_ci    #  len, type, crc are 2-char hex, addr is 4-char hex. type is 00 for
198c2ecf20Sopenharmony_ci    # normal records, 01 for EOF
208c2ecf20Sopenharmony_ci    my($lenstring, $addrstring, $typestring, $reststring, $doscrap) =
218c2ecf20Sopenharmony_ci      /^:(\w\w)(\w\w\w\w)(\w\w)(\w+)(\r?)$/;
228c2ecf20Sopenharmony_ci    die "malformed line: $_" unless $reststring;
238c2ecf20Sopenharmony_ci    last if $typestring eq '01';
248c2ecf20Sopenharmony_ci    my($len) = hex($lenstring);
258c2ecf20Sopenharmony_ci    my($addr) = hex($addrstring);
268c2ecf20Sopenharmony_ci    my(@bytes) = unpack("C*", pack("H".(2*$len), $reststring));
278c2ecf20Sopenharmony_ci    #pop(@bytes); # last byte is a CRC
288c2ecf20Sopenharmony_ci    push(@records, [$addr, \@bytes]);
298c2ecf20Sopenharmony_ci}
308c2ecf20Sopenharmony_ci
318c2ecf20Sopenharmony_ci@sorted_records = sort { $a->[0] <=> $b->[0] } @records;
328c2ecf20Sopenharmony_ci
338c2ecf20Sopenharmony_ciprint <<"EOF";
348c2ecf20Sopenharmony_ci/*
358c2ecf20Sopenharmony_ci * ${basename}_fw.h
368c2ecf20Sopenharmony_ci *
378c2ecf20Sopenharmony_ci * Generated from ${basename}.s by ezusb_convert.pl
388c2ecf20Sopenharmony_ci * This file is presumed to be under the same copyright as the source file
398c2ecf20Sopenharmony_ci * from which it was derived.
408c2ecf20Sopenharmony_ci */
418c2ecf20Sopenharmony_ci
428c2ecf20Sopenharmony_ciEOF
438c2ecf20Sopenharmony_ci
448c2ecf20Sopenharmony_ciprint "static const struct ezusb_hex_record ${basename}_firmware[] = {\n";
458c2ecf20Sopenharmony_ciforeach $r (@sorted_records) {
468c2ecf20Sopenharmony_ci    printf("{ 0x%04x,\t%d,\t{", $r->[0], scalar(@{$r->[1]}));
478c2ecf20Sopenharmony_ci    print join(", ", map {sprintf('0x%02x', $_);} @{$r->[1]});
488c2ecf20Sopenharmony_ci    print "} },\n";
498c2ecf20Sopenharmony_ci}
508c2ecf20Sopenharmony_ciprint "{ 0xffff,\t0,\t{0x00} }\n";
518c2ecf20Sopenharmony_ciprint "};\n";
52