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 * original file.
21 *
22 * Usage: pagebundler -f file -v varname > outfile
23 */
25 #include <errno.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <string.h>
30 const char *file;
31 const char *varname;
33 int
34 main(int argc, char **argv)
35 {
36 size_t len, r, i;
37 int ch;
38 FILE *f;
39 uint8_t buf[64];
41 while ((ch = getopt(argc, argv, "f:v:")) != -1) {
42 switch (ch) {
43 case 'f':
44 file = optarg;
45 break;
46 case 'v':
47 varname = optarg;
48 break;
49 default:
50 fprintf(stderr, "%s: wrong usage\n",
51 argv[0]);
52 return 1;
53 }
54 }
56 if (file == NULL || varname == NULL) {
57 fprintf(stderr, "%s: wrong usage\n", argv[0]);
58 return 1;
59 }
61 if ((f = fopen(file, "r")) == NULL) {
62 fprintf(stderr, "%s: can't open %s: %s",
63 argv[0], file, strerror(errno));
64 }
66 printf("const uint8_t %s[] = {\n", varname);
68 len = 0;
69 for (;;) {
70 r = fread(buf, 1, sizeof(buf), f);
71 len += r;
73 printf("\t");
74 for (i = 0; i < r; ++i) {
75 printf("0x%x, ", buf[i]);
76 }
77 printf("\n");
79 if (r != sizeof(buf))
80 break;
81 }
83 len++;
84 printf("\t0x00\n");
85 printf("}; /* %s */\n", varname);
87 printf("size_t %s_len = %zu;\n", varname, len);
89 fclose(f);
90 return 0;
91 }