mkdata.pl 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/perl
  2. # This program is used to embed arbitrary data into a C binary. It takes
  3. # a list of files as an input, and produces a .c data file that contains
  4. # contents of all these files as collection of char arrays.
  5. #
  6. # Usage: perl <this_file> <file1> [file2, ...] > embedded_data.c
  7. use File::Basename;
  8. %mimetypes = (
  9. js => 'application/javascript',
  10. css => 'text/css',
  11. ico => 'image/vnd.microsoft.icon',
  12. woff => 'application/font-woff',
  13. ttf => 'application/x-font-ttf',
  14. eot => 'application/octet-stream',
  15. svg => 'image/svg+xml',
  16. html => 'text/html'
  17. );
  18. foreach my $i (0 .. $#ARGV) {
  19. open FD, '<:raw', $ARGV[$i] or die "Cannot open $ARGV[$i]: $!\n";
  20. printf("static const unsigned char v%d[] = {", $i);
  21. my $byte;
  22. my $j = 0;
  23. while (read(FD, $byte, 1)) {
  24. if (($j % 12) == 0) {
  25. print "\n";
  26. }
  27. printf ' %#04x,', ord($byte);
  28. $j++;
  29. }
  30. print " 0x00\n};\n";
  31. close FD;
  32. }
  33. print <<EOS;
  34. #include <stddef.h>
  35. #include <string.h>
  36. #include <sys/types.h>
  37. #include "src/http_server.h"
  38. static const struct embedded_file embedded_files[] = {
  39. EOS
  40. foreach my $i (0 .. $#ARGV) {
  41. my ($ext) = $ARGV[$i] =~ /([^.]+)$/;
  42. my $mime = $mimetypes{$ext};
  43. $ARGV[$i] =~ s/htdocs//;
  44. print " {\"$ARGV[$i]\", v$i, \"$mime\", sizeof(v$i) - 1},\n";
  45. }
  46. print <<EOS;
  47. {NULL, NULL, NULL, 0}
  48. };
  49. const struct embedded_file *find_embedded_file(const char *name) {
  50. const struct embedded_file *p;
  51. for (p = embedded_files; p->name != NULL; p++)
  52. if (!strcmp(p->name, name))
  53. return p;
  54. return NULL;
  55. }
  56. EOS