162306a36Sopenharmony_ci#! /usr/bin/perl -w
262306a36Sopenharmony_ci# SPDX-License-Identifier: GPL-2.0
362306a36Sopenharmony_ci
462306a36Sopenharmony_ci
562306a36Sopenharmony_ci# convert an Intel HEX file into a set of C records usable by the firmware
662306a36Sopenharmony_ci# loading code in usb-serial.c (or others)
762306a36Sopenharmony_ci
862306a36Sopenharmony_ci# accepts the .hex file(s) on stdin, a basename (to name the initialized
962306a36Sopenharmony_ci# array) as an argument, and prints the .h file to stdout. Typical usage:
1062306a36Sopenharmony_ci#  perl ezusb_convert.pl foo <foo.hex >fw_foo.h
1162306a36Sopenharmony_ci
1262306a36Sopenharmony_ci
1362306a36Sopenharmony_cimy $basename = $ARGV[0];
1462306a36Sopenharmony_cidie "no base name specified" unless $basename;
1562306a36Sopenharmony_ci
1662306a36Sopenharmony_ciwhile (<STDIN>) {
1762306a36Sopenharmony_ci    # ':' <len> <addr> <type> <len-data> <crc> '\r'
1862306a36Sopenharmony_ci    #  len, type, crc are 2-char hex, addr is 4-char hex. type is 00 for
1962306a36Sopenharmony_ci    # normal records, 01 for EOF
2062306a36Sopenharmony_ci    my($lenstring, $addrstring, $typestring, $reststring, $doscrap) =
2162306a36Sopenharmony_ci      /^:(\w\w)(\w\w\w\w)(\w\w)(\w+)(\r?)$/;
2262306a36Sopenharmony_ci    die "malformed line: $_" unless $reststring;
2362306a36Sopenharmony_ci    last if $typestring eq '01';
2462306a36Sopenharmony_ci    my($len) = hex($lenstring);
2562306a36Sopenharmony_ci    my($addr) = hex($addrstring);
2662306a36Sopenharmony_ci    my(@bytes) = unpack("C*", pack("H".(2*$len), $reststring));
2762306a36Sopenharmony_ci    #pop(@bytes); # last byte is a CRC
2862306a36Sopenharmony_ci    push(@records, [$addr, \@bytes]);
2962306a36Sopenharmony_ci}
3062306a36Sopenharmony_ci
3162306a36Sopenharmony_ci@sorted_records = sort { $a->[0] <=> $b->[0] } @records;
3262306a36Sopenharmony_ci
3362306a36Sopenharmony_ciprint <<"EOF";
3462306a36Sopenharmony_ci/*
3562306a36Sopenharmony_ci * ${basename}_fw.h
3662306a36Sopenharmony_ci *
3762306a36Sopenharmony_ci * Generated from ${basename}.s by ezusb_convert.pl
3862306a36Sopenharmony_ci * This file is presumed to be under the same copyright as the source file
3962306a36Sopenharmony_ci * from which it was derived.
4062306a36Sopenharmony_ci */
4162306a36Sopenharmony_ci
4262306a36Sopenharmony_ciEOF
4362306a36Sopenharmony_ci
4462306a36Sopenharmony_ciprint "static const struct ezusb_hex_record ${basename}_firmware[] = {\n";
4562306a36Sopenharmony_ciforeach $r (@sorted_records) {
4662306a36Sopenharmony_ci    printf("{ 0x%04x,\t%d,\t{", $r->[0], scalar(@{$r->[1]}));
4762306a36Sopenharmony_ci    print join(", ", map {sprintf('0x%02x', $_);} @{$r->[1]});
4862306a36Sopenharmony_ci    print "} },\n";
4962306a36Sopenharmony_ci}
5062306a36Sopenharmony_ciprint "{ 0xffff,\t0,\t{0x00} }\n";
5162306a36Sopenharmony_ciprint "};\n";
52