Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 /*
18 * pagebundler converts the given file into a valid C program that can
19 * be compiled. The generated code provides a variable that holds the
20 * content of the original file and a _len variable with the size.
21 *
22 * Usage: pagebundler -f file -v varname > outfile
23 */
25 #include <errno.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <unistd.h>
31 const char *file;
32 const char *varname;
34 int
35 main(int argc, char **argv)
36 {
37 size_t len, r, i;
38 int ch, did;
39 FILE *f;
40 uint8_t buf[64];
42 while ((ch = getopt(argc, argv, "f:v:")) != -1) {
43 switch (ch) {
44 case 'f':
45 file = optarg;
46 break;
47 case 'v':
48 varname = optarg;
49 break;
50 default:
51 fprintf(stderr, "%s: wrong usage\n",
52 argv[0]);
53 return 1;
54 }
55 }
57 if (file == NULL || varname == NULL) {
58 fprintf(stderr, "%s: wrong usage\n", argv[0]);
59 return 1;
60 }
62 if ((f = fopen(file, "r")) == NULL) {
63 fprintf(stderr, "%s: can't open %s: %s",
64 argv[0], file, strerror(errno));
65 return 1;
66 }
68 printf("const uint8_t %s[] = {\n", varname);
70 did = 0;
71 len = 0;
72 for (;;) {
73 r = fread(buf, 1, sizeof(buf), f);
74 len += r;
76 if (r != 0)
77 did = 1;
79 printf("\t");
80 for (i = 0; i < r; ++i) {
81 printf("0x%x, ", buf[i]);
82 }
83 printf("\n");
85 if (r != sizeof(buf))
86 break;
87 }
89 if (!did) {
90 /*
91 * if nothing was emitted, add a NUL byte. This was
92 * still produce an exact copy of the file because
93 * `len' doesn't count this NUL byte. It prevents the
94 * "use of GNU empty initializer extension" warning
95 * when bundling pages/about_empty.gmi
96 */
97 printf("\t0x0\n");
98 }
100 printf("}; /* %s */\n", varname);
102 printf("size_t %s_len = %zu;\n", varname, len);
104 fclose(f);
105 return 0;