b.liu | e958203 | 2025-04-17 19:18:16 +0800 | [diff] [blame] | 1 | #!/usr/bin/env perl |
| 2 | # |
| 3 | # xxdi.pl - perl implementation of 'xxd -i' mode |
| 4 | # |
| 5 | # Copyright 2013 Greg Kroah-Hartman <gregkh@linuxfoundation.org> |
| 6 | # Copyright 2013 Linux Foundation |
| 7 | # |
| 8 | # Released under the GPLv2. |
| 9 | # |
| 10 | # Implements the "basic" functionality of 'xxd -i' in perl to keep build |
| 11 | # systems from having to build/install/rely on vim-core, which not all |
| 12 | # distros want to do. But everyone has perl, so use it instead. |
| 13 | # |
| 14 | |
| 15 | use strict; |
| 16 | use warnings; |
| 17 | |
| 18 | my $indata; |
| 19 | my $var_name = "stdin"; |
| 20 | my $full_output = (@ARGV > 0 && $ARGV[0] eq '-i') ? shift @ARGV : undef; |
| 21 | |
| 22 | { |
| 23 | local $/; |
| 24 | my $fh; |
| 25 | |
| 26 | if (@ARGV) { |
| 27 | $var_name = $ARGV[0]; |
| 28 | open($fh, '<:raw', $var_name) || die("xxdi.pl: Unable to open $var_name: $!\n"); |
| 29 | } elsif (! -t STDIN) { |
| 30 | $fh = \*STDIN; |
| 31 | undef $full_output; |
| 32 | } else { |
| 33 | die "usage: xxdi.pl [-i] [infile]\n"; |
| 34 | } |
| 35 | |
| 36 | $indata = readline $fh; |
| 37 | |
| 38 | close $fh; |
| 39 | } |
| 40 | |
| 41 | my $len_data = length($indata); |
| 42 | my $num_digits_per_line = 12; |
| 43 | my $outdata = ""; |
| 44 | |
| 45 | # Use the variable name of the file we read from, converting '/' and '. |
| 46 | # to '_', or, if this is stdin, just use "stdin" as the name. |
| 47 | $var_name =~ s/\//_/g; |
| 48 | $var_name =~ s/\./_/g; |
| 49 | $var_name = "__$var_name" if $var_name =~ /^\d/; |
| 50 | |
| 51 | $outdata = "unsigned char $var_name\[] = { " if $full_output; |
| 52 | |
| 53 | for (my $key= 0; $key < $len_data; $key++) { |
| 54 | if ($key % $num_digits_per_line == 0) { |
| 55 | $outdata = substr($outdata, 0, -1)."\n "; |
| 56 | } |
| 57 | $outdata .= sprintf("0x%.2x, ", ord(substr($indata, $key, 1))); |
| 58 | } |
| 59 | |
| 60 | $outdata = substr($outdata, 0, -2); |
| 61 | $outdata .= "\n"; |
| 62 | |
| 63 | $outdata .= "};\nunsigned int $var_name\_len = $len_data;\n" if $full_output; |
| 64 | |
| 65 | binmode STDOUT; |
| 66 | print $outdata; |