Blob


1 /*
2 * Copyright (c) 2022, 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 file > outfile
23 */
25 #include <errno.h>
26 #include <limits.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
33 static void
34 setfname(const char *fname, char *buf, size_t siz)
35 {
36 const char *c, *d;
37 size_t len;
39 if ((c = strrchr(fname, '/')) != NULL)
40 c++;
41 else
42 c = fname;
44 if ((d = strrchr(fname, '.')) == NULL || c > d)
45 d = strchr(fname, '\0');
47 len = d - c;
48 if (len >= siz) {
49 fprintf(stderr, "file name too long: %s\n", fname);
50 exit(1);
51 }
53 memcpy(buf, c, len);
54 buf[len] = '\0';
55 }
57 int
58 main(int argc, char **argv)
59 {
60 size_t len, r, i;
61 int did;
62 FILE *f;
63 uint8_t buf[BUFSIZ];
64 char varname[PATH_MAX];
66 if (argc != 2) {
67 fprintf(stderr, "usage: %s file\n", *argv);
68 return 1;
69 }
71 setfname(argv[1], varname, sizeof(varname));
73 if ((f = fopen(argv[1], "r")) == NULL) {
74 fprintf(stderr, "%s: can't open %s: %s",
75 argv[0], argv[1], strerror(errno));
76 return 1;
77 }
79 printf("const uint8_t %s[] = {\n", varname);
81 did = 0;
82 len = 0;
83 for (;;) {
84 r = fread(buf, 1, sizeof(buf), f);
85 len += r;
87 if (r != 0)
88 did = 1;
90 printf("\t");
91 for (i = 0; i < r; ++i) {
92 printf("0x%x, ", buf[i]);
93 }
94 printf("\n");
96 if (r != sizeof(buf))
97 break;
98 }
100 if (!did) {
101 /*
102 * if nothing was emitted, add a NUL byte. This was
103 * still produce an exact copy of the file because
104 * `len' doesn't count this NUL byte. It prevents the
105 * "use of GNU empty initializer extension" warning
106 * when bundling pages/about_empty.gmi
107 */
108 printf("\t0x0\n");
111 printf("}; /* %s */\n", varname);
113 printf("size_t %s_len = %zu;\n", varname, len);
115 fclose(f);
116 return 0;