]> git.saurik.com Git - apple/hfs.git/blob - tests/img-to-c.c
hfs-522.0.9.tar.gz
[apple/hfs.git] / tests / img-to-c.c
1 #include <spawn.h>
2 #include <err.h>
3 #include <unistd.h>
4 #include <zlib.h>
5 #include <fcntl.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <stdio.h>
9 #include <string.h>
10
11 void *zalloc(__unused void *opaque, uInt items, uInt size)
12 {
13 return malloc(items * size);
14 }
15
16 void zfree(__unused void *opaque, void *ptr)
17 {
18 free(ptr);
19 }
20
21 int main(int argc, char *argv[])
22 {
23 const int fixed_args = 4;
24 char *args[argc + fixed_args];
25
26 char template[] = "/tmp/img-to-c.XXXXXXXX";
27 char *dir = mkdtemp(template);
28
29 if (!dir)
30 err(1, "mkdtemp failed");
31
32 char *path;
33 asprintf(&path, "%s/img.sparseimage", dir);
34
35 args[0] = "hdiutil";
36 args[1] = "create";
37 args[2] = path;
38 args[3] = "-quiet";
39
40 int i;
41 for (i = 1; i < argc; ++i)
42 args[i + fixed_args - 1] = argv[i];
43 args[i + fixed_args - 1] = NULL;
44
45 pid_t pid;
46 posix_spawn(&pid, "/usr/bin/hdiutil", NULL, NULL, args, NULL);
47
48 int status;
49 waitpid(pid, &status, 0);
50
51 if (!WIFEXITED(status) || WEXITSTATUS(status))
52 err(1, "hdiutil failed");
53
54 int fd = open(path, O_RDONLY);
55
56 z_stream zs = {
57 .zalloc = zalloc,
58 .zfree = zfree,
59 };
60
61 deflateInit(&zs, Z_DEFAULT_COMPRESSION);
62
63 const size_t buf_size = 1024 * 1024;
64
65 unsigned char *out_buf = malloc(buf_size);
66 int flush = 0;
67
68 unsigned char *in_buf = malloc(buf_size);
69
70 printf("unsigned char data[] = {");
71 int offset = 0;
72
73 zs.next_in = in_buf;
74
75 do {
76 if (!flush) {
77 ssize_t amt = read(fd, zs.next_in, &in_buf[buf_size] - zs.next_in);
78
79 if (!amt)
80 flush = Z_FINISH;
81
82 zs.avail_in += amt;
83 }
84
85 zs.next_out = out_buf;
86 zs.avail_out = buf_size;
87
88 deflate(&zs, flush);
89
90 memmove(in_buf, zs.next_in, zs.avail_in);
91 zs.next_in = in_buf;
92
93 for (unsigned i = 0; i < buf_size - zs.avail_out; ++i) {
94 if (!(offset & 15))
95 printf("\n ");
96 printf("0x%02x, ", out_buf[i]);
97 ++offset;
98 }
99 } while (!flush || zs.avail_in);
100
101 printf("\n};\n");
102
103 // Clean up
104 unlink(path);
105 rmdir(dir);
106 }