├── .gitignore
├── AUTHORS
├── COPYING
├── ChangeLog
├── Makefile.am
├── NEWS
├── README
├── autogen.sh
├── configure.ac
└── src
├── blz.c
├── blz.h
├── build_pfs0.c
├── build_romfs.c
├── cJSON.c
├── cJSON.h
├── elf2kip.c
├── elf2nro.c
├── elf2nso.c
├── elf64.h
├── elf_common.h
├── filepath.c
├── filepath.h
├── nacptool.c
├── npdmtool.c
├── nxlink.c
├── romfs.c
├── romfs.h
├── sha256.c
├── sha256.h
└── types.h
/.gitignore:
--------------------------------------------------------------------------------
1 | build*
2 | INSTALL
3 | Makefile.in
4 | aclocal.m4
5 | autom4te.cache
6 | config.guess
7 | config.sub
8 | configure
9 | depcomp
10 | install-sh
11 | missing
12 | compile
13 | .deps
14 | Makefile
15 | config.status
16 | config.log
17 | .dirstamp
18 | elf2nro
19 | elf2nso
20 | elf2kip
21 | nacptool
22 | npdmtool
23 | nxlink
24 | *.o
25 | *.elf
26 | *.kip
27 | *.nro
28 | *.nso
29 | *.npdm
30 | *.json
31 |
--------------------------------------------------------------------------------
/AUTHORS:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/switchbrew/switch-tools/22756068dd0ed6ff9734c59cb4f99ebd3f62555b/AUTHORS
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | Copyright 2017 libnx Authors
2 |
3 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
/ChangeLog:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/switchbrew/switch-tools/22756068dd0ed6ff9734c59cb4f99ebd3f62555b/ChangeLog
--------------------------------------------------------------------------------
/Makefile.am:
--------------------------------------------------------------------------------
1 | # Makefile.am -- Process this file with automake to produce Makefile.in
2 | bin_PROGRAMS = elf2nso elf2nro elf2kip build_pfs0 build_romfs nacptool npdmtool nxlink
3 |
4 | build_pfs0_SOURCES = src/build_pfs0.c src/types.h
5 |
6 | build_romfs_SOURCES = src/build_romfs.c src/romfs.c src/romfs.h src/filepath.c src/filepath.h src/types.h
7 |
8 | elf2nro_SOURCES = src/elf2nro.c src/elf64.h src/romfs.c src/filepath.c src/filepath.h src/romfs.h src/elf_common.h
9 |
10 | elf2nso_SOURCES = src/elf2nso.c src/sha256.c src/sha256.h src/elf64.h src/elf_common.h
11 |
12 | elf2kip_SOURCES = src/elf2kip.c src/cJSON.c src/cJSON.h src/blz.c src/blz.h src/elf64.h src/elf_common.h
13 |
14 | nacptool_SOURCES = src/nacptool.c
15 |
16 | npdmtool_SOURCES = src/npdmtool.c src/cJSON.c src/cJSON.h
17 |
18 | nxlink_SOURCES = src/nxlink.c
19 |
20 | nxlink_CPPFLAGS = @ZLIB_CFLAGS@
21 | nxlink_LDADD = @ZLIB_LIBS@ @NET_LIBS@
22 |
23 | elf2nso_CPPFLAGS = @LZ4_CFLAGS@
24 | elf2nso_LDADD = @LZ4_LIBS@
25 |
26 | elf2nro_CPPFLAGS = @LZ4_CFLAGS@
27 | elf2nro_LDADD = @LZ4_LIBS@
28 |
29 |
30 | EXTRA_DIST = autogen.sh
31 |
--------------------------------------------------------------------------------
/NEWS:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/switchbrew/switch-tools/22756068dd0ed6ff9734c59cb4f99ebd3f62555b/NEWS
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/switchbrew/switch-tools/22756068dd0ed6ff9734c59cb4f99ebd3f62555b/README
--------------------------------------------------------------------------------
/autogen.sh:
--------------------------------------------------------------------------------
1 | aclocal
2 | autoconf
3 | automake --add-missing -c
4 |
--------------------------------------------------------------------------------
/configure.ac:
--------------------------------------------------------------------------------
1 | # -*- Autoconf -*-
2 | # Process this file with autoconf to produce a configure script.
3 |
4 | AC_PREREQ(2.61)
5 | AC_INIT([switch-tools],[1.13.1],[https://github.com/switchbrew/switch-tools/issues])
6 | AC_CONFIG_SRCDIR([src/build_pfs0.c])
7 |
8 | AM_INIT_AUTOMAKE([subdir-objects])
9 |
10 | AC_CANONICAL_BUILD
11 | AC_CANONICAL_HOST
12 |
13 | AC_PROG_CC
14 |
15 | AC_SYS_LARGEFILE
16 |
17 | PKG_CHECK_MODULES([LZ4],
18 | [liblz4 >= 1.7.1 liblz4 < 100],
19 | [have_lz4="yes"],
20 | [PKG_CHECK_MODULES([LZ4],
21 | [liblz4 >= 131],
22 | [have_lz4="yes"])
23 | ])
24 |
25 | PKG_CHECK_MODULES([ZLIB], zlib, [
26 | AC_DEFINE([HAVE_LIBZ], [1], [Define if using zlib.])
27 | ])
28 |
29 | NET_LIBS=""
30 |
31 | case "$host" in
32 | *-*-mingw*)
33 | NET_LIBS="-lws2_32"
34 | CFLAGS="$CFLAGS -D__USE_MINGW_ANSI_STDIO -D_WIN32_WINNT=0x0600"
35 | ;;
36 | esac
37 |
38 | CFLAGS="$CFLAGS -std=gnu99"
39 |
40 | AC_SUBST(ZLIB_CFLAGS)
41 | AC_SUBST(ZLIB_LIBS)
42 | AC_SUBST(NET_LIBS)
43 | AC_SUBST(LZ4_CFLAGS)
44 | AC_SUBST(LZ4_LIBS)
45 | AC_CONFIG_FILES([Makefile])
46 | AC_OUTPUT
47 |
--------------------------------------------------------------------------------
/src/blz.c:
--------------------------------------------------------------------------------
1 | /*----------------------------------------------------------------------------*/
2 | /*-- blz.c - Bottom LZ coding for Nintendo GBA/DS --*/
3 | /*-- Copyright (C) 2011 CUE --*/
4 | /*-- --*/
5 | /*-- This program is free software: you can redistribute it and/or modify --*/
6 | /*-- it under the terms of the GNU General Public License as published by --*/
7 | /*-- the Free Software Foundation, either version 3 of the License, or --*/
8 | /*-- (at your option) any later version. --*/
9 | /*-- --*/
10 | /*-- This program is distributed in the hope that it will be useful, --*/
11 | /*-- but WITHOUT ANY WARRANTY; without even the implied warranty of --*/
12 | /*-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --*/
13 | /*-- GNU General Public License for more details. --*/
14 | /*-- --*/
15 | /*-- You should have received a copy of the GNU General Public License --*/
16 | /*-- along with this program. If not, see . --*/
17 | /*----------------------------------------------------------------------------*/
18 |
19 | /*----------------------------------------------------------------------------*/
20 | #include "blz.h"
21 | #include
22 | #include
23 | #include
24 |
25 | /*----------------------------------------------------------------------------*/
26 | #define CMD_DECODE 0x00 // decode
27 | #define CMD_ENCODE 0x01 // encode
28 |
29 | #define BLZ_SHIFT 1 // bits to shift
30 | #define BLZ_MASK 0x80 // bits to check:
31 | // ((((1 << BLZ_SHIFT) - 1) << (8 - BLZ_SHIFT)
32 |
33 | #define BLZ_THRESHOLD 2 // max number of bytes to not encode
34 | #define BLZ_N 0x1002 // max offset ((1 << 12) + 2)
35 | #define BLZ_F 0x12 // max coded ((1 << 4) + BLZ_THRESHOLD)
36 |
37 | #define RAW_MINIM 0x00000000 // empty file, 0 bytes
38 | #define RAW_MAXIM 0x00FFFFFF // 3-bytes length, 16MB - 1
39 |
40 | #define BLZ_MINIM 0x00000004 // header only (empty RAW file)
41 | #define BLZ_MAXIM 0x01400000 // 0x0120000A, padded to 20MB:
42 | // * length, RAW_MAXIM
43 | // * flags, (RAW_MAXIM + 7) / 8
44 | // * header, 11
45 | // 0x00FFFFFF + 0x00200000 + 12 + padding
46 |
47 | /*----------------------------------------------------------------------------*/
48 | #define BREAK(text) { printf(text); return; }
49 | #define EXIT(text) { printf(text); exit(-1); }
50 |
51 | /*----------------------------------------------------------------------------*/
52 | u8 *Memory(int length, int size);
53 |
54 | u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
55 | void BLZ_Invert(u8 *buffer, int length);
56 |
57 | /*----------------------------------------------------------------------------*/
58 | u8 *Memory(int length, int size) {
59 | u8 *fb;
60 |
61 | fb = (u8 *) calloc(length * size, size);
62 | if (fb == NULL) EXIT("\nMemory error\n");
63 |
64 | return(fb);
65 | }
66 |
67 | /*----------------------------------------------------------------------------*/
68 | void BLZ_Decode(char *filename) {
69 | // u8 *pak_buffer, *raw_buffer, *pak, *raw, *pak_end, *raw_end;
70 | // u32 pak_len, raw_len, len, pos, inc_len, hdr_len, enc_len, dec_len;
71 | // u8 flags, mask;
72 |
73 | // printf("- decoding '%s'", filename);
74 |
75 | // // pak_buffer = Load(filename, &pak_len, BLZ_MINIM, BLZ_MAXIM);
76 |
77 | // inc_len = *(u32 *)(pak_buffer + pak_len - 4);
78 | // if (!inc_len) {
79 | // enc_len = 0;
80 | // dec_len = pak_len - 4;
81 | // pak_len = 0;
82 | // raw_len = dec_len;
83 | // } else {
84 | // if (pak_len < 8) EXIT("File has a bad header\n");
85 | // hdr_len = pak_buffer[pak_len - 5];
86 | // if ((hdr_len < 0x08) || (hdr_len > 0x0B)) EXIT("Bad header length\n");
87 | // if (pak_len <= hdr_len) EXIT("Bad length\n");
88 | // enc_len = *(u32 *)(pak_buffer + pak_len - 8) & 0x00FFFFFF;
89 | // dec_len = pak_len - enc_len;
90 | // pak_len = enc_len - hdr_len;
91 | // raw_len = dec_len + enc_len + inc_len;
92 | // if (raw_len > RAW_MAXIM) EXIT("Bad decoded length\n");
93 | // }
94 |
95 | // raw_buffer = (u8 *) Memory(raw_len, sizeof(char));
96 |
97 | // pak = pak_buffer;
98 | // raw = raw_buffer;
99 | // pak_end = pak_buffer + dec_len + pak_len;
100 | // raw_end = raw_buffer + raw_len;
101 |
102 | // for (len = 0; len < dec_len; len++) *(raw++) = *(pak++);
103 |
104 | // BLZ_Invert(pak_buffer + dec_len, pak_len);
105 |
106 | // mask = 0;
107 |
108 | // while (raw < raw_end) {
109 | // if (!(mask >>= BLZ_SHIFT)) {
110 | // if (pak == pak_end) break;
111 | // flags = *pak++;
112 | // mask = BLZ_MASK;
113 | // }
114 |
115 | // if (!(flags & mask)) {
116 | // if (pak == pak_end) break;
117 | // *raw++ = *pak++;
118 | // } else {
119 | // if (pak + 1 >= pak_end) break;
120 | // pos = *pak++ << 8;
121 | // pos |= *pak++;
122 | // len = (pos >> 12) + BLZ_THRESHOLD + 1;
123 | // if (raw + len > raw_end) {
124 | // printf(", WARNING: wrong decoded length!");
125 | // len = raw_end - raw;
126 | // }
127 | // pos = (pos & 0xFFF) + 3;
128 | // while (len--) *(raw++) = *(raw - pos);
129 | // }
130 | // }
131 |
132 | // BLZ_Invert(raw_buffer + dec_len, raw_len - dec_len);
133 |
134 | // raw_len = raw - raw_buffer;
135 |
136 | // if (raw != raw_end) printf(", WARNING: unexpected end of encoded file!");
137 |
138 | // // Save(filename, raw_buffer, raw_len);
139 |
140 | // free(raw_buffer);
141 | // free(pak_buffer);
142 |
143 | // printf("\n");
144 | }
145 |
146 | u8 *Load(char *filename, u32 *length, int min, int max) {
147 | FILE *fp;
148 | int fs;
149 | u8 *fb;
150 |
151 | if ((fp = fopen(filename, "rb")) == NULL) EXIT("\nFile open error\n");
152 | fseek(fp, 0, SEEK_END);
153 | fs = ftell(fp);
154 | fseek(fp, 0, SEEK_SET);
155 | if ((fs < min) || (fs > max)) EXIT("\nFile size error\n");
156 | fb = Memory(fs + 3, sizeof(char));
157 | if (fread(fb, 1, fs, fp) != fs) EXIT("\nFile read error\n");
158 | if (fclose(fp) == EOF) EXIT("\nFile close error\n");
159 |
160 | *length = fs;
161 |
162 | return(fb);
163 | }
164 |
165 | /*----------------------------------------------------------------------------*/
166 | u8* BLZ_Encode(char *filename, u32* pak_len, int mode) {
167 | u8 *raw_buffer, *pak_buffer, *new_buffer;
168 | u32 raw_len, new_len;
169 |
170 | raw_buffer = Load(filename, &raw_len, RAW_MINIM, RAW_MAXIM);
171 |
172 | pak_buffer = NULL;
173 | *pak_len = BLZ_MAXIM + 1;
174 |
175 | new_buffer = BLZ_Code(raw_buffer, raw_len, &new_len, mode);
176 | if (new_len < *pak_len) {
177 | if (pak_buffer != NULL) free(pak_buffer);
178 | pak_buffer = new_buffer;
179 | *pak_len = new_len;
180 | }
181 |
182 | return pak_buffer;
183 | }
184 |
185 | /*----------------------------------------------------------------------------*/
186 | u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best) {
187 | u8 *pak_buffer, *pak, *raw, *raw_end, *flg = NULL, *tmp;
188 | u32 pak_len, inc_len, hdr_len, enc_len, len, pos, max;
189 | u32 len_best, pos_best = 0, len_next, pos_next, len_post, pos_post;
190 | u32 pak_tmp, raw_tmp;
191 | u8 mask;
192 |
193 | #define SEARCH(l,p) { \
194 | l = BLZ_THRESHOLD; \
195 | \
196 | max = raw - raw_buffer >= BLZ_N ? BLZ_N : raw - raw_buffer; \
197 | for (pos = 3; pos <= max; pos++) { \
198 | for (len = 0; len < BLZ_F; len++) { \
199 | if (raw + len == raw_end) break; \
200 | if (len >= pos) break; \
201 | if (*(raw + len) != *(raw + len - pos)) break; \
202 | } \
203 | \
204 | if (len > l) { \
205 | p = pos; \
206 | if ((l = len) == BLZ_F) break; \
207 | } \
208 | } \
209 | }
210 |
211 | pak_tmp = 0;
212 | raw_tmp = raw_len;
213 |
214 | pak_len = raw_len + ((raw_len + 7) / 8) + 15;
215 | pak_buffer = (u8 *) Memory(pak_len, sizeof(char));
216 |
217 | BLZ_Invert(raw_buffer, raw_len);
218 |
219 | pak = pak_buffer;
220 | raw = raw_buffer;
221 | raw_end = raw_buffer + raw_len;
222 |
223 | mask = 0;
224 |
225 | while (raw < raw_end) {
226 | if (!(mask >>= BLZ_SHIFT)) {
227 | *(flg = pak++) = 0;
228 | mask = BLZ_MASK;
229 | }
230 |
231 | SEARCH(len_best, pos_best);
232 |
233 | // LZ-CUE optimization start
234 | if (best) {
235 | if (len_best > BLZ_THRESHOLD) {
236 | if (raw + len_best < raw_end) {
237 | raw += len_best;
238 | SEARCH(len_next, pos_next);
239 | raw -= len_best - 1;
240 | SEARCH(len_post, pos_post);
241 | raw--;
242 |
243 | if (len_next <= BLZ_THRESHOLD) len_next = 1;
244 | if (len_post <= BLZ_THRESHOLD) len_post = 1;
245 |
246 | if (len_best + len_next <= 1 + len_post) len_best = 1;
247 | }
248 | }
249 | }
250 | // LZ-CUE optimization end
251 |
252 | *flg <<= 1;
253 | if (len_best > BLZ_THRESHOLD) {
254 | raw += len_best;
255 | *flg |= 1;
256 | *pak++ = ((len_best - (BLZ_THRESHOLD+1)) << 4) | ((pos_best - 3) >> 8);
257 | *pak++ = (pos_best - 3) & 0xFF;
258 | } else {
259 | *pak++ = *raw++;
260 | }
261 |
262 | if (pak - pak_buffer + raw_len - (raw - raw_buffer) < pak_tmp + raw_tmp) {
263 | pak_tmp = pak - pak_buffer;
264 | raw_tmp = raw_len - (raw - raw_buffer);
265 | }
266 | }
267 |
268 | while (mask && (mask != 1)) {
269 | mask >>= BLZ_SHIFT;
270 | *flg <<= 1;
271 | }
272 |
273 | pak_len = pak - pak_buffer;
274 |
275 | BLZ_Invert(raw_buffer, raw_len);
276 | BLZ_Invert(pak_buffer, pak_len);
277 |
278 | if (!pak_tmp || (raw_len + 4 < ((pak_tmp + raw_tmp + 3) & -4) + 8)) {
279 | pak = pak_buffer;
280 | raw = raw_buffer;
281 | raw_end = raw_buffer + raw_len;
282 |
283 | while (raw < raw_end) *pak++ = *raw++;
284 |
285 | while ((pak - pak_buffer) & 3) *pak++ = 0;
286 |
287 | *(u32 *)pak = 0; pak += 4;
288 | } else {
289 | tmp = (u8 *) Memory(raw_tmp + pak_tmp + 15, sizeof(char));
290 |
291 | for (len = 0; len < raw_tmp; len++)
292 | tmp[len] = raw_buffer[len];
293 |
294 | for (len = 0; len < pak_tmp; len++)
295 | tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];
296 |
297 | pak = pak_buffer;
298 | pak_buffer = tmp;
299 |
300 | free(pak);
301 |
302 | pak = pak_buffer + raw_tmp + pak_tmp;
303 |
304 | enc_len = pak_tmp;
305 | hdr_len = 12;
306 | inc_len = raw_len - pak_tmp - raw_tmp;
307 |
308 | while ((pak - pak_buffer) & 3) {
309 | *pak++ = 0xFF;
310 | hdr_len++;
311 | }
312 |
313 | *(u32 *)pak = enc_len + hdr_len; pak += 4;
314 | *(u32 *)pak = hdr_len; pak += 4;
315 | *(u32 *)pak = inc_len - hdr_len; pak += 4;
316 | }
317 |
318 | *new_len = pak - pak_buffer;
319 |
320 | return(pak_buffer);
321 | }
322 |
323 | /*----------------------------------------------------------------------------*/
324 | void BLZ_Invert(u8 *buffer, int length) {
325 | u8 *bottom, ch;
326 |
327 | bottom = buffer + length - 1;
328 |
329 | while (buffer < bottom) {
330 | ch = *buffer;
331 | *buffer++ = *bottom;
332 | *bottom-- = ch;
333 | }
334 | }
335 |
336 | /*----------------------------------------------------------------------------*/
337 | /*-- EOF Copyright (C) 2011 CUE --*/
338 | /*----------------------------------------------------------------------------*/
339 |
--------------------------------------------------------------------------------
/src/blz.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | typedef uint64_t u64;
6 | typedef uint32_t u32;
7 | typedef uint16_t u16;
8 | typedef uint8_t u8;
9 |
10 | #define BLZ_NORMAL 0 // normal mode
11 | #define BLZ_BEST 1 // best mode
12 |
13 | u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
--------------------------------------------------------------------------------
/src/build_pfs0.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include "types.h"
8 |
9 | //Build with: gcc -o build_pfs0 build_pfs0.c
10 |
11 | #define MAX_FS_ENTRIES 0x10//If ever needed, this constant and the size of stringtable can be increased.
12 |
13 | typedef struct {
14 | u32 magicnum;//"PFS0"
15 | u32 file_count;
16 | u32 stringtable_size;
17 | u32 val_xc;//"Zero/Reserved"
18 | } pfs0_header;
19 |
20 | typedef struct {
21 | u64 offset;
22 | u64 size;
23 | u32 stringtable_offset;
24 | u32 val_x14;//"Normally zero?"
25 | } pfs0_fsentry;
26 |
27 | int build_pfs0(char *in_dirpath, char *out_pfs0_filepath)
28 | {
29 | DIR *dir = NULL;
30 | struct dirent *cur_dirent = NULL;
31 | struct stat objstats;
32 | FILE *fout = NULL, *fin = NULL;
33 | int ret=0;
34 | u32 tmplen=0;
35 | u32 pos;
36 | u8 *tmpbuf;
37 |
38 | u32 objcount = 0;
39 | u32 stringtable_offset=0;
40 | u64 filedata_reloffset=0;
41 |
42 | pfs0_header header;
43 | pfs0_fsentry fsentries[MAX_FS_ENTRIES];
44 | pfs0_fsentry *fsentry;
45 |
46 | char objpath[257];
47 |
48 | char stringtable[0x100];
49 |
50 | memset(&header, 0, sizeof(header));
51 | memset(fsentries, 0, sizeof(fsentries));
52 | memset(stringtable, 0, sizeof(stringtable));
53 |
54 | dir = opendir(in_dirpath);
55 | if(dir==NULL)
56 | {
57 | printf("Failed to open dirpath.\n");
58 | return 1;
59 | }
60 |
61 | fout = fopen(out_pfs0_filepath, "wb");
62 | if(fout==NULL)
63 | {
64 | printf("Failed to open PFS0 filepath.\n");
65 | closedir(dir);
66 | return 1;
67 | }
68 |
69 | while((cur_dirent = readdir(dir)))
70 | {
71 | if(strcmp(cur_dirent->d_name, ".")==0 || strcmp(cur_dirent->d_name, "..")==0)continue;
72 |
73 | memset(objpath, 0, sizeof(objpath));
74 | snprintf(objpath, sizeof(objpath)-1, "%s%s", in_dirpath, cur_dirent->d_name);
75 |
76 | if(stat(objpath, &objstats)==-1)
77 | {
78 | printf("Failed to stat: %s\n", objpath);
79 | ret = 2;
80 | break;
81 | }
82 |
83 | if((objstats.st_mode & S_IFMT) == S_IFDIR)//directory
84 | {
85 | printf("Directories aren't supported, skipping... (%s)\n", objpath);
86 | }
87 | else if((objstats.st_mode & S_IFMT) == S_IFREG)//file
88 | {
89 | if(objcount>=MAX_FS_ENTRIES)
90 | {
91 | printf("Maximum fs object count already reached.\n");
92 | ret = 3;
93 | break;
94 | }
95 |
96 | fsentry = &fsentries[objcount];
97 |
98 | fsentry->offset = filedata_reloffset;
99 | fsentry->size = objstats.st_size;
100 | filedata_reloffset+= fsentry->size;
101 | fsentry->stringtable_offset = stringtable_offset;
102 |
103 | tmplen = strlen(cur_dirent->d_name)+1;
104 | if(stringtable_offset+tmplen > sizeof(stringtable))
105 | {
106 | printf("Max size of stringtable reached.\n");
107 | ret = 4;
108 | break;
109 | }
110 |
111 | strncpy(&stringtable[stringtable_offset], cur_dirent->d_name, sizeof(stringtable)-stringtable_offset);
112 | stringtable_offset+= tmplen;
113 |
114 | objcount++;
115 | }
116 | else
117 | {
118 | printf("Invalid FS object type.\n");
119 | ret = 14;
120 | break;
121 | }
122 | }
123 |
124 | closedir(dir);
125 |
126 | if(ret==0)
127 | {
128 | stringtable_offset = (stringtable_offset+0x1f) & ~0x1f;
129 |
130 | header.magicnum = le_word(0x30534650);
131 | header.file_count = le_word(objcount);
132 | header.stringtable_size = le_word(stringtable_offset);
133 |
134 | fwrite(&header, 1, sizeof(header), fout);
135 | fwrite(fsentries, 1, sizeof(pfs0_fsentry)*objcount, fout);
136 | fwrite(stringtable, 1, stringtable_offset, fout);
137 |
138 | stringtable_offset = 0;
139 |
140 | for(pos=0; pos sizeof(stringtable))
152 | {
153 | printf("Max size of stringtable reached during stringtable entry reading.\n");
154 | ret = 4;
155 | break;
156 | }
157 |
158 | memset(objpath, 0, sizeof(objpath));
159 | snprintf(objpath, sizeof(objpath)-1, "%s%s", in_dirpath, &stringtable[stringtable_offset]);
160 | stringtable_offset+=tmplen;
161 |
162 | fin = fopen(objpath, "rb");
163 | if(fin==NULL)
164 | {
165 | printf("Failed to open filepath for filedata.\n");
166 | ret = 1;
167 | break;
168 | }
169 |
170 | tmpbuf = malloc(fsentries[pos].size);
171 | if(tmpbuf==NULL)
172 | {
173 | printf("Failed to allocate filedata.\n");
174 | ret = 6;
175 | fclose(fin);
176 | break;
177 | }
178 |
179 | tmplen = fread(tmpbuf, 1, fsentries[pos].size, fin);
180 | fclose(fin);
181 |
182 | fwrite(tmpbuf, 1, fsentries[pos].size, fout);
183 | free(tmpbuf);
184 | }
185 | }
186 |
187 | fclose(fout);
188 |
189 | return ret;
190 | }
191 |
192 | int main(int argc, char **argv)
193 | {
194 | int ret = 0;
195 | u32 pos;
196 |
197 | char dirpath[256];
198 |
199 | if(argc < 3)
200 | {
201 | printf("%s\n", argv[0]);
202 | printf("Build a PFS0 from an input directory.\n");
203 | printf("Usage:\n");
204 | printf("%s \n", argv[0]);
205 | return 0;
206 | }
207 |
208 | pos = strlen(argv[1]);
209 |
210 | if(pos==0 || pos>sizeof(dirpath)-1)
211 | {
212 | printf("Dirpath is length is invalid.\n");
213 | return 1;
214 | }
215 | pos--;
216 |
217 | memset(dirpath, 0, sizeof(dirpath));
218 | strncpy(dirpath, argv[1], sizeof(dirpath)-1);
219 | if(dirpath[pos] != '/')dirpath[pos+1] = '/';
220 |
221 | ret = build_pfs0(dirpath, argv[2]);
222 |
223 | if(ret)printf("Failed to build PFS0.\n");
224 | return 0;
225 | }
226 |
227 |
--------------------------------------------------------------------------------
/src/build_romfs.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "romfs.h"
6 |
7 | int main(int argc, char **argv) {
8 |
9 | if (argc != 3) {
10 | printf("Usage: %s \n", argv[0]);
11 | return 1;
12 | }
13 |
14 | build_romfs_by_paths(argv[1], argv[2]);
15 |
16 | printf("Done!\n");
17 |
18 | return 0;
19 | }
--------------------------------------------------------------------------------
/src/cJSON.h:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is
9 | furnished to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in
12 | all copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | THE SOFTWARE.
21 | */
22 |
23 | #ifndef cJSON__h
24 | #define cJSON__h
25 |
26 | #ifdef __cplusplus
27 | extern "C"
28 | {
29 | #endif
30 |
31 | /* project version */
32 | #define CJSON_VERSION_MAJOR 1
33 | #define CJSON_VERSION_MINOR 7
34 | #define CJSON_VERSION_PATCH 6
35 |
36 | #include
37 |
38 | /* cJSON Types: */
39 | #define cJSON_Invalid (0)
40 | #define cJSON_False (1 << 0)
41 | #define cJSON_True (1 << 1)
42 | #define cJSON_NULL (1 << 2)
43 | #define cJSON_Number (1 << 3)
44 | #define cJSON_String (1 << 4)
45 | #define cJSON_Array (1 << 5)
46 | #define cJSON_Object (1 << 6)
47 | #define cJSON_Raw (1 << 7) /* raw json */
48 |
49 | #define cJSON_IsReference 256
50 | #define cJSON_StringIsConst 512
51 |
52 | /* The cJSON structure: */
53 | typedef struct cJSON
54 | {
55 | /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
56 | struct cJSON *next;
57 | struct cJSON *prev;
58 | /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
59 | struct cJSON *child;
60 |
61 | /* The type of the item, as above. */
62 | int type;
63 |
64 | /* The item's string, if type==cJSON_String and type == cJSON_Raw */
65 | char *valuestring;
66 | /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
67 | int valueint;
68 | /* The item's number, if type==cJSON_Number */
69 | double valuedouble;
70 |
71 | /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
72 | char *string;
73 | } cJSON;
74 |
75 | typedef struct cJSON_Hooks
76 | {
77 | void *(*malloc_fn)(size_t sz);
78 | void (*free_fn)(void *ptr);
79 | } cJSON_Hooks;
80 |
81 | typedef int cJSON_bool;
82 |
83 | #if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
84 | #define __WINDOWS__
85 | #endif
86 | #ifdef __WINDOWS__
87 |
88 | /* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 2 define options:
89 |
90 | CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
91 | CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
92 | CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
93 |
94 | For *nix builds that support visibility attribute, you can define similar behavior by
95 |
96 | setting default visibility to hidden by adding
97 | -fvisibility=hidden (for gcc)
98 | or
99 | -xldscope=hidden (for sun cc)
100 | to CFLAGS
101 |
102 | then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
103 |
104 | */
105 |
106 | /* export symbols by default, this is necessary for copy pasting the C and header file */
107 | #if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
108 | #define CJSON_EXPORT_SYMBOLS
109 | #endif
110 |
111 | #if defined(CJSON_HIDE_SYMBOLS)
112 | #define CJSON_PUBLIC(type) type __stdcall
113 | #elif defined(CJSON_EXPORT_SYMBOLS)
114 | #define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall
115 | #elif defined(CJSON_IMPORT_SYMBOLS)
116 | #define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall
117 | #endif
118 | #else /* !WIN32 */
119 | #if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
120 | #define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
121 | #else
122 | #define CJSON_PUBLIC(type) type
123 | #endif
124 | #endif
125 |
126 | /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
127 | * This is to prevent stack overflows. */
128 | #ifndef CJSON_NESTING_LIMIT
129 | #define CJSON_NESTING_LIMIT 1000
130 | #endif
131 |
132 | /* returns the version of cJSON as a string */
133 | CJSON_PUBLIC(const char*) cJSON_Version(void);
134 |
135 | /* Supply malloc, realloc and free functions to cJSON */
136 | CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
137 |
138 | /* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
139 | /* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
140 | CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
141 | /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
142 | /* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
143 | CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
144 |
145 | /* Render a cJSON entity to text for transfer/storage. */
146 | CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
147 | /* Render a cJSON entity to text for transfer/storage without any formatting. */
148 | CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
149 | /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
150 | CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
151 | /* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
152 | /* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
153 | CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
154 | /* Delete a cJSON entity and all subentities. */
155 | CJSON_PUBLIC(void) cJSON_Delete(cJSON *c);
156 |
157 | /* Returns the number of items in an array (or object). */
158 | CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
159 | /* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
160 | CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
161 | /* Get item "string" from object. Case insensitive. */
162 | CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
163 | CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
164 | CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
165 | /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
166 | CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
167 |
168 | /* Check if the item is a string and return its valuestring */
169 | CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);
170 |
171 | /* These functions check the type of an item */
172 | CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
173 | CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
174 | CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
175 | CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
176 | CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
177 | CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
178 | CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
179 | CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
180 | CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
181 | CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
182 |
183 | /* These calls create a cJSON item of the appropriate type. */
184 | CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
185 | CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
186 | CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
187 | CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
188 | CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
189 | CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
190 | /* raw json */
191 | CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
192 | CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
193 | CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
194 |
195 | /* Create a string where valuestring references a string so
196 | * it will not be freed by cJSON_Delete */
197 | CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
198 | /* Create an object/arrray that only references it's elements so
199 | * they will not be freed by cJSON_Delete */
200 | CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
201 | CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
202 |
203 | /* These utilities create an Array of count items. */
204 | CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
205 | CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
206 | CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
207 | CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);
208 |
209 | /* Append item to the specified array/object. */
210 | CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
211 | CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
212 | /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
213 | * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
214 | * writing to `item->string` */
215 | CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
216 | /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
217 | CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
218 | CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
219 |
220 | /* Remove/Detatch items from Arrays/Objects. */
221 | CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
222 | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
223 | CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
224 | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
225 | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
226 | CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
227 | CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
228 |
229 | /* Update array items. */
230 | CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
231 | CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
232 | CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
233 | CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
234 | CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
235 |
236 | /* Duplicate a cJSON item */
237 | CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
238 | /* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
239 | need to be released. With recurse!=0, it will duplicate any children connected to the item.
240 | The item->next and ->prev pointers are always zero on return from Duplicate. */
241 | /* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
242 | * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
243 | CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
244 |
245 |
246 | CJSON_PUBLIC(void) cJSON_Minify(char *json);
247 |
248 | /* Helper functions for creating and adding items to an object at the same time.
249 | * They return the added item or NULL on failure. */
250 | CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
251 | CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
252 | CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
253 | CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
254 | CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
255 | CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
256 | CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
257 | CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
258 | CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
259 |
260 | /* When assigning an integer value, it needs to be propagated to valuedouble too. */
261 | #define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
262 | /* helper for the cJSON_SetNumberValue macro */
263 | CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
264 | #define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
265 |
266 | /* Macro for iterating over an array or object */
267 | #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
268 |
269 | /* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
270 | CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
271 | CJSON_PUBLIC(void) cJSON_free(void *object);
272 |
273 | #ifdef __cplusplus
274 | }
275 | #endif
276 |
277 | #endif
278 |
--------------------------------------------------------------------------------
/src/elf2kip.c:
--------------------------------------------------------------------------------
1 | // Copyright 2018 SciresM
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "cJSON.h"
9 | #include "blz.h"
10 | #include "elf64.h"
11 |
12 | typedef struct {
13 | u32 DstOff;
14 | u32 DecompSz;
15 | u32 CompSz;
16 | u32 Attribute;
17 | } KipSegment;
18 |
19 | typedef struct {
20 | u8 Magic[4];
21 | u8 Name[0xC];
22 | u64 ProgramId;
23 | u32 Version;
24 | u8 MainThreadPriority;
25 | u8 DefaultCpuId;
26 | u8 Unk;
27 | u8 Flags;
28 | KipSegment Segments[6];
29 | u32 Capabilities[0x20];
30 | } KipHeader;
31 |
32 | uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
33 | FILE* fd = fopen(fn, "rb");
34 | if (fd == NULL)
35 | return NULL;
36 |
37 | fseek(fd, 0, SEEK_END);
38 | size_t len = ftell(fd);
39 | fseek(fd, 0, SEEK_SET);
40 |
41 | uint8_t* buf = malloc(len);
42 | if (buf == NULL) {
43 | fclose(fd);
44 | return NULL;
45 | }
46 |
47 | size_t rc = fread(buf, 1, len, fd);
48 | if (rc != len) {
49 | fclose(fd);
50 | free(buf);
51 | return NULL;
52 | }
53 |
54 | *len_out = len;
55 | return buf;
56 | }
57 |
58 | int cJSON_GetString(const cJSON *obj, const char *field, const char **out) {
59 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
60 | if (cJSON_IsString(config)) {
61 | *out = config->valuestring;
62 | return 1;
63 | } else {
64 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
65 | return 0;
66 | }
67 | }
68 |
69 | int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
70 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
71 | if (cJSON_IsNumber(config)) {
72 | *out = (u8)config->valueint;
73 | return 1;
74 | } else {
75 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
76 | return 0;
77 | }
78 | }
79 |
80 | int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
81 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
82 | if (cJSON_IsNumber(config)) {
83 | *out = (u16)config->valueint;
84 | return 1;
85 | } else {
86 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
87 | return 0;
88 | }
89 | }
90 |
91 | int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
92 | if (cJSON_IsNumber(config)) {
93 | *out = (u16)config->valueint;
94 | return 1;
95 | } else {
96 | fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
97 | return 0;
98 | }
99 | }
100 |
101 | int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
102 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
103 | if (cJSON_IsBool(config)) {
104 | if (cJSON_IsTrue(config)) {
105 | *out = 1;
106 | } else if (cJSON_IsFalse(config)) {
107 | *out = 0;
108 | } else {
109 | fprintf(stderr, "Unknown boolean value in %s.\n", field);
110 | return 0;
111 | }
112 | return 1;
113 | } else {
114 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
115 | return 0;
116 | }
117 | }
118 |
119 | int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {
120 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
121 | if (cJSON_IsBool(config)) {
122 | if (cJSON_IsTrue(config)) {
123 | *out = 1;
124 | } else if (cJSON_IsFalse(config)) {
125 | *out = 0;
126 | } else {
127 | fprintf(stderr, "Unknown boolean value in %s.\n", field);
128 | return 0;
129 | }
130 | return 1;
131 | } else {
132 | *out = 0;
133 | return 0;
134 | }
135 | }
136 |
137 | int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
138 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
139 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
140 | char *endptr = NULL;
141 | *out = strtoull(config->valuestring, &endptr, 16);
142 | if (config->valuestring == endptr) {
143 | fprintf(stderr, "Failed to get %s (empty string)\n", field);
144 | return 0;
145 | } else if (errno == ERANGE) {
146 | fprintf(stderr, "Failed to get %s (value out of range)\n", field);
147 | return 0;
148 | } else if (errno == EINVAL) {
149 | fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
150 | return 0;
151 | } else if (errno) {
152 | fprintf(stderr, "Failed to get %s (unknown error)\n", field);
153 | return 0;
154 | } else {
155 | return 1;
156 | }
157 | } else {
158 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
159 | return 0;
160 | }
161 | }
162 |
163 | int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
164 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
165 | char *endptr = NULL;
166 | *out = strtoull(config->valuestring, &endptr, 16);
167 | if (config->valuestring == endptr) {
168 | fprintf(stderr, "Failed to get %s (empty string)\n", config->string);
169 | return 0;
170 | } else if (errno == ERANGE) {
171 | fprintf(stderr, "Failed to get %s (value out of range)\n", config->string);
172 | return 0;
173 | } else if (errno == EINVAL) {
174 | fprintf(stderr, "Failed to get %s (not base16 string)\n", config->string);
175 | return 0;
176 | } else if (errno) {
177 | fprintf(stderr, "Failed to get %s (unknown error)\n", config->string);
178 | return 0;
179 | } else {
180 | return 1;
181 | }
182 | } else {
183 | fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
184 | return 0;
185 | }
186 | }
187 |
188 | int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
189 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
190 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
191 | char *endptr = NULL;
192 | *out = strtoul(config->valuestring, &endptr, 16);
193 | if (config->valuestring == endptr) {
194 | fprintf(stderr, "Failed to get %s (empty string)\n", field);
195 | return 0;
196 | } else if (errno == ERANGE) {
197 | fprintf(stderr, "Failed to get %s (value out of range)\n", field);
198 | return 0;
199 | } else if (errno == EINVAL) {
200 | fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
201 | return 0;
202 | } else if (errno) {
203 | fprintf(stderr, "Failed to get %s (unknown error)\n", field);
204 | return 0;
205 | } else {
206 | return 1;
207 | }
208 | } else {
209 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
210 | return 0;
211 | }
212 | }
213 |
214 | int ParseKipConfiguration(const char *json, KipHeader *kip_hdr) {
215 | const cJSON *capability = NULL;
216 | const cJSON *capabilities = NULL;
217 | int status = 0;
218 | cJSON *npdm_json = cJSON_Parse(json);
219 | if (npdm_json == NULL) {
220 | const char *error_ptr = cJSON_GetErrorPtr();
221 | if (error_ptr != NULL) {
222 | fprintf(stderr, "JSON Parse Error: %s\n", error_ptr);
223 | }
224 | status = 0;
225 | goto PARSE_CAPS_END;
226 | }
227 |
228 | /* Parse name. */
229 | const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, "name");
230 | if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {
231 | strncpy(kip_hdr->Name, title_name->valuestring, sizeof(kip_hdr->Name) - 1);
232 | } else {
233 | fprintf(stderr, "Failed to get title name (name field not present).\n");
234 | status = 0;
235 | goto PARSE_CAPS_END;
236 | }
237 |
238 | /* Parse program_id (or deprecated title_id). */
239 | if (!cJSON_GetU64(npdm_json, "program_id", &kip_hdr->ProgramId) && !cJSON_GetU64(npdm_json, "title_id", &kip_hdr->ProgramId)) {
240 | status = 0;
241 | goto PARSE_CAPS_END;
242 | }
243 |
244 | /* Parse use secure memory. */
245 | /* This field is optional, and defaults to true (set before this function is called). */
246 | int use_secure_memory = 1;
247 | if (cJSON_GetBooleanOptional(npdm_json, "use_secure_memory", &use_secure_memory)) {
248 | if (use_secure_memory) {
249 | kip_hdr->Flags |= 0x20;
250 | } else {
251 | kip_hdr->Flags &= ~0x20;
252 | }
253 | }
254 |
255 | /* Parse immortality. */
256 | /* This field is optional, and defaults to true (set before this function is called). */
257 | int immortal = 1;
258 | if (cJSON_GetBooleanOptional(npdm_json, "immortal", &immortal)) {
259 | if (immortal) {
260 | kip_hdr->Flags |= 0x40;
261 | } else {
262 | kip_hdr->Flags &= ~0x40;
263 | }
264 | }
265 |
266 | /* Parse main_thread_stack_size. */
267 | u64 stack_size = 0;
268 | if (!cJSON_GetU64(npdm_json, "main_thread_stack_size", &stack_size)) {
269 | status = 0;
270 | goto PARSE_CAPS_END;
271 | }
272 | if (stack_size >> 32) {
273 | fprintf(stderr, "Error: Main thread stack size must be a u32!\n");
274 | status = 0;
275 | goto PARSE_CAPS_END;
276 | }
277 | kip_hdr->Segments[1].Attribute = (u32)(stack_size & 0xFFFFFFFF);
278 |
279 | /* Parse various config. */
280 | if (!cJSON_GetU8(npdm_json, "main_thread_priority", &kip_hdr->MainThreadPriority)) {
281 | status = 0;
282 | goto PARSE_CAPS_END;
283 | }
284 | if (!cJSON_GetU8(npdm_json, "default_cpu_id", &kip_hdr->DefaultCpuId)) {
285 | status = 0;
286 | goto PARSE_CAPS_END;
287 | }
288 | if (!cJSON_GetU32(npdm_json, "version", &kip_hdr->Version) && !cJSON_GetU32(npdm_json, "process_category", &kip_hdr->Version)) { // optional
289 | kip_hdr->Version = 1;
290 | }
291 |
292 | /* Parse capabilities. */
293 | capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, "kernel_capabilities");
294 | if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {
295 | fprintf(stderr, "Kernel Capabilities must be an array!\n");
296 | status = 0;
297 | goto PARSE_CAPS_END;
298 | }
299 |
300 | int kac_obj = 0;
301 | if (cJSON_IsObject(capabilities)) {
302 | kac_obj = 1;
303 | fprintf(stderr, "Using deprecated kernel_capabilities format. Please turn it into an array.\n");
304 | }
305 |
306 | u32 cur_cap = 0;
307 | u32 desc;
308 | cJSON_ArrayForEach(capability, capabilities) {
309 | desc = 0;
310 | const char *type_str;
311 | const cJSON *value;
312 |
313 | if (kac_obj) {
314 | type_str = capability->string;
315 | value = capability;
316 | } else {
317 | if (!cJSON_GetString(capability, "type", &type_str)) {
318 | status = 0;
319 | goto PARSE_CAPS_END;
320 | }
321 | value = cJSON_GetObjectItemCaseSensitive(capability, "value");
322 | }
323 |
324 |
325 | if (!strcmp(type_str, "kernel_flags")) {
326 | if (cur_cap + 1 > 0x20) {
327 | fprintf(stderr, "Error: Too many capabilities!\n");
328 | status = 0;
329 | goto PARSE_CAPS_END;
330 | }
331 | if (!cJSON_IsObject(value)) {
332 | fprintf(stderr, "Kernel Flags Capability value must be object!\n");
333 | status = 0;
334 | goto PARSE_CAPS_END;
335 | }
336 | u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;
337 | if (!cJSON_GetU8(value, "highest_thread_priority", &highest_prio) ||
338 | !cJSON_GetU8(value, "lowest_thread_priority", &lowest_prio) ||
339 | !cJSON_GetU8(value, "highest_cpu_id", &highest_cpu) ||
340 | !cJSON_GetU8(value, "lowest_cpu_id", &lowest_cpu)) {
341 | status = 0;
342 | goto PARSE_CAPS_END;
343 | }
344 |
345 | u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;
346 | u8 real_lowest_prio = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;
347 |
348 | desc = highest_cpu;
349 | desc <<= 8;
350 | desc |= lowest_cpu;
351 | desc <<= 6;
352 | desc |= (real_highest_prio & 0x3F);
353 | desc <<= 6;
354 | desc |= (real_lowest_prio & 0x3F);
355 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 4) | (0x0007));
356 | } else if (!strcmp(type_str, "syscalls")) {
357 | if (!cJSON_IsObject(value)) {
358 | fprintf(stderr, "Syscalls Capability value must be object!\n");
359 | status = 0;
360 | goto PARSE_CAPS_END;
361 | }
362 | u32 num_descriptors;
363 | u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */
364 | char field_name[8] = {0};
365 | const cJSON *cur_syscall = NULL;
366 | u64 syscall_value = 0;
367 | cJSON_ArrayForEach(cur_syscall, value) {
368 | if (cJSON_IsNumber(cur_syscall)) {
369 | syscall_value = (u64)cur_syscall->valueint;
370 | } else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {
371 | fprintf(stderr, "Error: Syscall entries must be integers or hex strings.\n");
372 | status = 0;
373 | goto PARSE_CAPS_END;
374 | }
375 |
376 | if (syscall_value >= 0xC0) {
377 | fprintf(stderr, "Error: All syscall entries must be numbers in [0, 0xBF]\n");
378 | status = 0;
379 | goto PARSE_CAPS_END;
380 | }
381 | descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));
382 | }
383 | for (unsigned int i = 0; i < 8; i++) {
384 | if (descriptors[i]) {
385 | if (cur_cap + 1 > 0x20) {
386 | fprintf(stderr, "Error: Too many capabilities!\n");
387 | status = 0;
388 | goto PARSE_CAPS_END;
389 | }
390 | desc = descriptors[i] | (i << 24);
391 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 5) | (0x000F));
392 | }
393 | }
394 | } else if (!strcmp(type_str, "map")) {
395 | if (cur_cap + 2 > 0x20) {
396 | fprintf(stderr, "Error: Too many capabilities!\n");
397 | status = 0;
398 | goto PARSE_CAPS_END;
399 | }
400 | if (!cJSON_IsObject(value)) {
401 | fprintf(stderr, "Map Capability value must be object!\n");
402 | status = 0;
403 | goto PARSE_CAPS_END;
404 | }
405 | u64 map_address = 0;
406 | u64 map_size = 0;
407 | int is_ro;
408 | int is_io;
409 | if (!cJSON_GetU64(value, "address", &map_address) ||
410 | !cJSON_GetU64(value, "size", &map_size) ||
411 | !cJSON_GetBoolean(value, "is_ro", &is_ro) ||
412 | !cJSON_GetBoolean(value, "is_io", &is_io)) {
413 | status = 0;
414 | goto PARSE_CAPS_END;
415 | }
416 | desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);
417 | desc |= is_ro << 24;
418 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));
419 |
420 | desc = (u32)((map_size >> 12) & 0x000FFFFFULL);
421 | desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);
422 | is_io ^= 1;
423 | desc |= is_io << 24;
424 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));
425 | } else if (!strcmp(type_str, "map_page")) {
426 | if (cur_cap + 1 > 0x20) {
427 | fprintf(stderr, "Error: Too many capabilities!\n");
428 | status = 0;
429 | goto PARSE_CAPS_END;
430 | }
431 | u64 page_address = 0;
432 | if (!cJSON_GetU64FromObjectValue(value, &page_address)) {
433 | status = 0;
434 | goto PARSE_CAPS_END;
435 | }
436 | desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);
437 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 8) | (0x007F));
438 | } else if (!strcmp(type_str, "map_region")) {
439 | if (cur_cap + 1 > 0x20) {
440 | fprintf(stderr, "Error: Too many capabilities!\n");
441 | status = 0;
442 | goto PARSE_CAPS_END;
443 | }
444 | if (!cJSON_IsArray(value)) {
445 | fprintf(stderr, "Map Region capability value must be array!\n");
446 | status = 0;
447 | goto PARSE_CAPS_END;
448 | }
449 | u8 regions[3] = {0};
450 | int is_ro[3] = {0};
451 | const cJSON *cur_region = NULL;
452 | int index = 0;
453 | cJSON_ArrayForEach(cur_region, value) {
454 | if (index >= 3) {
455 | fprintf(stderr, "Too many region descriptors!\n");
456 | status = 0;
457 | goto PARSE_CAPS_END;
458 | }
459 | if (!cJSON_IsObject(cur_region)) {
460 | fprintf(stderr, "Region descriptor value must be object!\n");
461 | status = 0;
462 | goto PARSE_CAPS_END;
463 | }
464 |
465 | if (!cJSON_GetU8(cur_region, "region_type", ®ions[index]) ||
466 | !cJSON_GetBoolean(cur_region, "is_ro", &is_ro[index])) {
467 | status = 0;
468 | goto PARSE_CAPS_END;
469 | }
470 |
471 | index++;
472 | }
473 |
474 | u32 capability = 0x3FF;
475 | for (int i = 0; i < 3; ++i) {
476 | capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);
477 | }
478 | kip_hdr->Capabilities[cur_cap++] = capability;
479 | } else if (!strcmp(type_str, "irq_pair")) {
480 | if (cur_cap + 1 > 0x20) {
481 | fprintf(stderr, "Error: Too many capabilities!\n");
482 | status = 0;
483 | goto PARSE_CAPS_END;
484 | }
485 | if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {
486 | fprintf(stderr, "Error: IRQ Pairs must have size 2 array value.\n");
487 | status = 0;
488 | goto PARSE_CAPS_END;
489 | }
490 | const cJSON *irq = NULL;
491 | int desc_idx = 0;
492 | cJSON_ArrayForEach(irq, value) {
493 | if (cJSON_IsNull(irq)) {
494 | desc |= 0x3FF << desc_idx;
495 | } else if (cJSON_IsNumber(irq)) {
496 | desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;
497 | } else {
498 | fprintf(stderr, "Failed to parse IRQ value.\n");
499 | status = 0;
500 | goto PARSE_CAPS_END;
501 | }
502 | desc_idx += 10;
503 | }
504 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 12) | (0x07FF));
505 | } else if (!strcmp(type_str, "application_type")) {
506 | if (cur_cap + 1 > 0x20) {
507 | fprintf(stderr, "Error: Too many capabilities!\n");
508 | status = 0;
509 | goto PARSE_CAPS_END;
510 | }
511 | if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
512 | status = 0;
513 | goto PARSE_CAPS_END;
514 | }
515 | desc &= 7;
516 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 14) | (0x1FFF));
517 | } else if (!strcmp(type_str, "min_kernel_version")) {
518 | if (cur_cap + 1 > 0x20) {
519 | fprintf(stderr, "Error: Too many capabilities!\n");
520 | status = 0;
521 | goto PARSE_CAPS_END;
522 | }
523 | u64 kern_ver = 0;
524 | if (cJSON_IsNumber(value)) {
525 | kern_ver = (u64)value->valueint;
526 | } else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {
527 | fprintf(stderr, "Error: Kernel version must be integer or hex strings.\n");
528 | status = 0;
529 | goto PARSE_CAPS_END;
530 | }
531 | desc = (kern_ver) & 0xFFFF;
532 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 15) | (0x3FFF));
533 | } else if (!strcmp(type_str, "handle_table_size")) {
534 | if (cur_cap + 1 > 0x20) {
535 | fprintf(stderr, "Error: Too many capabilities!\n");
536 | status = 0;
537 | goto PARSE_CAPS_END;
538 | }
539 | if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
540 | status = 0;
541 | goto PARSE_CAPS_END;
542 | }
543 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 16) | (0x7FFF));
544 | } else if (!strcmp(type_str, "debug_flags")) {
545 | if (cur_cap + 1 > 0x20) {
546 | fprintf(stderr, "Error: Too many capabilities!\n");
547 | status = 0;
548 | goto PARSE_CAPS_END;
549 | }
550 | if (!cJSON_IsObject(value)) {
551 | fprintf(stderr, "Debug Flag Capability value must be object!\n");
552 | status = 0;
553 | goto PARSE_CAPS_END;
554 | }
555 | int allow_debug = 0;
556 | int force_debug = 0;
557 | int force_debug_prod = 0;
558 | if (!cJSON_GetBoolean(value, "allow_debug", &allow_debug)) {
559 | status = 0;
560 | goto PARSE_CAPS_END;
561 | }
562 | if (!cJSON_GetBoolean(value, "force_debug", &force_debug)) {
563 | status = 0;
564 | goto PARSE_CAPS_END;
565 | }
566 | if (!cJSON_GetBoolean(value, "force_debug_prod", &force_debug_prod)) {
567 | status = 0;
568 | goto PARSE_CAPS_END;
569 | }
570 | desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);
571 | kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 17) | (0xFFFF));
572 | } else {
573 | fprintf(stderr, "Error: unknown capability %s\n", type_str);
574 | status = 0;
575 | goto PARSE_CAPS_END;
576 | }
577 | }
578 |
579 | for (u32 i = cur_cap; i < 0x20; i++) {
580 | kip_hdr->Capabilities[i] = 0xFFFFFFFF;
581 | }
582 |
583 | status = 1;
584 | PARSE_CAPS_END:
585 | cJSON_Delete(npdm_json);
586 | return status;
587 | }
588 |
589 | int main(int argc, char* argv[]) {
590 | if (argc != 4) {
591 | fprintf(stderr, "%s \n", argv[0]);
592 | return EXIT_FAILURE;
593 | }
594 |
595 | KipHeader kip_hdr = {0};
596 | memcpy(kip_hdr.Magic, "KIP1", 4);
597 | kip_hdr.Flags = 0x7F;
598 |
599 | if (sizeof(KipHeader) != 0x100) {
600 | fprintf(stderr, "Bad compile environment!\n");
601 | return EXIT_FAILURE;
602 | }
603 |
604 | size_t json_len;
605 | uint8_t* json = ReadEntireFile(argv[2], &json_len);
606 | if (json == NULL) {
607 | fprintf(stderr, "Failed to read descriptor json!\n");
608 | return EXIT_FAILURE;
609 | }
610 |
611 | if (!ParseKipConfiguration(json, &kip_hdr)) {
612 | fprintf(stderr, "Failed to parse kip configuration!\n");
613 | return EXIT_FAILURE;
614 | }
615 |
616 | size_t elf_len;
617 | uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
618 | if (elf == NULL) {
619 | fprintf(stderr, "Failed to open input!\n");
620 | return EXIT_FAILURE;
621 | }
622 |
623 | if (elf_len < sizeof(Elf64_Ehdr)) {
624 | fprintf(stderr, "Input file doesn't fit ELF header!\n");
625 | return EXIT_FAILURE;
626 | }
627 |
628 | Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
629 | if (hdr->e_machine != EM_AARCH64) {
630 | fprintf(stderr, "Invalid ELF: expected AArch64!\n");
631 | return EXIT_FAILURE;
632 | }
633 |
634 | Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
635 |
636 | if (ph_end < hdr->e_phoff || ph_end > elf_len) {
637 | fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
638 | return EXIT_FAILURE;
639 | }
640 |
641 | Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
642 | size_t i, j = 0;
643 | size_t file_off = 0;
644 | size_t dst_off = 0;
645 | size_t tmpsize;
646 |
647 | uint8_t* buf[3];
648 | uint8_t* cmp[3];
649 | size_t FileOffsets[3];
650 |
651 | for (i=0; i<4; i++) {
652 | Elf64_Phdr* phdr = NULL;
653 | while (j < hdr->e_phnum) {
654 | Elf64_Phdr* cur = &phdrs[j];
655 | if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
656 | if (cur->p_type == PT_LOAD || i == 3) {
657 | phdr = cur;
658 | break;
659 | }
660 | }
661 |
662 | if (phdr == NULL) {
663 | fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
664 | return EXIT_FAILURE;
665 | }
666 |
667 |
668 | kip_hdr.Segments[i].DstOff = dst_off;
669 |
670 | // .bss is special
671 | if (i == 3) {
672 | tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
673 | if ( phdr->p_memsz > tmpsize) {
674 | kip_hdr.Segments[i].DecompSz = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
675 | } else {
676 | kip_hdr.Segments[i].DecompSz = 0;
677 | }
678 | kip_hdr.Segments[i].CompSz = 0;
679 | break;
680 | }
681 |
682 | FileOffsets[i] = file_off;
683 | kip_hdr.Segments[i].DecompSz = phdr->p_filesz;
684 | buf[i] = malloc(kip_hdr.Segments[i].DecompSz);
685 |
686 | if (buf[i] == NULL) {
687 | fprintf(stderr, "Out of memory!\n");
688 | return EXIT_FAILURE;
689 | }
690 |
691 | memset(buf[i], 0, kip_hdr.Segments[i].DecompSz);
692 |
693 | memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);
694 | cmp[i] = BLZ_Code(buf[i], phdr->p_filesz, &kip_hdr.Segments[i].CompSz, BLZ_BEST);
695 |
696 | file_off += kip_hdr.Segments[i].CompSz;
697 | dst_off += kip_hdr.Segments[i].DecompSz;
698 | dst_off = (dst_off + 0xFFF) & ~0xFFF;
699 | }
700 |
701 | FILE* out = fopen(argv[3], "wb");
702 |
703 | if (out == NULL) {
704 | fprintf(stderr, "Failed to open output file!\n");
705 | return EXIT_FAILURE;
706 | }
707 |
708 | // TODO check retvals
709 |
710 | for (i=0; i<3; i++)
711 | {
712 | fseek(out, sizeof(kip_hdr) + FileOffsets[i], SEEK_SET);
713 | fwrite(cmp[i], kip_hdr.Segments[i].CompSz, 1, out);
714 | }
715 |
716 | fseek(out, 0, SEEK_SET);
717 | fwrite(&kip_hdr, sizeof(kip_hdr), 1, out);
718 |
719 | fclose(out);
720 | return EXIT_SUCCESS;
721 | }
722 |
--------------------------------------------------------------------------------
/src/elf2nro.c:
--------------------------------------------------------------------------------
1 | // Copyright 2017 plutoo
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include "sha256.h"
8 | #include "elf64.h"
9 | #include "romfs.h"
10 |
11 | typedef struct {
12 | u32 FileOff;
13 | u32 Size;
14 | } NsoSegment;
15 |
16 | typedef struct {
17 | u32 unused;
18 | u32 modOffset;
19 | u8 Padding[8];
20 | } NroStart;
21 |
22 | typedef struct {
23 | u8 Magic[4];
24 | u32 version;
25 | u32 size;
26 | u32 flags;
27 | NsoSegment Segments[3];
28 | u32 bssSize;
29 | u32 Unk3;
30 | u8 BuildId[0x20];
31 | u8 Padding[0x20];
32 | } NroHeader;
33 |
34 | typedef struct {
35 | u64 offset;
36 | u64 size;
37 | } AssetSection;
38 |
39 | typedef struct {
40 | u8 magic[4];
41 | u32 version;
42 | AssetSection icon;
43 | AssetSection nacp;
44 | AssetSection romfs;
45 | } AssetHeader;
46 |
47 | uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
48 | FILE* fd = fopen(fn, "rb");
49 | if (fd == NULL)
50 | return NULL;
51 |
52 | fseek(fd, 0, SEEK_END);
53 | size_t len = ftell(fd);
54 | fseek(fd, 0, SEEK_SET);
55 |
56 | uint8_t* buf = malloc(len);
57 | if (buf == NULL) {
58 | fclose(fd);
59 | return NULL;
60 | }
61 |
62 | size_t rc = fread(buf, 1, len, fd);
63 | if (rc != len) {
64 | fclose(fd);
65 | free(buf);
66 | return NULL;
67 | }
68 |
69 | *len_out = len;
70 | return buf;
71 | }
72 |
73 | int main(int argc, char* argv[]) {
74 | if (argc < 3) {
75 | fprintf(stderr, "%s [options]\n\n", argv[0]);
76 | fprintf(stderr, "Options:\n");
77 | fprintf(stderr, "--icon= Embeds icon into the output file.\n");
78 | fprintf(stderr, "--nacp= Embeds control.nacp into the output file.\n");
79 | fprintf(stderr, "--romfs= Embeds RomFS into the output file.\n");
80 | fprintf(stderr, "--romfsdir= Builds and embeds RomFS into the output file.\n");
81 | fprintf(stderr, "--alignedheader Sets the \"AlignedHeader\" flag in the output file.\n");
82 | return EXIT_FAILURE;
83 | }
84 |
85 | NroStart nro_start;
86 | memset(&nro_start, 0, sizeof(nro_start));
87 |
88 | NroHeader nro_hdr;
89 | memset(&nro_hdr, 0, sizeof(nro_hdr));
90 | memcpy(nro_hdr.Magic, "NRO0", 4);
91 |
92 | if (sizeof(NroHeader) != 0x70) {
93 | fprintf(stderr, "Bad compile environment!\n");
94 | return EXIT_FAILURE;
95 | }
96 |
97 | size_t elf_len;
98 | uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
99 | if (elf == NULL) {
100 | fprintf(stderr, "Failed to open input!\n");
101 | return EXIT_FAILURE;
102 | }
103 |
104 | int argi;
105 | char* icon_path = NULL, *nacp_path = NULL, *romfs_path = NULL, *romfs_dir_path = NULL;
106 | u32 aligned_header = 0;
107 | for (argi=3; argie_machine != EM_AARCH64) {
127 | fprintf(stderr, "Invalid ELF: expected AArch64!\n");
128 | return EXIT_FAILURE;
129 | }
130 |
131 | Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
132 |
133 | if (ph_end < hdr->e_phoff || ph_end > elf_len) {
134 | fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
135 | return EXIT_FAILURE;
136 | }
137 |
138 | Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
139 | size_t i, j = 0;
140 | size_t file_off = 0;
141 | size_t tmpsize;
142 |
143 | uint8_t* buf[3];
144 |
145 | for (i=0; i<4; i++) {
146 | Elf64_Phdr* phdr = NULL;
147 | while (j < hdr->e_phnum) {
148 | Elf64_Phdr* cur = &phdrs[j];
149 | if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
150 | if (cur->p_type == PT_LOAD || i == 3) {
151 | phdr = cur;
152 | break;
153 | }
154 | }
155 |
156 | if (phdr == NULL) {
157 | fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
158 | return EXIT_FAILURE;
159 | }
160 |
161 | // .bss is special
162 | if (i == 3) {
163 | tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
164 | if ( phdr->p_memsz > tmpsize)
165 | nro_hdr.bssSize = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
166 | else
167 | nro_hdr.bssSize = 0;
168 | break;
169 | }
170 |
171 | nro_hdr.Segments[i].FileOff = phdr->p_vaddr;
172 | nro_hdr.Segments[i].Size = (phdr->p_filesz + 0xFFF) & ~0xFFF;
173 | buf[i] = malloc(nro_hdr.Segments[i].Size);
174 | memset(buf[i], 0, nro_hdr.Segments[i].Size);
175 |
176 | if (buf[i] == NULL) {
177 | fprintf(stderr, "Out of memory!\n");
178 | return EXIT_FAILURE;
179 | }
180 |
181 | memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);
182 |
183 | file_off += nro_hdr.Segments[i].Size;
184 | file_off = (file_off + 0xFFF) & ~0xFFF;
185 | }
186 |
187 | /* Iterate over sections to find build id. */
188 | size_t cur_sect_hdr_ofs = hdr->e_shoff;
189 | for (unsigned int i = 0; i < hdr->e_shnum; i++) {
190 | Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
191 | if (cur_shdr->sh_type == SHT_NOTE) {
192 | Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
193 | u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
194 | u8 *note_desc = note_name + note_hdr->n_namesz;
195 | if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
196 | size_t build_id_size = note_hdr->n_descsz;
197 | if (build_id_size > 0x20) {
198 | build_id_size = 0x20;
199 | }
200 | memcpy(nro_hdr.BuildId, note_desc, build_id_size);
201 | }
202 | }
203 | cur_sect_hdr_ofs += hdr->e_shentsize;
204 | }
205 |
206 | FILE* out = fopen(argv[2], "wb");
207 |
208 | if (out == NULL) {
209 | fprintf(stderr, "Failed to open output file!\n");
210 | return EXIT_FAILURE;
211 | }
212 |
213 | nro_hdr.size = file_off;
214 |
215 | nro_hdr.version = 0;
216 | nro_hdr.flags = (aligned_header << 0);
217 |
218 | // TODO check retvals
219 |
220 | for (i=0; i<3; i++)
221 | {
222 | fseek(out, nro_hdr.Segments[i].FileOff, SEEK_SET);
223 | fwrite(buf[i], nro_hdr.Segments[i].Size, 1, out);
224 | }
225 |
226 | fseek(out, sizeof(nro_start), SEEK_SET);
227 | fwrite(&nro_hdr, sizeof(nro_hdr), 1, out);
228 |
229 | if (icon_path==NULL && nacp_path==NULL && romfs_path==NULL) {
230 | fclose(out);
231 | return EXIT_SUCCESS;
232 | }
233 |
234 | AssetHeader asset_hdr;
235 | memset(&asset_hdr, 0, sizeof(asset_hdr));
236 | memcpy(asset_hdr.magic, "ASET", 4);
237 | asset_hdr.version = 0;
238 |
239 | fseek(out, file_off, SEEK_SET);
240 |
241 | uint8_t* icon = NULL, *nacp = NULL, *romfs = NULL;
242 | size_t icon_len = 0, nacp_len = 0, romfs_len = 0;
243 | size_t tmp_off = sizeof(asset_hdr);
244 |
245 | if (icon_path) {
246 | icon = ReadEntireFile(icon_path, &icon_len);
247 | if (icon == NULL) {
248 | fprintf(stderr, "Failed to open input icon!\n");
249 | return EXIT_FAILURE;
250 | }
251 |
252 | asset_hdr.icon.offset = tmp_off;
253 | asset_hdr.icon.size = icon_len;
254 | tmp_off+= icon_len;
255 | }
256 |
257 | if (nacp_path) {
258 | nacp = ReadEntireFile(nacp_path, &nacp_len);
259 | if (nacp == NULL) {
260 | fprintf(stderr, "Failed to open input nacp!\n");
261 | return EXIT_FAILURE;
262 | }
263 |
264 | asset_hdr.nacp.offset = tmp_off;
265 | asset_hdr.nacp.size = nacp_len;
266 | tmp_off+= nacp_len;
267 | }
268 |
269 | if (romfs_path) {
270 | romfs = ReadEntireFile(romfs_path, &romfs_len);
271 | if (romfs == NULL) {
272 | fprintf(stderr, "Failed to open input romfs!\n");
273 | return EXIT_FAILURE;
274 | }
275 |
276 | asset_hdr.romfs.offset = tmp_off;
277 | asset_hdr.romfs.size = romfs_len;
278 | tmp_off+= romfs_len;
279 |
280 | } else if (romfs_dir_path) {
281 | asset_hdr.romfs.offset = tmp_off;
282 | asset_hdr.romfs.size = build_romfs_by_path_into_file(romfs_dir_path, out, file_off + tmp_off);
283 | tmp_off+= asset_hdr.romfs.size;
284 | fseek(out, file_off, SEEK_SET);
285 | }
286 |
287 | fwrite(&asset_hdr, sizeof(asset_hdr), 1, out);
288 |
289 | if (icon_path) {
290 | fseek(out, file_off + asset_hdr.icon.offset, SEEK_SET);
291 | fwrite(icon, icon_len, 1, out);
292 | }
293 |
294 | if (nacp_path) {
295 | fseek(out, file_off + asset_hdr.nacp.offset, SEEK_SET);
296 | fwrite(nacp, nacp_len, 1, out);
297 | }
298 |
299 | if (romfs_path) {
300 | fseek(out, file_off + asset_hdr.romfs.offset, SEEK_SET);
301 | fwrite(romfs, romfs_len, 1, out);
302 | }
303 |
304 | fclose(out);
305 |
306 | return EXIT_SUCCESS;
307 | }
308 |
--------------------------------------------------------------------------------
/src/elf2nso.c:
--------------------------------------------------------------------------------
1 | // Copyright 2017 plutoo
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include "sha256.h"
8 | #include "elf64.h"
9 |
10 | typedef uint64_t u64;
11 | typedef uint32_t u32;
12 | typedef uint8_t u8;
13 |
14 | typedef struct {
15 | u32 FileOff;
16 | u32 DstOff;
17 | u32 DecompSz;
18 | u32 AlignOrTotalSz;
19 | } NsoSegment;
20 |
21 | typedef u8 Sha2Hash[0x20];
22 |
23 | typedef struct {
24 | u8 Magic[4];
25 | u32 Unk1;
26 | u32 Unk2;
27 | u32 Unk3;
28 | NsoSegment Segments[3];
29 | u8 BuildId[0x20];
30 | u32 CompSz[3];
31 | u8 Padding[0x24];
32 | u64 Unk4;
33 | u64 Unk5;
34 | Sha2Hash Hashes[3];
35 | } NsoHeader;
36 |
37 | uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
38 | FILE* fd = fopen(fn, "rb");
39 | if (fd == NULL)
40 | return NULL;
41 |
42 | fseek(fd, 0, SEEK_END);
43 | size_t len = ftell(fd);
44 | fseek(fd, 0, SEEK_SET);
45 |
46 | uint8_t* buf = malloc(len);
47 | if (buf == NULL) {
48 | fclose(fd);
49 | return NULL;
50 | }
51 |
52 | size_t rc = fread(buf, 1, len, fd);
53 | if (rc != len) {
54 | fclose(fd);
55 | free(buf);
56 | return NULL;
57 | }
58 |
59 | *len_out = len;
60 | return buf;
61 | }
62 |
63 | int main(int argc, char* argv[]) {
64 | if (argc != 3) {
65 | fprintf(stderr, "%s \n", argv[0]);
66 | return EXIT_FAILURE;
67 | }
68 |
69 | NsoHeader nso_hdr;
70 | memset(&nso_hdr, 0, sizeof(nso_hdr));
71 | memcpy(nso_hdr.Magic, "NSO0", 4);
72 | nso_hdr.Unk3 = 0x3f;
73 |
74 | if (sizeof(NsoHeader) != 0x100) {
75 | fprintf(stderr, "Bad compile environment!\n");
76 | return EXIT_FAILURE;
77 | }
78 |
79 | size_t elf_len;
80 | uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
81 | if (elf == NULL) {
82 | fprintf(stderr, "Failed to open input!\n");
83 | return EXIT_FAILURE;
84 | }
85 |
86 | if (elf_len < sizeof(Elf64_Ehdr)) {
87 | fprintf(stderr, "Input file doesn't fit ELF header!\n");
88 | return EXIT_FAILURE;
89 | }
90 |
91 | Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
92 | if (hdr->e_machine != EM_AARCH64) {
93 | fprintf(stderr, "Invalid ELF: expected AArch64!\n");
94 | return EXIT_FAILURE;
95 | }
96 |
97 | Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
98 |
99 | if (ph_end < hdr->e_phoff || ph_end > elf_len) {
100 | fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
101 | return EXIT_FAILURE;
102 | }
103 |
104 | Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
105 | size_t i, j = 0;
106 | size_t file_off = sizeof(NsoHeader);
107 |
108 | uint8_t* comp_buf[3];
109 | int comp_sz[3];
110 |
111 | for (i=0; i<3; i++) {
112 | Elf64_Phdr* phdr = NULL;
113 | while (j < hdr->e_phnum) {
114 | Elf64_Phdr* cur = &phdrs[j++];
115 | if (cur->p_type == PT_LOAD) {
116 | phdr = cur;
117 | break;
118 | }
119 | }
120 |
121 | if (phdr == NULL) {
122 | fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs!\n");
123 | return EXIT_FAILURE;
124 | }
125 |
126 | nso_hdr.Segments[i].FileOff = file_off;
127 | nso_hdr.Segments[i].DstOff = phdr->p_vaddr;
128 | nso_hdr.Segments[i].DecompSz = phdr->p_filesz;
129 |
130 | // for .data segment this field contains bss size
131 | if (i == 2)
132 | nso_hdr.Segments[i].AlignOrTotalSz = phdr->p_memsz - phdr->p_filesz;
133 | else
134 | nso_hdr.Segments[i].AlignOrTotalSz = 1;
135 |
136 | SHA256_CTX ctx;
137 | sha256_init(&ctx);
138 | sha256_update(&ctx, &elf[phdr->p_offset], phdr->p_filesz);
139 | sha256_final(&ctx, (u8*) &nso_hdr.Hashes[i]);
140 |
141 | size_t comp_max = LZ4_compressBound(phdr->p_filesz);
142 | comp_buf[i] = malloc(comp_max);
143 |
144 | if (comp_buf[i] == NULL) {
145 | fprintf(stderr, "Compressing: Out of memory!\n");
146 | return EXIT_FAILURE;
147 | }
148 |
149 | // TODO check p_offset
150 | comp_sz[i] = LZ4_compress_default(&elf[phdr->p_offset], comp_buf[i], phdr->p_filesz, comp_max);
151 |
152 | if (comp_sz[i] < 0) {
153 | fprintf(stderr, "Failed to compress!\n");
154 | return EXIT_FAILURE;
155 | }
156 |
157 | nso_hdr.CompSz[i] = comp_sz[i];
158 | file_off += comp_sz[i];
159 | }
160 |
161 | /* Iterate over sections to find build id. */
162 | size_t cur_sect_hdr_ofs = hdr->e_shoff;
163 | for (unsigned int i = 0; i < hdr->e_shnum; i++) {
164 | Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
165 | if (cur_shdr->sh_type == SHT_NOTE) {
166 | Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
167 | u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
168 | u8 *note_desc = note_name + note_hdr->n_namesz;
169 | if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
170 | size_t build_id_size = note_hdr->n_descsz;
171 | if (build_id_size > 0x20) {
172 | build_id_size = 0x20;
173 | }
174 | memcpy(nso_hdr.BuildId, note_desc, build_id_size);
175 | }
176 | }
177 | cur_sect_hdr_ofs += hdr->e_shentsize;
178 | }
179 |
180 | FILE* out = fopen(argv[2], "wb");
181 |
182 | if (out == NULL) {
183 | fprintf(stderr, "Failed to open output file!\n");
184 | return EXIT_FAILURE;
185 | }
186 |
187 | // TODO check retvals
188 | fwrite(&nso_hdr, sizeof(nso_hdr), 1, out);
189 |
190 | for (i=0; i<3; i++)
191 | fwrite(comp_buf[i], comp_sz[i], 1, out);
192 |
193 | return EXIT_SUCCESS;
194 | }
195 |
--------------------------------------------------------------------------------
/src/elf64.h:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright (c) 1996-1998 John D. Polstra.
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions
7 | * are met:
8 | * 1. Redistributions of source code must retain the above copyright
9 | * notice, this list of conditions and the following disclaimer.
10 | * 2. Redistributions in binary form must reproduce the above copyright
11 | * notice, this list of conditions and the following disclaimer in the
12 | * documentation and/or other materials provided with the distribution.
13 | *
14 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 | * SUCH DAMAGE.
25 | *
26 | * $FreeBSD: head/sys/sys/elf64.h 186667 2009-01-01 02:08:56Z obrien $
27 | */
28 |
29 | #ifndef _SYS_ELF64_H_
30 | #define _SYS_ELF64_H_ 1
31 |
32 | #include "elf_common.h"
33 |
34 | /*
35 | * ELF definitions common to all 64-bit architectures.
36 | */
37 |
38 | typedef uint64_t Elf64_Addr;
39 | typedef uint16_t Elf64_Half;
40 | typedef uint64_t Elf64_Off;
41 | typedef int32_t Elf64_Sword;
42 | typedef int64_t Elf64_Sxword;
43 | typedef uint32_t Elf64_Word;
44 | typedef uint64_t Elf64_Lword;
45 | typedef uint64_t Elf64_Xword;
46 |
47 | /*
48 | * Types of dynamic symbol hash table bucket and chain elements.
49 | *
50 | * This is inconsistent among 64 bit architectures, so a machine dependent
51 | * typedef is required.
52 | */
53 |
54 | typedef Elf64_Word Elf64_Hashelt;
55 |
56 | /* Non-standard class-dependent datatype used for abstraction. */
57 | typedef Elf64_Xword Elf64_Size;
58 | typedef Elf64_Sxword Elf64_Ssize;
59 |
60 | /*
61 | * ELF header.
62 | */
63 |
64 | typedef struct {
65 | unsigned char e_ident[EI_NIDENT]; /* File identification. */
66 | Elf64_Half e_type; /* File type. */
67 | Elf64_Half e_machine; /* Machine architecture. */
68 | Elf64_Word e_version; /* ELF format version. */
69 | Elf64_Addr e_entry; /* Entry point. */
70 | Elf64_Off e_phoff; /* Program header file offset. */
71 | Elf64_Off e_shoff; /* Section header file offset. */
72 | Elf64_Word e_flags; /* Architecture-specific flags. */
73 | Elf64_Half e_ehsize; /* Size of ELF header in bytes. */
74 | Elf64_Half e_phentsize; /* Size of program header entry. */
75 | Elf64_Half e_phnum; /* Number of program header entries. */
76 | Elf64_Half e_shentsize; /* Size of section header entry. */
77 | Elf64_Half e_shnum; /* Number of section header entries. */
78 | Elf64_Half e_shstrndx; /* Section name strings section. */
79 | } Elf64_Ehdr;
80 |
81 | /*
82 | * Section header.
83 | */
84 |
85 | typedef struct {
86 | Elf64_Word sh_name; /* Section name (index into the
87 | section header string table). */
88 | Elf64_Word sh_type; /* Section type. */
89 | Elf64_Xword sh_flags; /* Section flags. */
90 | Elf64_Addr sh_addr; /* Address in memory image. */
91 | Elf64_Off sh_offset; /* Offset in file. */
92 | Elf64_Xword sh_size; /* Size in bytes. */
93 | Elf64_Word sh_link; /* Index of a related section. */
94 | Elf64_Word sh_info; /* Depends on section type. */
95 | Elf64_Xword sh_addralign; /* Alignment in bytes. */
96 | Elf64_Xword sh_entsize; /* Size of each entry in section. */
97 | } Elf64_Shdr;
98 |
99 | /*
100 | * Program header.
101 | */
102 |
103 | typedef struct {
104 | Elf64_Word p_type; /* Entry type. */
105 | Elf64_Word p_flags; /* Access permission flags. */
106 | Elf64_Off p_offset; /* File offset of contents. */
107 | Elf64_Addr p_vaddr; /* Virtual address in memory image. */
108 | Elf64_Addr p_paddr; /* Physical address (not used). */
109 | Elf64_Xword p_filesz; /* Size of contents in file. */
110 | Elf64_Xword p_memsz; /* Size of contents in memory. */
111 | Elf64_Xword p_align; /* Alignment in memory and file. */
112 | } Elf64_Phdr;
113 |
114 | /*
115 | * Dynamic structure. The ".dynamic" section contains an array of them.
116 | */
117 |
118 | typedef struct {
119 | Elf64_Sxword d_tag; /* Entry type. */
120 | union {
121 | Elf64_Xword d_val; /* Integer value. */
122 | Elf64_Addr d_ptr; /* Address value. */
123 | } d_un;
124 | } Elf64_Dyn;
125 |
126 | /*
127 | * Relocation entries.
128 | */
129 |
130 | /* Relocations that don't need an addend field. */
131 | typedef struct {
132 | Elf64_Addr r_offset; /* Location to be relocated. */
133 | Elf64_Xword r_info; /* Relocation type and symbol index. */
134 | } Elf64_Rel;
135 |
136 | /* Relocations that need an addend field. */
137 | typedef struct {
138 | Elf64_Addr r_offset; /* Location to be relocated. */
139 | Elf64_Xword r_info; /* Relocation type and symbol index. */
140 | Elf64_Sxword r_addend; /* Addend. */
141 | } Elf64_Rela;
142 |
143 | /* Macros for accessing the fields of r_info. */
144 | #define ELF64_R_SYM(info) ((info) >> 32)
145 | #define ELF64_R_TYPE(info) ((info) & 0xffffffffL)
146 |
147 | /* Macro for constructing r_info from field values. */
148 | #define ELF64_R_INFO(sym, type) (((sym) << 32) + ((type) & 0xffffffffL))
149 |
150 | #define ELF64_R_TYPE_DATA(info) (((Elf64_Xword)(info)<<32)>>40)
151 | #define ELF64_R_TYPE_ID(info) (((Elf64_Xword)(info)<<56)>>56)
152 | #define ELF64_R_TYPE_INFO(data, type) \
153 | (((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))
154 |
155 | /*
156 | * Note entry header
157 | */
158 | typedef Elf_Note Elf64_Nhdr;
159 |
160 | /*
161 | * Move entry
162 | */
163 | typedef struct {
164 | Elf64_Lword m_value; /* symbol value */
165 | Elf64_Xword m_info; /* size + index */
166 | Elf64_Xword m_poffset; /* symbol offset */
167 | Elf64_Half m_repeat; /* repeat count */
168 | Elf64_Half m_stride; /* stride info */
169 | } Elf64_Move;
170 |
171 | #define ELF64_M_SYM(info) ((info)>>8)
172 | #define ELF64_M_SIZE(info) ((unsigned char)(info))
173 | #define ELF64_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))
174 |
175 | /*
176 | * Hardware/Software capabilities entry
177 | */
178 | typedef struct {
179 | Elf64_Xword c_tag; /* how to interpret value */
180 | union {
181 | Elf64_Xword c_val;
182 | Elf64_Addr c_ptr;
183 | } c_un;
184 | } Elf64_Cap;
185 |
186 | /*
187 | * Symbol table entries.
188 | */
189 |
190 | typedef struct {
191 | Elf64_Word st_name; /* String table index of name. */
192 | unsigned char st_info; /* Type and binding information. */
193 | unsigned char st_other; /* Reserved (not used). */
194 | Elf64_Half st_shndx; /* Section index of symbol. */
195 | Elf64_Addr st_value; /* Symbol value. */
196 | Elf64_Xword st_size; /* Size of associated object. */
197 | } Elf64_Sym;
198 |
199 | /* Macros for accessing the fields of st_info. */
200 | #define ELF64_ST_BIND(info) ((info) >> 4)
201 | #define ELF64_ST_TYPE(info) ((info) & 0xf)
202 |
203 | /* Macro for constructing st_info from field values. */
204 | #define ELF64_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
205 |
206 | /* Macro for accessing the fields of st_other. */
207 | #define ELF64_ST_VISIBILITY(oth) ((oth) & 0x3)
208 |
209 | /* Structures used by Sun & GNU-style symbol versioning. */
210 | typedef struct {
211 | Elf64_Half vd_version;
212 | Elf64_Half vd_flags;
213 | Elf64_Half vd_ndx;
214 | Elf64_Half vd_cnt;
215 | Elf64_Word vd_hash;
216 | Elf64_Word vd_aux;
217 | Elf64_Word vd_next;
218 | } Elf64_Verdef;
219 |
220 | typedef struct {
221 | Elf64_Word vda_name;
222 | Elf64_Word vda_next;
223 | } Elf64_Verdaux;
224 |
225 | typedef struct {
226 | Elf64_Half vn_version;
227 | Elf64_Half vn_cnt;
228 | Elf64_Word vn_file;
229 | Elf64_Word vn_aux;
230 | Elf64_Word vn_next;
231 | } Elf64_Verneed;
232 |
233 | typedef struct {
234 | Elf64_Word vna_hash;
235 | Elf64_Half vna_flags;
236 | Elf64_Half vna_other;
237 | Elf64_Word vna_name;
238 | Elf64_Word vna_next;
239 | } Elf64_Vernaux;
240 |
241 | typedef Elf64_Half Elf64_Versym;
242 |
243 | typedef struct {
244 | Elf64_Half si_boundto; /* direct bindings - symbol bound to */
245 | Elf64_Half si_flags; /* per symbol flags */
246 | } Elf64_Syminfo;
247 |
248 | #endif /* !_SYS_ELF64_H_ */
249 |
--------------------------------------------------------------------------------
/src/filepath.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | #ifdef _WIN32
8 | #define WIN32_LEAN_AND_MEAN
9 | #include
10 | #endif
11 |
12 | #include "types.h"
13 | #include "filepath.h"
14 |
15 | void os_strncpy(oschar_t *dst, const char *src, size_t size) {
16 | #ifdef _WIN32
17 | MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size);
18 | #else
19 | strncpy(dst, src, size);
20 | #endif
21 | }
22 |
23 | void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size) {
24 | #ifdef _WIN32
25 | WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, size, NULL, NULL);
26 | #else
27 | strncpy(dst, src, size);
28 | #endif
29 | }
30 |
31 | int os_makedir(const oschar_t *dir) {
32 | #ifdef _WIN32
33 | return _wmkdir(dir);
34 | #else
35 | return mkdir(dir, 0777);
36 | #endif
37 | }
38 |
39 | int os_rmdir(const oschar_t *dir) {
40 | #ifdef _WIN32
41 | return _wrmdir(dir);
42 | #else
43 | return remove(dir);
44 | #endif
45 | }
46 |
47 | void filepath_update(filepath_t *fpath) {
48 | memset(fpath->os_path, 0, MAX_SWITCHPATH * sizeof(oschar_t));
49 | os_strncpy(fpath->os_path, fpath->char_path, MAX_SWITCHPATH);
50 | }
51 |
52 | void filepath_init(filepath_t *fpath) {
53 | fpath->valid = VALIDITY_INVALID;
54 | }
55 |
56 | void filepath_copy(filepath_t *fpath, filepath_t *copy) {
57 | if (copy != NULL && copy->valid == VALIDITY_VALID)
58 | memcpy(fpath, copy, sizeof(filepath_t));
59 | else
60 | memset(fpath, 0, sizeof(filepath_t));
61 | }
62 |
63 | void filepath_os_append(filepath_t *fpath, oschar_t *path) {
64 | char tmppath[MAX_SWITCHPATH];
65 | if (fpath->valid == VALIDITY_INVALID)
66 | return;
67 |
68 | memset(tmppath, 0, MAX_SWITCHPATH);
69 |
70 | os_strncpy_to_char(tmppath, path, MAX_SWITCHPATH);
71 | strcat(fpath->char_path, OS_PATH_SEPARATOR);
72 | strcat(fpath->char_path, tmppath);
73 | filepath_update(fpath);
74 | }
75 |
76 | void filepath_append(filepath_t *fpath, const char *format, ...) {
77 | char tmppath[MAX_SWITCHPATH];
78 | va_list args;
79 |
80 | if (fpath->valid == VALIDITY_INVALID)
81 | return;
82 |
83 | memset(tmppath, 0, MAX_SWITCHPATH);
84 |
85 | va_start(args, format);
86 | vsnprintf(tmppath, sizeof(tmppath), format, args);
87 | va_end(args);
88 |
89 | strcat(fpath->char_path, OS_PATH_SEPARATOR);
90 | strcat(fpath->char_path, tmppath);
91 | filepath_update(fpath);
92 | }
93 |
94 | void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...) {
95 | char tmppath[MAX_SWITCHPATH];
96 | va_list args;
97 |
98 | if (fpath->valid == VALIDITY_INVALID || n > MAX_SWITCHPATH)
99 | return;
100 |
101 | memset(tmppath, 0, MAX_SWITCHPATH);
102 |
103 | va_start(args, format);
104 | vsnprintf(tmppath, sizeof(tmppath), format, args);
105 | va_end(args);
106 |
107 | strcat(fpath->char_path, OS_PATH_SEPARATOR);
108 | strncat(fpath->char_path, tmppath, n);
109 | filepath_update(fpath);
110 | }
111 |
112 | void filepath_set(filepath_t *fpath, const char *path) {
113 | if (strlen(path) < MAX_SWITCHPATH) {
114 | fpath->valid = VALIDITY_VALID;
115 | memset(fpath->char_path, 0, MAX_SWITCHPATH);
116 | strncpy(fpath->char_path, path, MAX_SWITCHPATH);
117 | filepath_update(fpath);
118 | } else {
119 | fpath->valid = VALIDITY_INVALID;
120 | }
121 | }
122 |
123 | oschar_t *filepath_get(filepath_t *fpath) {
124 | if (fpath->valid == VALIDITY_INVALID)
125 | return NULL;
126 | else
127 | return fpath->os_path;
128 | }
129 |
--------------------------------------------------------------------------------
/src/filepath.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "types.h"
4 | #include
5 | #ifdef _WIN32
6 | #include
7 | #include
8 | #endif
9 |
10 | #define MAX_SWITCHPATH 0x300
11 |
12 | typedef enum {
13 | VALIDITY_UNCHECKED = 0,
14 | VALIDITY_INVALID,
15 | VALIDITY_VALID
16 | } validity_t;
17 |
18 | #ifdef _MSC_VER
19 | inline int fseeko64(FILE *__stream, long long __off, int __whence)
20 | {
21 | return _fseeki64(__stream, __off, __whence);
22 | }
23 | #else
24 | /* off_t is 64-bit with large file support */
25 | #define fseeko64 fseek
26 | #endif
27 |
28 | #ifdef _WIN32
29 | typedef wchar_t oschar_t; /* utf-16 */
30 | typedef _WDIR osdir_t;
31 | typedef struct _wdirent osdirent_t;
32 | typedef struct _stati64 os_stat64_t;
33 |
34 | #define os_fopen _wfopen
35 | #define os_opendir _wopendir
36 | #define os_closedir _wclosedir
37 | #define os_readdir _wreaddir
38 | #define os_stat _wstati64
39 | #define os_fclose fclose
40 |
41 | #define OS_MODE_READ L"rb"
42 | #define OS_MODE_WRITE L"wb"
43 | #define OS_MODE_EDIT L"rb+"
44 | #else
45 | typedef char oschar_t; /* utf-8 */
46 | typedef DIR osdir_t;
47 | typedef struct dirent osdirent_t;
48 | typedef struct stat os_stat64_t;
49 |
50 | #define os_fopen fopen
51 | #define os_opendir opendir
52 | #define os_closedir closedir
53 | #define os_readdir readdir
54 | #define os_stat stat
55 | #define os_fclose fclose
56 |
57 | #define OS_MODE_READ "rb"
58 | #define OS_MODE_WRITE "wb"
59 | #define OS_MODE_EDIT "rb+"
60 | #endif
61 |
62 | #define OS_PATH_SEPARATOR "/"
63 |
64 | typedef struct filepath {
65 | char char_path[MAX_SWITCHPATH];
66 | oschar_t os_path[MAX_SWITCHPATH];
67 | validity_t valid;
68 | } filepath_t;
69 |
70 | void os_strncpy(oschar_t *dst, const char *src, size_t size);
71 | void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size);
72 | int os_makedir(const oschar_t *dir);
73 | int os_rmdir(const oschar_t *dir);
74 |
75 | void filepath_init(filepath_t *fpath);
76 | void filepath_copy(filepath_t *fpath, filepath_t *copy);
77 | void filepath_os_append(filepath_t *fpath, oschar_t *path);
78 | void filepath_append(filepath_t *fpath, const char *format, ...);
79 | void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...);
80 | void filepath_set(filepath_t *fpath, const char *path);
81 | oschar_t *filepath_get(filepath_t *fpath);
82 |
--------------------------------------------------------------------------------
/src/nacptool.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | typedef uint64_t u64;
8 | typedef uint32_t u32;
9 | typedef uint8_t u8;
10 |
11 | typedef struct {
12 | char name[0x200];
13 | char author[0x100];
14 | } NacpLanguageEntry;
15 |
16 | typedef struct {
17 | NacpLanguageEntry lang[12];
18 | NacpLanguageEntry lang_unk[4];//?
19 |
20 | u8 x3000_unk[0x24];////Normally all-zero?
21 | u32 x3024_unk;
22 | u32 x3028_unk;
23 | u32 x302C_unk;
24 | u32 x3030_unk;
25 | u32 x3034_unk;
26 | u64 titleid0;
27 |
28 | u8 x3040_unk[0x20];
29 | char version[0x10];
30 |
31 | u64 titleid_dlcbase;
32 | u64 titleid1;
33 |
34 | u32 x3080_unk;
35 | u32 x3084_unk;
36 | u32 x3088_unk;
37 | u8 x308C_unk[0x24];//zeros?
38 |
39 | u64 titleid2;
40 | u64 titleids[7];//"Array of application titleIDs, normally the same as the above app-titleIDs. Only set for game-updates?"
41 |
42 | u32 x30F0_unk;
43 | u32 x30F4_unk;
44 |
45 | u64 titleid3;//"Application titleID. Only set for game-updates?"
46 |
47 | char bcat_passphrase[0x40];
48 | u8 x3140_unk[0xEC0];//Normally all-zero?
49 | } NacpStruct;
50 |
51 | int main(int argc, char* argv[]) {
52 | if (argc < 6 || strncmp(argv[1], "--create", 8)!=0) {
53 | fprintf(stderr, "%s --create [options]\n\n", argv[0]);
54 | fprintf(stderr, "FLAGS:\n");
55 | fprintf(stderr, "--create : Create control.nacp for use with Switch homebrew applications.\n");
56 | fprintf(stderr, "Options:\n");
57 | fprintf(stderr, "--titleid= Set the application titleID.\n");
58 | return EXIT_FAILURE;
59 | }
60 |
61 | NacpStruct nacp;
62 | memset(&nacp, 0, sizeof(nacp));
63 |
64 | if (sizeof(NacpStruct) != 0x4000) {
65 | fprintf(stderr, "Bad compile environment!\n");
66 | return EXIT_FAILURE;
67 | }
68 |
69 | char *name = argv[2];
70 | char *author = argv[3];
71 | char *names[12];
72 | char *authors[12];
73 |
74 | int i;
75 | for (i=0; i<12; i++) {
76 | names[i] = name;
77 | authors[i] = author;
78 | }
79 |
80 | int argi;
81 | u64 titleid=0;
82 | for (argi=6; argi
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "cJSON.h"
9 |
10 | typedef uint64_t u64;
11 | typedef uint32_t u32;
12 | typedef uint16_t u16;
13 | typedef uint8_t u8;
14 |
15 | #define MAGIC_META 0x4154454D
16 | #define MAGIC_ACID 0x44494341
17 | #define MAGIC_ACI0 0x30494341
18 |
19 | /* FAC, FAH need to be tightly packed. */
20 | #pragma pack(push, 1)
21 | typedef struct {
22 | u8 Version;
23 | u8 CoiCount;
24 | u8 SdoiCount;
25 | u8 pad;
26 | u64 Perms;
27 | u64 CoiMin;
28 | u64 CoiMax;
29 | u64 SdoiMin;
30 | u64 SdoiMax;
31 | } FilesystemAccessControl;
32 | #pragma pack(pop)
33 |
34 | #pragma pack(push, 1)
35 | typedef struct {
36 | u32 Version;
37 | u64 Perms;
38 | u32 CoiOffset;
39 | u32 CoiSize;
40 | u32 SdoiOffset;
41 | u32 SdoiSize;
42 | } FilesystemAccessHeader;
43 | #pragma pack(pop)
44 |
45 | typedef struct {
46 | u32 Magic;
47 | u8 _0x4[0xC];
48 | u64 ProgramId;
49 | u64 _0x18;
50 | u32 FahOffset;
51 | u32 FahSize;
52 | u32 SacOffset;
53 | u32 SacSize;
54 | u32 KacOffset;
55 | u32 KacSize;
56 | u64 Padding;
57 | } NpdmAci0;
58 |
59 | typedef struct {
60 | u8 Signature[0x100];
61 | u8 Modulus[0x100];
62 | u32 Magic;
63 | u32 Size;
64 | u32 _0x208;
65 | u32 Flags;
66 | u64 ProgramIdRangeMin;
67 | u64 ProgramIdRangeMax;
68 | u32 FacOffset;
69 | u32 FacSize;
70 | u32 SacOffset;
71 | u32 SacSize;
72 | u32 KacOffset;
73 | u32 KacSize;
74 | u64 Padding;
75 | } NpdmAcid;
76 |
77 | typedef struct {
78 | u32 Magic;
79 | u32 SignatureKeyGeneration;
80 | u32 _0x8;
81 | u8 MmuFlags;
82 | u8 _0xD;
83 | u8 MainThreadPriority;
84 | u8 DefaultCpuId;
85 | u32 _0x10;
86 | u32 SystemResourceSize;
87 | u32 Version;
88 | u32 MainThreadStackSize;
89 | char Name[0x10];
90 | char ProductCode[0x10];
91 | u8 _0x40[0x30];
92 | u32 Aci0Offset;
93 | u32 Aci0Size;
94 | u32 AcidOffset;
95 | u32 AcidSize;
96 | } NpdmHeader;
97 |
98 |
99 | uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
100 | FILE* fd = fopen(fn, "rb");
101 | if (fd == NULL)
102 | return NULL;
103 |
104 | fseek(fd, 0, SEEK_END);
105 | size_t len = ftell(fd);
106 | fseek(fd, 0, SEEK_SET);
107 |
108 | uint8_t* buf = malloc(len);
109 | if (buf == NULL) {
110 | fclose(fd);
111 | return NULL;
112 | }
113 |
114 | size_t rc = fread(buf, 1, len, fd);
115 | if (rc != len) {
116 | fclose(fd);
117 | free(buf);
118 | return NULL;
119 | }
120 |
121 | *len_out = len;
122 | return buf;
123 | }
124 |
125 | int cJSON_GetString(const cJSON *obj, const char *field, const char **out) {
126 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
127 | if (cJSON_IsString(config)) {
128 | *out = config->valuestring;
129 | return 1;
130 | } else {
131 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
132 | return 0;
133 | }
134 | }
135 |
136 | int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
137 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
138 | if (cJSON_IsNumber(config)) {
139 | *out = (u8)config->valueint;
140 | return 1;
141 | } else {
142 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
143 | return 0;
144 | }
145 | }
146 |
147 | int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
148 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
149 | if (cJSON_IsNumber(config)) {
150 | *out = (u16)config->valueint;
151 | return 1;
152 | } else {
153 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
154 | return 0;
155 | }
156 | }
157 |
158 | int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
159 | if (cJSON_IsNumber(config)) {
160 | *out = (u16)config->valueint;
161 | return 1;
162 | } else {
163 | fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
164 | return 0;
165 | }
166 | }
167 |
168 | int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
169 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
170 | if (cJSON_IsBool(config)) {
171 | if (cJSON_IsTrue(config)) {
172 | *out = 1;
173 | } else if (cJSON_IsFalse(config)) {
174 | *out = 0;
175 | } else {
176 | fprintf(stderr, "Unknown boolean value in %s.\n", field);
177 | return 0;
178 | }
179 | return 1;
180 | } else {
181 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
182 | return 0;
183 | }
184 | }
185 |
186 | int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {
187 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
188 | if (cJSON_IsBool(config)) {
189 | if (cJSON_IsTrue(config)) {
190 | *out = 1;
191 | } else if (cJSON_IsFalse(config)) {
192 | *out = 0;
193 | } else {
194 | fprintf(stderr, "Unknown boolean value in %s.\n", field);
195 | return 0;
196 | }
197 | } else {
198 | *out = 0;
199 | }
200 | return 1;
201 | }
202 |
203 | int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
204 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
205 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
206 | char *endptr = NULL;
207 | *out = strtoull(config->valuestring, &endptr, 16);
208 | if (config->valuestring == endptr) {
209 | fprintf(stderr, "Failed to get %s (empty string)\n", field);
210 | return 0;
211 | } else if (errno == ERANGE) {
212 | fprintf(stderr, "Failed to get %s (value out of range)\n", field);
213 | return 0;
214 | } else if (errno == EINVAL) {
215 | fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
216 | return 0;
217 | } else if (errno) {
218 | fprintf(stderr, "Failed to get %s (unknown error)\n", field);
219 | return 0;
220 | } else {
221 | return 1;
222 | }
223 | } else {
224 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
225 | return 0;
226 | }
227 | }
228 |
229 | int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
230 | const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
231 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
232 | char *endptr = NULL;
233 | *out = strtoul(config->valuestring, &endptr, 16);
234 | if (config->valuestring == endptr) {
235 | fprintf(stderr, "Failed to get %s (empty string)\n", field);
236 | return 0;
237 | } else if (errno == ERANGE) {
238 | fprintf(stderr, "Failed to get %s (value out of range)\n", field);
239 | return 0;
240 | } else if (errno == EINVAL) {
241 | fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
242 | return 0;
243 | } else if (errno) {
244 | fprintf(stderr, "Failed to get %s (unknown error)\n", field);
245 | return 0;
246 | } else {
247 | return 1;
248 | }
249 | } else {
250 | fprintf(stderr, "Failed to get %s (field not present).\n", field);
251 | return 0;
252 | }
253 | }
254 |
255 | int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
256 | if (cJSON_IsString(config) && (config->valuestring != NULL)) {
257 | char *endptr = NULL;
258 | *out = strtoull(config->valuestring, &endptr, 16);
259 | if (config->valuestring == endptr) {
260 | fprintf(stderr, "Failed to get %s (empty string)\n", config->string);
261 | return 0;
262 | } else if (errno == ERANGE) {
263 | fprintf(stderr, "Failed to get %s (value out of range)\n", config->string);
264 | return 0;
265 | } else if (errno == EINVAL) {
266 | fprintf(stderr, "Failed to get %s (not base16 string)\n", config->string);
267 | return 0;
268 | } else if (errno) {
269 | fprintf(stderr, "Failed to get %s (unknown error)\n", config->string);
270 | return 0;
271 | } else {
272 | return 1;
273 | }
274 | } else {
275 | fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
276 | return 0;
277 | }
278 | }
279 |
280 | int CreateNpdm(const char *json, void **dst, u32 *dst_size) {
281 | NpdmHeader header = {0};
282 | NpdmAci0 *aci0 = calloc(1, 0x100000);
283 | NpdmAcid *acid = calloc(1, 0x100000);
284 | if (aci0 == NULL || acid == NULL) {
285 | fprintf(stderr, "Failed to allocate NPDM resources!\n");
286 | exit(EXIT_FAILURE);
287 | }
288 | const cJSON *capability = NULL;
289 | const cJSON *capabilities = NULL;
290 | const cJSON *service = NULL;
291 | const cJSON *services = NULL;
292 | const cJSON *fsaccess = NULL;
293 | const cJSON *cois = NULL;
294 | const cJSON *coi = NULL;
295 | const cJSON *sdois = NULL;
296 | const cJSON *sdoi = NULL;
297 |
298 | int status = 0;
299 | cJSON *npdm_json = cJSON_Parse(json);
300 | if (npdm_json == NULL) {
301 | const char *error_ptr = cJSON_GetErrorPtr();
302 | if (error_ptr != NULL) {
303 | fprintf(stderr, "JSON Parse Error: %s\n", error_ptr);
304 | }
305 | status = 0;
306 | goto NPDM_BUILD_END;
307 | }
308 |
309 | /* Initialize default NPDM values. */
310 | header.Magic = MAGIC_META; /* "META" */
311 |
312 |
313 | /* Parse name. */
314 | const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, "name");
315 | if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {
316 | strncpy(header.Name, title_name->valuestring, sizeof(header.Name) - 1);
317 | } else {
318 | fprintf(stderr, "Failed to get title name (name field not present).\n");
319 | status = 0;
320 | goto NPDM_BUILD_END;
321 | }
322 |
323 | /* Parse main_thread_stack_size. */
324 | u64 stack_size = 0;
325 | if (!cJSON_GetU64(npdm_json, "main_thread_stack_size", &stack_size)) {
326 | status = 0;
327 | goto NPDM_BUILD_END;
328 | }
329 | if (stack_size >> 32) {
330 | fprintf(stderr, "Error: Main thread stack size must be a u32!\n");
331 | status = 0;
332 | goto NPDM_BUILD_END;
333 | }
334 | header.MainThreadStackSize = (u32)(stack_size & 0xFFFFFFFF);
335 |
336 | /* Parse various config. */
337 | if (!cJSON_GetU8(npdm_json, "main_thread_priority", &header.MainThreadPriority)) {
338 | status = 0;
339 | goto NPDM_BUILD_END;
340 | }
341 | if (!cJSON_GetU8(npdm_json, "default_cpu_id", &header.DefaultCpuId)) {
342 | status = 0;
343 | goto NPDM_BUILD_END;
344 | }
345 |
346 | cJSON_GetU32(npdm_json, "system_resource_size", &header.SystemResourceSize); // optional
347 |
348 | /* Get version (deprecated name "process_category"). */
349 | if (!cJSON_GetU32(npdm_json, "version", &header.Version) && !cJSON_GetU32(npdm_json, "process_category", &header.Version)) { // optional
350 | header.Version = 0;
351 | }
352 |
353 | if (!cJSON_GetU8(npdm_json, "address_space_type", (u8 *)&header.MmuFlags)) {
354 | status = 0;
355 | goto NPDM_BUILD_END;
356 | }
357 | header.MmuFlags &= 3;
358 | header.MmuFlags <<= 1;
359 | int is_64_bit;
360 | if (!cJSON_GetBoolean(npdm_json, "is_64_bit", &is_64_bit)) {
361 | status = 0;
362 | goto NPDM_BUILD_END;
363 | }
364 | header.MmuFlags |= is_64_bit;
365 |
366 | int optimize_memory_allocation; // optional
367 | if (cJSON_GetBoolean(npdm_json, "optimize_memory_allocation", &optimize_memory_allocation)) {
368 | header.MmuFlags |= ((optimize_memory_allocation & 1) << 4);
369 | }
370 |
371 | int disable_device_address_space_merge; // optional
372 | if (cJSON_GetBoolean(npdm_json, "disable_device_address_space_merge", &disable_device_address_space_merge)) {
373 | header.MmuFlags |= ((disable_device_address_space_merge & 1) << 5);
374 | }
375 |
376 | int enable_alias_region_extra_size; // optional
377 | if (cJSON_GetBoolean(npdm_json, "enable_alias_region_extra_size", &enable_alias_region_extra_size)) {
378 | header.MmuFlags |= ((enable_alias_region_extra_size & 1) << 6);
379 | }
380 |
381 | int prevent_code_reads; // optional
382 | if (cJSON_GetBoolean(npdm_json, "prevent_code_reads", &prevent_code_reads)) {
383 | header.MmuFlags |= ((prevent_code_reads & 1) << 7);
384 | }
385 |
386 | u8 signature_key_generation; // optional
387 | if (cJSON_GetU8(npdm_json, "signature_key_generation", &signature_key_generation)) {
388 | header.SignatureKeyGeneration = signature_key_generation;
389 | } else {
390 | header.SignatureKeyGeneration = 0;
391 | }
392 |
393 | /* ACID. */
394 | memset(acid->Signature, 0, sizeof(acid->Signature));
395 | memset(acid->Modulus, 0, sizeof(acid->Modulus));
396 | acid->Magic = MAGIC_ACID; /* "ACID" */
397 | int is_retail;
398 | if (!cJSON_GetBoolean(npdm_json, "is_retail", &is_retail)) {
399 | status = 0;
400 | goto NPDM_BUILD_END;
401 | }
402 | acid->Flags |= is_retail;
403 | u8 pool_partition;
404 | if (!cJSON_GetU8(npdm_json, "pool_partition", &pool_partition)) {
405 | status = 0;
406 | goto NPDM_BUILD_END;
407 | }
408 | acid->Flags |= (pool_partition & 3) << 2;
409 |
410 | if (!cJSON_GetU64(npdm_json, "program_id_range_min", &acid->ProgramIdRangeMin) && !cJSON_GetU64(npdm_json, "title_id_range_min", &acid->ProgramIdRangeMin)) {
411 | status = 0;
412 | goto NPDM_BUILD_END;
413 | }
414 | if (!cJSON_GetU64(npdm_json, "program_id_range_max", &acid->ProgramIdRangeMax) && !cJSON_GetU64(npdm_json, "title_id_range_max", &acid->ProgramIdRangeMax)) {
415 | status = 0;
416 | goto NPDM_BUILD_END;
417 | }
418 |
419 | /* ACI0. */
420 | aci0->Magic = MAGIC_ACI0; /* "ACI0" */
421 | /* Parse program_id (or deprecated title_id). */
422 | if (!cJSON_GetU64(npdm_json, "program_id", &aci0->ProgramId) && !cJSON_GetU64(npdm_json, "title_id", &aci0->ProgramId)) {
423 | status = 0;
424 | goto NPDM_BUILD_END;
425 | }
426 |
427 | /* Fac. */
428 | fsaccess = cJSON_GetObjectItemCaseSensitive(npdm_json, "filesystem_access");
429 | if (!cJSON_IsObject(fsaccess)) {
430 | fprintf(stderr, "Filesystem Access must be an object!\n");
431 | status = 0;
432 | goto NPDM_BUILD_END;
433 | }
434 |
435 | FilesystemAccessControl *fac = (FilesystemAccessControl *)((u8 *)acid + sizeof(NpdmAcid));
436 | fac->Version = 1;
437 | if (!cJSON_GetU64(fsaccess, "permissions", &fac->Perms)) {
438 | status = 0;
439 | goto NPDM_BUILD_END;
440 | }
441 |
442 | fac->CoiMin = 0;
443 | fac->CoiMax = 0;
444 | fac->SdoiMin = 0;
445 | fac->SdoiMax = 0;
446 | fac->CoiCount = 0;
447 | fac->SdoiCount = 0;
448 |
449 | acid->FacOffset = sizeof(NpdmAcid);
450 | acid->FacSize = sizeof(FilesystemAccessControl);
451 | acid->SacOffset = (acid->FacOffset + acid->FacSize + 0xF) & ~0xF;
452 |
453 | /* Fah. */
454 | FilesystemAccessHeader *fah = (FilesystemAccessHeader *)((u8 *)aci0 + sizeof(NpdmAci0));
455 | fah->Version = 1;
456 | fah->Perms = fac->Perms;
457 | fah->CoiOffset = sizeof(FilesystemAccessHeader);
458 | fah->CoiSize = 0;
459 |
460 | cois = cJSON_GetObjectItemCaseSensitive(fsaccess, "content_owner_ids");
461 | if (cJSON_IsArray(cois)) {
462 | u32 *count = (u32 *)((u8 *)fah + fah->CoiOffset);
463 | u64 *id = (u64 *)((u8 *)count + sizeof(u32));
464 | cJSON_ArrayForEach(coi, cois) {
465 | if (!cJSON_GetU64FromObjectValue(coi, id)) {
466 | status = 0;
467 | goto NPDM_BUILD_END;
468 | }
469 | ++id;
470 | ++(*count);
471 | }
472 |
473 | if (*count > 0) {
474 | fah->CoiSize = sizeof(u32) + sizeof(u64) * (*count);
475 | }
476 | }
477 |
478 | fah->SdoiOffset = fah->CoiOffset + fah->CoiSize;
479 | fah->SdoiSize = 0;
480 |
481 | sdois = cJSON_GetObjectItemCaseSensitive(fsaccess, "save_data_owner_ids");
482 | if (cJSON_IsArray(sdois)) {
483 | u32 *count = (u32 *)((u8 *)fah + fah->SdoiOffset);
484 | cJSON_ArrayForEach(sdoi, sdois) {
485 | if (!cJSON_IsObject(sdoi)) {
486 | status = 0;
487 | goto NPDM_BUILD_END;
488 | }
489 | ++(*count);
490 | }
491 |
492 | u8 *accessibility = (u8 *)count + sizeof(u32);
493 | u64 *id = (u64 *)(accessibility + (((*count) + 3ULL) & ~3ULL));
494 |
495 | cJSON_ArrayForEach(sdoi, sdois) {
496 | if (!cJSON_GetU8(sdoi, "accessibility", accessibility)) {
497 | status = 0;
498 | goto NPDM_BUILD_END;
499 | }
500 | if (!cJSON_GetU64(sdoi, "id", id)) {
501 | status = 0;
502 | goto NPDM_BUILD_END;
503 | }
504 |
505 | ++accessibility;
506 | ++id;
507 | }
508 |
509 | if (*count > 0) {
510 | fah->SdoiSize = sizeof(u32) + sizeof(u8) * ((((*count) + 3ULL) & ~3ULL)) + sizeof(u64) * (*count);
511 | }
512 | }
513 |
514 | aci0->FahOffset = sizeof(NpdmAci0);
515 | aci0->FahSize = sizeof(FilesystemAccessHeader) + fah->CoiSize + fah->SdoiSize;
516 | aci0->SacOffset = (aci0->FahOffset + aci0->FahSize + 0xF) & ~0xF;
517 |
518 | /* Sac. */
519 | u8 *sac = (u8*)aci0 + aci0->SacOffset;
520 | u32 sac_size = 0;
521 |
522 | services = cJSON_GetObjectItemCaseSensitive(npdm_json, "service_host");
523 | if (services != NULL && !cJSON_IsArray(services)) {
524 | fprintf(stderr, "Service Host must be an array!\n");
525 | status = 0;
526 | goto NPDM_BUILD_END;
527 | }
528 |
529 | cJSON_ArrayForEach(service, services) {
530 | int is_host = 1;
531 | char *service_name;
532 |
533 | if (!cJSON_IsString(service)) {
534 | fprintf(stderr, "service_access must be an array of string\n");
535 | status = 0;
536 | goto NPDM_BUILD_END;
537 | }
538 | service_name = service->valuestring;
539 |
540 | int cur_srv_len = strlen(service_name);
541 | if (cur_srv_len > 8 || cur_srv_len == 0) {
542 | fprintf(stderr, "Services must have name length 1 <= len <= 8!\n");
543 | status = 0;
544 | goto NPDM_BUILD_END;
545 | }
546 | u8 ctrl = (u8)(cur_srv_len - 1);
547 | if (is_host) {
548 | ctrl |= 0x80;
549 | }
550 | sac[sac_size++] = ctrl;
551 | memcpy(sac + sac_size, service_name, cur_srv_len);
552 | sac_size += cur_srv_len;
553 | }
554 |
555 | services = cJSON_GetObjectItemCaseSensitive(npdm_json, "service_access");
556 | if (!(services == NULL || cJSON_IsObject(services) || cJSON_IsArray(services))) {
557 | fprintf(stderr, "Service Access must be an array!\n");
558 | status = 0;
559 | goto NPDM_BUILD_END;
560 | }
561 |
562 | int sac_obj = 0;
563 | if (services != NULL && cJSON_IsObject(services)) {
564 | sac_obj = 1;
565 | fprintf(stderr, "Using deprecated service_access format. Please turn it into an array.\n");
566 | }
567 |
568 | cJSON_ArrayForEach(service, services) {
569 | int is_host = 0;
570 | char *service_name;
571 |
572 | if (sac_obj) {
573 | if (!cJSON_IsBool(service)) {
574 | fprintf(stderr, "Services must be of form service_name (str) : is_host (bool)\n");
575 | status = 0;
576 | goto NPDM_BUILD_END;
577 | }
578 | is_host = cJSON_IsTrue(service);
579 | service_name = service->string;
580 | } else {
581 | if (!cJSON_IsString(service)) {
582 | fprintf(stderr, "service_access must be an array of string\n");
583 | status = 0;
584 | goto NPDM_BUILD_END;
585 | }
586 | is_host = 0;
587 | service_name = service->valuestring;
588 | }
589 |
590 | int cur_srv_len = strlen(service_name);
591 | if (cur_srv_len > 8 || cur_srv_len == 0) {
592 | fprintf(stderr, "Services must have name length 1 <= len <= 8!\n");
593 | status = 0;
594 | goto NPDM_BUILD_END;
595 | }
596 | u8 ctrl = (u8)(cur_srv_len - 1);
597 | if (is_host) {
598 | ctrl |= 0x80;
599 | }
600 | sac[sac_size++] = ctrl;
601 | memcpy(sac + sac_size, service_name, cur_srv_len);
602 | sac_size += cur_srv_len;
603 | }
604 |
605 |
606 | memcpy((u8 *)acid + acid->SacOffset, sac, sac_size);
607 | aci0->SacSize = sac_size;
608 | acid->SacSize = sac_size;
609 | aci0->KacOffset = (aci0->SacOffset + aci0->SacSize + 0xF) & ~0xF;
610 | acid->KacOffset = (acid->SacOffset + acid->SacSize + 0xF) & ~0xF;
611 |
612 | /* Parse capabilities. */
613 | capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, "kernel_capabilities");
614 | if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {
615 | fprintf(stderr, "Kernel Capabilities must be an array!\n");
616 | status = 0;
617 | goto NPDM_BUILD_END;
618 | }
619 |
620 | int kac_obj = 0;
621 | if (cJSON_IsObject(capabilities)) {
622 | kac_obj = 1;
623 | fprintf(stderr, "Using deprecated kernel_capabilities format. Please turn it into an array.\n");
624 | }
625 |
626 | u32 *caps = (u32 *)((u8 *)aci0 + aci0->KacOffset);
627 | u32 cur_cap = 0;
628 | u32 desc;
629 | cJSON_ArrayForEach(capability, capabilities) {
630 | desc = 0;
631 | const char *type_str;
632 | const cJSON *value;
633 |
634 | if (kac_obj) {
635 | type_str = capability->string;
636 | value = capability;
637 | } else {
638 | if (!cJSON_GetString(capability, "type", &type_str)) {
639 | status = 0;
640 | goto NPDM_BUILD_END;
641 | }
642 | value = cJSON_GetObjectItemCaseSensitive(capability, "value");
643 | }
644 |
645 | if (!strcmp(type_str, "kernel_flags")) {
646 | if (!cJSON_IsObject(value)) {
647 | fprintf(stderr, "Kernel Flags Capability value must be object!\n");
648 | status = 0;
649 | goto NPDM_BUILD_END;
650 | }
651 | u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;
652 | if (!cJSON_GetU8(value, "highest_thread_priority", &highest_prio) ||
653 | !cJSON_GetU8(value, "lowest_thread_priority", &lowest_prio) ||
654 | !cJSON_GetU8(value, "highest_cpu_id", &highest_cpu) ||
655 | !cJSON_GetU8(value, "lowest_cpu_id", &lowest_cpu)) {
656 | status = 0;
657 | goto NPDM_BUILD_END;
658 | }
659 |
660 | u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;
661 | u8 real_lowest_prio = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;
662 |
663 | desc = highest_cpu;
664 | desc <<= 8;
665 | desc |= lowest_cpu;
666 | desc <<= 6;
667 | desc |= (real_highest_prio & 0x3F);
668 | desc <<= 6;
669 | desc |= (real_lowest_prio & 0x3F);
670 | caps[cur_cap++] = (u32)((desc << 4) | (0x0007));
671 | } else if (!strcmp(type_str, "syscalls")) {
672 | if (!cJSON_IsObject(value)) {
673 | fprintf(stderr, "Syscalls Capability value must be object!\n");
674 | status = 0;
675 | goto NPDM_BUILD_END;
676 | }
677 | u32 num_descriptors;
678 | u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */
679 | char field_name[8] = {0};
680 | const cJSON *cur_syscall = NULL;
681 | u64 syscall_value = 0;
682 | cJSON_ArrayForEach(cur_syscall, value) {
683 | if (cJSON_IsNumber(cur_syscall)) {
684 | syscall_value = (u64)cur_syscall->valueint;
685 | } else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {
686 | fprintf(stderr, "Error: Syscall entries must be integers or hex strings.\n");
687 | status = 0;
688 | goto NPDM_BUILD_END;
689 | }
690 |
691 | if (syscall_value >= 0xC0) {
692 | fprintf(stderr, "Error: All syscall entries must be numbers in [0, 0xBF]\n");
693 | status = 0;
694 | goto NPDM_BUILD_END;
695 | }
696 | descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));
697 | }
698 | for (unsigned int i = 0; i < 8; i++) {
699 | if (descriptors[i]) {
700 | desc = descriptors[i] | (i << 24);
701 | caps[cur_cap++] = (u32)((desc << 5) | (0x000F));
702 | }
703 | }
704 | } else if (!strcmp(type_str, "map")) {
705 | if (!cJSON_IsObject(value)) {
706 | fprintf(stderr, "Map Capability value must be object!\n");
707 | status = 0;
708 | goto NPDM_BUILD_END;
709 | }
710 | u64 map_address = 0;
711 | u64 map_size = 0;
712 | int is_ro;
713 | int is_io;
714 | if (!cJSON_GetU64(value, "address", &map_address) ||
715 | !cJSON_GetU64(value, "size", &map_size) ||
716 | !cJSON_GetBoolean(value, "is_ro", &is_ro) ||
717 | !cJSON_GetBoolean(value, "is_io", &is_io)) {
718 | status = 0;
719 | goto NPDM_BUILD_END;
720 | }
721 | desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);
722 | desc |= is_ro << 24;
723 | caps[cur_cap++] = (u32)((desc << 7) | (0x003F));
724 |
725 | desc = (u32)((map_size >> 12) & 0x000FFFFFULL);
726 | desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);
727 | is_io ^= 1;
728 | desc |= is_io << 24;
729 | caps[cur_cap++] = (u32)((desc << 7) | (0x003F));
730 | } else if (!strcmp(type_str, "map_page")) {
731 | u64 page_address = 0;
732 | if (!cJSON_GetU64FromObjectValue(value, &page_address)) {
733 | status = 0;
734 | goto NPDM_BUILD_END;
735 | }
736 | desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);
737 | caps[cur_cap++] = (u32)((desc << 8) | (0x007F));
738 | } else if (!strcmp(type_str, "map_region")) {
739 | if (cur_cap + 1 > 0x20) {
740 | fprintf(stderr, "Error: Too many capabilities!\n");
741 | status = 0;
742 | goto NPDM_BUILD_END;
743 | }
744 | if (!cJSON_IsArray(value)) {
745 | fprintf(stderr, "Map Region capability value must be array!\n");
746 | status = 0;
747 | goto NPDM_BUILD_END;
748 | }
749 | u8 regions[3] = {0};
750 | int is_ro[3] = {0};
751 | const cJSON *cur_region = NULL;
752 | int index = 0;
753 | cJSON_ArrayForEach(cur_region, value) {
754 | if (index >= 3) {
755 | fprintf(stderr, "Too many region descriptors!\n");
756 | status = 0;
757 | goto NPDM_BUILD_END;
758 | }
759 | if (!cJSON_IsObject(cur_region)) {
760 | fprintf(stderr, "Region descriptor value must be object!\n");
761 | status = 0;
762 | goto NPDM_BUILD_END;
763 | }
764 |
765 | if (!cJSON_GetU8(cur_region, "region_type", ®ions[index]) ||
766 | !cJSON_GetBoolean(cur_region, "is_ro", &is_ro[index])) {
767 | status = 0;
768 | goto NPDM_BUILD_END;
769 | }
770 |
771 | index++;
772 | }
773 |
774 | u32 capability = 0x3FF;
775 | for (int i = 0; i < 3; ++i) {
776 | capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);
777 | }
778 | caps[cur_cap++] = capability;
779 | } else if (!strcmp(type_str, "irq_pair")) {
780 | if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {
781 | fprintf(stderr, "Error: IRQ Pairs must have size 2 array value.\n");
782 | status = 0;
783 | goto NPDM_BUILD_END;
784 | }
785 | const cJSON *irq = NULL;
786 | int desc_idx = 0;
787 | cJSON_ArrayForEach(irq, value) {
788 | if (cJSON_IsNull(irq)) {
789 | desc |= 0x3FF << desc_idx;
790 | } else if (cJSON_IsNumber(irq)) {
791 | desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;
792 | } else {
793 | fprintf(stderr, "Failed to parse IRQ value.\n");
794 | status = 0;
795 | goto NPDM_BUILD_END;
796 | }
797 | desc_idx += 10;
798 | }
799 | caps[cur_cap++] = (u32)((desc << 12) | (0x07FF));
800 | } else if (!strcmp(type_str, "application_type")) {
801 | if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
802 | status = 0;
803 | goto NPDM_BUILD_END;
804 | }
805 | desc &= 7;
806 | caps[cur_cap++] = (u32)((desc << 14) | (0x1FFF));
807 | } else if (!strcmp(type_str, "min_kernel_version")) {
808 | u64 kern_ver = 0;
809 | if (cJSON_IsNumber(value)) {
810 | kern_ver = (u64)value->valueint;
811 | } else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {
812 | fprintf(stderr, "Error: Kernel version must be integer or hex strings.\n");
813 | status = 0;
814 | goto NPDM_BUILD_END;
815 | }
816 | desc = (kern_ver) & 0xFFFF;
817 | caps[cur_cap++] = (u32)((desc << 15) | (0x3FFF));
818 | } else if (!strcmp(type_str, "handle_table_size")) {
819 | if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
820 | status = 0;
821 | goto NPDM_BUILD_END;
822 | }
823 | caps[cur_cap++] = (u32)((desc << 16) | (0x7FFF));
824 | } else if (!strcmp(type_str, "debug_flags")) {
825 | if (!cJSON_IsObject(value)) {
826 | fprintf(stderr, "Debug Flag Capability value must be object!\n");
827 | status = 0;
828 | goto NPDM_BUILD_END;
829 | }
830 | int allow_debug = 0;
831 | int force_debug = 0;
832 | int force_debug_prod = 0;
833 | cJSON_GetBoolean(value, "allow_debug", &allow_debug);
834 | cJSON_GetBoolean(value, "force_debug", &force_debug);
835 | cJSON_GetBoolean(value, "force_debug_prod", &force_debug_prod);
836 | if ( allow_debug + force_debug + force_debug_prod > 1 ) {
837 | fprintf(stderr, "Only one of allow_debug, force_debug, or force_debug_prod can be set!\n");
838 | status = 0;
839 | goto NPDM_BUILD_END;
840 | }
841 | desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);
842 | caps[cur_cap++] = (u32)((desc << 17) | (0xFFFF));
843 | }
844 | }
845 | aci0->KacSize = cur_cap * sizeof(u32);
846 | acid->KacSize = aci0->KacSize;
847 | memcpy((u8 *)acid + acid->KacOffset, caps, aci0->KacSize);
848 |
849 | header.AcidOffset = sizeof(header);
850 | header.AcidSize = acid->KacOffset + acid->KacSize;
851 | acid->Size = header.AcidSize - sizeof(acid->Signature);
852 | header.Aci0Offset = (header.AcidOffset + header.AcidSize + 0xF) & ~0xF;
853 | header.Aci0Size = aci0->KacOffset + aci0->KacSize;
854 | u32 total_size = header.Aci0Offset + header.Aci0Size;
855 | u8 *npdm = calloc(1, total_size);
856 | if (npdm == NULL) {
857 | fprintf(stderr, "Failed to allocate output!\n");
858 | exit(EXIT_FAILURE);
859 | }
860 | memcpy(npdm, &header, sizeof(header));
861 | memcpy(npdm + header.AcidOffset, acid, header.AcidSize);
862 | memcpy(npdm + header.Aci0Offset, aci0, header.Aci0Size);
863 | free(acid);
864 | free(aci0);
865 | *dst = npdm;
866 | *dst_size = total_size;
867 |
868 | status = 1;
869 | NPDM_BUILD_END:
870 | cJSON_Delete(npdm_json);
871 | return status;
872 | }
873 |
874 | int main(int argc, char* argv[]) {
875 | if (argc != 3) {
876 | fprintf(stderr, "%s \n", argv[0]);
877 | return EXIT_FAILURE;
878 | }
879 |
880 | void *npdm;
881 | u32 npdm_size;
882 |
883 | if (sizeof(NpdmHeader) != 0x80 || sizeof(NpdmAcid) != 0x240 || sizeof(NpdmAci0) != 0x40) {
884 | fprintf(stderr, "Bad compile environment!\n");
885 | return EXIT_FAILURE;
886 | }
887 |
888 | size_t json_len;
889 | uint8_t* json = ReadEntireFile(argv[1], &json_len);
890 | if (json == NULL) {
891 | fprintf(stderr, "Failed to read descriptor json!\n");
892 | return EXIT_FAILURE;
893 | }
894 |
895 | if (!CreateNpdm(json, &npdm, &npdm_size)) {
896 | fprintf(stderr, "Failed to parse descriptor json!\n");
897 | return EXIT_FAILURE;
898 | }
899 |
900 | FILE *f_out = fopen(argv[2], "wb");
901 | if (f_out == NULL) {
902 | fprintf(stderr, "Failed to open %s for writing!\n", argv[2]);
903 | return EXIT_FAILURE;
904 | }
905 | if (fwrite(npdm, 1, npdm_size, f_out) != npdm_size) {
906 | fprintf(stderr, "Failed to write NPDM to %s!\n", argv[2]);
907 | return EXIT_FAILURE;
908 | }
909 | fclose(f_out);
910 | free(npdm);
911 |
912 | return EXIT_SUCCESS;
913 | }
914 |
--------------------------------------------------------------------------------
/src/nxlink.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | #ifndef __WIN32__
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #define closesocket close
19 | #else
20 | #include
21 | #include
22 | typedef int socklen_t;
23 | typedef uint32_t in_addr_t;
24 | #define SHUT_RD SD_RECEIVE
25 | #define SHUT_WR SD_SEND
26 | #define SHUT_RDWR SD_BOTH
27 | #ifdef EWOULDBLOCK
28 | #undef EWOULDBLOCK
29 | #endif
30 | #define EWOULDBLOCK WSAEWOULDBLOCK
31 | #define poll WSAPoll
32 | #endif
33 |
34 | #include
35 | #include
36 |
37 | #define ZLIB_CHUNK (16 * 1024)
38 |
39 | #define NETLOADER_SERVER_PORT 28280
40 | #define NETLOADER_CLIENT_PORT 28771
41 |
42 |
43 | static char cmdbuf[3072];
44 | static uint32_t cmdlen=0;
45 |
46 | //---------------------------------------------------------------------------------
47 | static void shutdownSocket(int socket, int flags) {
48 | //---------------------------------------------------------------------------------
49 | if (flags)
50 | shutdown(socket, flags);
51 | closesocket(socket);
52 | }
53 |
54 | //---------------------------------------------------------------------------------
55 | static int setSocketNonblocking(int sock) {
56 | //---------------------------------------------------------------------------------
57 |
58 | #ifndef __WIN32__
59 | int flags = fcntl(sock, F_GETFL);
60 |
61 | if (flags == -1) return -1;
62 |
63 | int rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
64 |
65 | if (rc != 0) return -1;
66 | #else
67 | u_long iMode = 1; // non-blocking
68 |
69 | int rc = ioctlsocket(sock, FIONBIO, &iMode);
70 |
71 | if (rc != NO_ERROR) return -1;
72 | #endif
73 |
74 | return 0;
75 | }
76 |
77 | //---------------------------------------------------------------------------------
78 | static int socketError(const char *msg) {
79 | //---------------------------------------------------------------------------------
80 | #ifndef _WIN32
81 | int ret = errno;
82 | if (ret == EAGAIN)
83 | ret = EWOULDBLOCK;
84 | perror(msg);
85 | #else
86 | int ret = WSAGetLastError();
87 | wchar_t *s = NULL;
88 | FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
89 | NULL, ret,
90 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
91 | (LPWSTR)&s, 0, NULL);
92 | fprintf(stderr, "%S\n", s);
93 | LocalFree(s);
94 | if (ret == WSAEWOULDBLOCK)
95 | ret = EWOULDBLOCK;
96 | #endif
97 |
98 | return ret;
99 | }
100 |
101 | //---------------------------------------------------------------------------------
102 | int pollSocket(int fd, int events, int timeout) {
103 | //---------------------------------------------------------------------------------
104 | #ifndef __WIN32__
105 | struct pollfd pfd;
106 | #else
107 | WSAPOLLFD pfd;
108 | #endif
109 |
110 | pfd.fd = fd;
111 | pfd.events = events;
112 | pfd.revents = 0;
113 |
114 | int ret = poll(&pfd, 1, timeout);
115 | if (ret < 0) {
116 | socketError("poll");
117 | return -1;
118 | }
119 |
120 | if (ret == 0)
121 | return -1;
122 |
123 | if (!(pfd.revents & events)) {
124 | int err = 0;
125 | int len = sizeof(err);
126 | getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len);
127 | fprintf(stderr, "socket error 0x%x on poll\n", err);
128 | return -1;
129 | }
130 |
131 | return 0;
132 | }
133 |
134 | //---------------------------------------------------------------------------------
135 | static struct in_addr findSwitch(int retries) {
136 | //---------------------------------------------------------------------------------
137 |
138 | printf("pinging switch\n");
139 |
140 | struct sockaddr_in s, remote, rs;
141 | char recvbuf[256];
142 | char mess[] = "nxboot";
143 |
144 | int broadcastSock = socket(PF_INET, SOCK_DGRAM, 0);
145 | if (broadcastSock < 0) socketError("create send socket");
146 |
147 | int optval = 1, len;
148 | setsockopt(broadcastSock, SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval));
149 |
150 | memset(&s, '\0', sizeof(struct sockaddr_in));
151 | s.sin_family = AF_INET;
152 | s.sin_port = htons(NETLOADER_SERVER_PORT);
153 | s.sin_addr.s_addr = INADDR_BROADCAST;
154 |
155 | memset(&rs, '\0', sizeof(struct sockaddr_in));
156 | rs.sin_family = AF_INET;
157 | rs.sin_port = htons(NETLOADER_CLIENT_PORT);
158 | rs.sin_addr.s_addr = INADDR_ANY;
159 |
160 | int recvSock = socket(PF_INET, SOCK_DGRAM, 0);
161 |
162 | if (recvSock < 0) socketError("create receive socket");
163 |
164 | if (bind(recvSock, (struct sockaddr*) &rs, sizeof(rs)) < 0) socketError("bind receive socket");
165 | setSocketNonblocking(recvSock);
166 |
167 | while (retries) {
168 | if (sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(s)) < 0)
169 | socketError("sendto");
170 |
171 | if (pollSocket(recvSock, POLLIN, 150) == 0) {
172 | socklen_t socklen = sizeof(remote);
173 | len = recvfrom(recvSock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&remote, &socklen);
174 | if (len != -1) {
175 | if (strncmp("bootnx", recvbuf, strlen("bootnx")) == 0) {
176 | break;
177 | }
178 | }
179 | }
180 |
181 | --retries;
182 | }
183 |
184 | if (retries == 0)
185 | remote.sin_addr.s_addr = INADDR_NONE;
186 |
187 | shutdownSocket(broadcastSock, 0);
188 | shutdownSocket(recvSock, SHUT_RD);
189 |
190 | return remote.sin_addr;
191 | }
192 |
193 | //---------------------------------------------------------------------------------
194 | static int sendData(int sock, int sendsize, void *buffer) {
195 | //---------------------------------------------------------------------------------
196 | char *buf = (char*)buffer;
197 | while (sendsize) {
198 | if (pollSocket(sock, POLLOUT, -1))
199 | return 1;
200 |
201 | int len = send(sock, buf, sendsize, 0);
202 | if (len == 0)
203 | return 1;
204 |
205 | if (len == -1) {
206 | if (socketError("send") != EWOULDBLOCK)
207 | return 1;
208 | } else {
209 | sendsize -= len;
210 | buf += len;
211 | }
212 | }
213 |
214 | return sendsize != 0;
215 | }
216 |
217 | //---------------------------------------------------------------------------------
218 | static int recvData(int sock, void *buffer, int size, int flags) {
219 | //---------------------------------------------------------------------------------
220 | int len, sizeleft = size;
221 | char *buf = (char*)buffer;
222 | while (sizeleft) {
223 | if (pollSocket(sock, POLLIN, -1))
224 | return 0;
225 |
226 | len = recv(sock,buf,sizeleft,flags);
227 | if (len == 0)
228 | return 0;
229 |
230 | if (len == -1) {
231 | if (socketError("recv") != EWOULDBLOCK)
232 | return 0;
233 | } else {
234 | sizeleft -=len;
235 | buf +=len;
236 | }
237 | }
238 |
239 | return size;
240 | }
241 |
242 |
243 | //---------------------------------------------------------------------------------
244 | static int sendInt32LE(int socket, uint32_t size) {
245 | //---------------------------------------------------------------------------------
246 | unsigned char lenbuf[4];
247 | lenbuf[0] = size & 0xff;
248 | lenbuf[1] = (size >> 8) & 0xff;
249 | lenbuf[2] = (size >> 16) & 0xff;
250 | lenbuf[3] = (size >> 24) & 0xff;
251 |
252 | return sendData(socket, 4, lenbuf);
253 | }
254 |
255 | //---------------------------------------------------------------------------------
256 | static int recvInt32LE(int socket, int32_t *data) {
257 | //---------------------------------------------------------------------------------
258 | unsigned char intbuf[4];
259 | int len = recvData(socket, intbuf, 4, 0);
260 |
261 | if (len == 4) {
262 | *data = intbuf[0] & 0xff + (intbuf[1] << 8) + (intbuf[2] << 16) + (intbuf[3] << 24);
263 | return 0;
264 | }
265 |
266 | return -1;
267 | }
268 |
269 | static unsigned char in[ZLIB_CHUNK];
270 | static unsigned char out[ZLIB_CHUNK];
271 |
272 | //---------------------------------------------------------------------------------
273 | static int sendNROFile(in_addr_t nxaddr, char *name, size_t filesize, FILE *fh) {
274 | //---------------------------------------------------------------------------------
275 |
276 | int retval = 0;
277 |
278 | int ret, flush;
279 | unsigned have;
280 | z_stream strm;
281 |
282 | /* allocate deflate state */
283 | strm.zalloc = Z_NULL;
284 | strm.zfree = Z_NULL;
285 | strm.opaque = Z_NULL;
286 | ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
287 | if (ret != Z_OK) return ret;
288 |
289 | int sock = socket(AF_INET,SOCK_STREAM,0);
290 | if (sock < 0) {
291 | socketError("create connection socket");
292 | return -1;
293 | }
294 |
295 | struct sockaddr_in s;
296 | memset(&s, '\0', sizeof(struct sockaddr_in));
297 | s.sin_family = AF_INET;
298 | s.sin_port = htons(NETLOADER_SERVER_PORT);
299 | s.sin_addr.s_addr = nxaddr;
300 |
301 | if (connect(sock,(struct sockaddr *)&s,sizeof(s)) < 0) {
302 | struct in_addr address;
303 | address.s_addr = nxaddr;
304 | fprintf(stderr,"Connection to %s failed\n",inet_ntoa(address));
305 | return -1;
306 | }
307 |
308 | int namelen = strlen(name);
309 |
310 | if (sendInt32LE(sock,namelen)) {
311 | fprintf(stderr,"Failed sending filename length\n");
312 | retval = -1;
313 | goto error;
314 | }
315 |
316 | if (sendData(sock,namelen,name)) {
317 | fprintf(stderr,"Failed sending filename\n");
318 | retval = -1;
319 | goto error;
320 | }
321 |
322 | if (sendInt32LE(sock,filesize)) {
323 | fprintf(stderr,"Failed sending file length\n");
324 | retval = -1;
325 | goto error;
326 | }
327 |
328 | int response;
329 |
330 | if (recvInt32LE(sock,&response)!=0) {
331 | fprintf(stderr,"Invalid response\n");
332 | retval = 1;
333 | goto error;
334 | }
335 |
336 | if (response!=0) {
337 | switch(response) {
338 | case -1:
339 | fprintf(stderr,"Failed to create file\n");
340 | break;
341 | case -2:
342 | fprintf(stderr,"Insufficient space\n");
343 | break;
344 | case -3:
345 | fprintf(stderr,"Insufficient memory\n");
346 | break;
347 | }
348 | retval = 1;
349 | goto error;
350 | }
351 |
352 | printf("Sending %s, %zd bytes\n",name, filesize);
353 |
354 | size_t totalsent = 0, blocks = 0;
355 |
356 |
357 | do {
358 | strm.avail_in = fread(in, 1, ZLIB_CHUNK, fh);
359 | if (ferror(fh)) {
360 | (void)deflateEnd(&strm);
361 | return Z_ERRNO;
362 | }
363 | flush = feof(fh) ? Z_FINISH : Z_NO_FLUSH;
364 | strm.next_in = in;
365 | /* run deflate() on input until output buffer not full, finish
366 | compression if all of source has been read in */
367 | do {
368 | strm.avail_out = ZLIB_CHUNK;
369 | strm.next_out = out;
370 | ret = deflate(&strm, flush); /* no bad return value */
371 | assert(ret != Z_STREAM_ERROR); /* state not clobbered */
372 | have = ZLIB_CHUNK - strm.avail_out;
373 |
374 | if (have != 0) {
375 | if (sendInt32LE(sock,have)) {
376 | fprintf(stderr,"Failed sending chunk size\n");
377 | retval = -1;
378 | goto error;
379 | }
380 |
381 | if (sendData(sock,have,out)) {
382 | fprintf(stderr,"Failed sending %s\n", name);
383 | retval = 1;
384 | (void)deflateEnd(&strm);
385 | goto error;
386 | }
387 |
388 | totalsent += have;
389 | blocks++;
390 | }
391 | } while (strm.avail_out == 0);
392 | assert(strm.avail_in == 0); /* all input will be used */
393 | /* done when last data in file processed */
394 | } while (flush != Z_FINISH);
395 | assert(ret == Z_STREAM_END); /* stream will be complete */
396 | (void)deflateEnd(&strm);
397 |
398 | printf("%zu sent (%.2f%%), %zd blocks\n",totalsent, (float)(totalsent * 100.0)/ filesize, blocks);
399 |
400 | if (recvInt32LE(sock,&response)!=0) {
401 | fprintf(stderr,"Failed sending %s\n",name);
402 | retval = 1;
403 | goto error;
404 | }
405 |
406 |
407 | if (sendData(sock,cmdlen+4,(unsigned char*)cmdbuf)) {
408 |
409 | fprintf(stderr,"Failed sending command line\n");
410 | retval = 1;
411 |
412 | }
413 |
414 | error:
415 | shutdownSocket(sock, SHUT_WR);
416 | return retval;
417 | }
418 |
419 | //---------------------------------------------------------------------------------
420 | static void showHelp() {
421 | //---------------------------------------------------------------------------------
422 | puts("Usage: nxlink [options] nrofile\n");
423 | puts("--help, -h Display this information");
424 | puts("--address, -a Hostname or IPv4 address of Switch");
425 | puts("--retries, -r number of times to ping before giving up");
426 | puts("--path , -p set upload path for file");
427 | puts("--args args to send to nro");
428 | puts("--server , -s start server after completed upload");
429 | puts("\n");
430 | }
431 |
432 |
433 | //---------------------------------------------------------------------------------
434 | static int addExtraArgs(int len, char *buf, char *extra_args) {
435 | //---------------------------------------------------------------------------------
436 |
437 | if (NULL==extra_args) return len;
438 |
439 |
440 | int extra_len = strlen(extra_args);
441 |
442 | char *dst = &buf[len];
443 | char *src = extra_args;
444 |
445 | do {
446 | int c;
447 |
448 | do {
449 | c = *src++;
450 | extra_len--;
451 | } while (c ==' ' && extra_len >= 0);
452 |
453 | if (c == '\"' || c == '\'') {
454 | int quote = c;
455 | do {
456 | c = *src++;
457 | if (c != quote) *dst++ = c;
458 | extra_len--;
459 | } while (c != quote && extra_len >= 0);
460 |
461 | *dst++ = '\0';
462 |
463 | continue;
464 | }
465 | do {
466 | *dst++ = c;
467 | extra_len--;
468 | c = *src++;
469 | } while (c != ' ' && extra_len >= 0);
470 |
471 | *dst++ = '\0';
472 | } while (extra_len >= 0);
473 |
474 | return dst - buf;
475 | }
476 |
477 | #define NRO_ARGS 1000
478 |
479 | #ifdef __WIN32__
480 | static void win32_socket_cleanup(void) {
481 | WSACleanup();
482 | }
483 | #endif
484 |
485 | //---------------------------------------------------------------------------------
486 | int main(int argc, char **argv) {
487 | //---------------------------------------------------------------------------------
488 | char *address = NULL;
489 | char *basepath = NULL;
490 | char *finalpath = NULL;
491 | char *endarg = NULL;
492 | char *extra_args = NULL;
493 | int retries = 10;
494 | static int server = 0;
495 |
496 | if (argc < 2) {
497 | showHelp();
498 | return EXIT_FAILURE;
499 | }
500 |
501 | while (1) {
502 | static struct option long_options[] = {
503 | {"address", required_argument, 0, 'a'},
504 | {"retries", required_argument, 0, 'r'},
505 | {"path", required_argument, 0, 'p'},
506 | {"args", required_argument, 0, NRO_ARGS},
507 | {"help", no_argument, 0, 'h'},
508 | {"server", no_argument, &server, 1 },
509 | {0, 0, 0, 0}
510 | };
511 |
512 | /* getopt_long stores the option index here. */
513 | int option_index = 0, c;
514 |
515 | c = getopt_long (argc, argv, "a:r:hp:s", long_options, &option_index);
516 |
517 | /* Detect the end of the options. */
518 | if (c == -1)
519 | break;
520 |
521 | switch(c) {
522 |
523 | case 'a':
524 | address = optarg;
525 | break;
526 | case 'r':
527 | errno = 0;
528 | retries = strtoul(optarg, &endarg, 0);
529 | if (endarg == optarg) errno = EINVAL;
530 | if (errno != 0) {
531 | perror("--retries");
532 | exit(1);
533 | }
534 | break;
535 | case 'p':
536 | basepath = optarg;
537 | break;
538 | case 's':
539 | server = 1;
540 | break;
541 | case 'h':
542 | showHelp();
543 | return EXIT_FAILURE;
544 | case NRO_ARGS:
545 | extra_args=optarg;
546 | break;
547 | }
548 |
549 | }
550 |
551 | char *filename = argv[optind++];
552 | if (filename== NULL) {
553 | showHelp();
554 | return EXIT_FAILURE;
555 | }
556 |
557 | memset(cmdbuf, '\0', sizeof(cmdbuf));
558 |
559 | FILE *fh = fopen(filename,"rb");
560 | if (fh == NULL) {
561 | fprintf(stderr,"Failed to open %s\n",filename);
562 | return EXIT_FAILURE;
563 | }
564 |
565 | #ifdef _WIN32
566 | setvbuf(stdout, 0, _IONBF, 0);
567 | #endif
568 |
569 | fseek(fh,0,SEEK_END);
570 | size_t filesize = ftell(fh);
571 | fseek(fh,0,SEEK_SET);
572 |
573 | char *basename = NULL;
574 | if ((basename=strrchr(filename,'/'))!=NULL) {
575 | basename++;
576 | } else if ((basename=strrchr(filename,'\\'))!=NULL) {
577 | basename++;
578 | } else {
579 | basename = filename;
580 | }
581 |
582 | if (basepath) {
583 | size_t finalpath_len = strlen(basepath);
584 | if (basepath[finalpath_len] == '/') {
585 | finalpath_len += (strlen(basename) + 1);
586 | finalpath = malloc(finalpath_len);
587 | sprintf(finalpath, "%s%s", basepath, basename);
588 | } else {
589 | finalpath = basepath;
590 | }
591 | } else {
592 | finalpath = basename;
593 | }
594 |
595 | cmdlen = 0;
596 |
597 | for (int index = optind; index < argc; index++) {
598 | int len=strlen(argv[index]);
599 | if ((cmdlen + len + 5) >= (sizeof(cmdbuf) - 2)) break;
600 | strcpy(&cmdbuf[cmdlen+4],argv[index]);
601 | cmdlen+= len + 1;
602 | }
603 |
604 | cmdlen = addExtraArgs(cmdlen, &cmdbuf[4], extra_args);
605 |
606 | cmdbuf[0] = cmdlen & 0xff;
607 | cmdbuf[1] = (cmdlen>>8) & 0xff;
608 | cmdbuf[2] = (cmdlen>>16) & 0xff;
609 | cmdbuf[3] = (cmdlen>>24) & 0xff;
610 |
611 | #ifdef __WIN32__
612 | WSADATA wsa_data;
613 | if (WSAStartup (MAKEWORD(2,2), &wsa_data)) {
614 | printf ("WSAStartup failed\n");
615 | return EXIT_FAILURE;
616 | }
617 | atexit(&win32_socket_cleanup);
618 | #endif
619 |
620 | struct in_addr nxaddr;
621 | nxaddr.s_addr = INADDR_NONE;
622 |
623 | if (address == NULL) {
624 | nxaddr = findSwitch(retries);
625 |
626 | if (nxaddr.s_addr == INADDR_NONE) {
627 | printf("No response from Switch!\n");
628 | return EXIT_FAILURE;
629 | }
630 |
631 | } else {
632 | struct addrinfo *info;
633 | if (getaddrinfo(address, NULL, NULL, &info) == 0) {
634 | nxaddr = ((struct sockaddr_in*)info->ai_addr)->sin_addr;
635 | freeaddrinfo(info);
636 | }
637 | }
638 |
639 | if (nxaddr.s_addr == INADDR_NONE) {
640 | fprintf(stderr,"Invalid address\n");
641 | return EXIT_FAILURE;
642 | }
643 |
644 | int res = sendNROFile(nxaddr.s_addr,finalpath,filesize,fh);
645 |
646 | fclose(fh);
647 |
648 | if (res != 0)
649 | return EXIT_FAILURE;
650 |
651 | if (!server)
652 | return EXIT_SUCCESS;
653 |
654 | printf("starting server\n");
655 |
656 | struct sockaddr_in serv_addr;
657 |
658 | memset(&serv_addr, '0', sizeof(serv_addr));
659 | serv_addr.sin_family = AF_INET;
660 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
661 | serv_addr.sin_port = htons(NETLOADER_CLIENT_PORT);
662 |
663 | int listenfd = socket(AF_INET, SOCK_STREAM, 0);
664 | if (listenfd < 0) {
665 | socketError("socket");
666 | return EXIT_FAILURE;
667 | }
668 |
669 | int rc = bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
670 | if (rc != 0) {
671 | socketError("bind listen socket");
672 | shutdownSocket(listenfd, 0);
673 | return EXIT_FAILURE;
674 | }
675 |
676 | rc = setSocketNonblocking(listenfd);
677 | if (rc == -1) {
678 | socketError("listen fcntl");
679 | shutdownSocket(listenfd, 0);
680 | return EXIT_FAILURE;
681 | }
682 |
683 | rc = listen(listenfd, 10);
684 | if (rc != 0) {
685 | socketError("listen");
686 | shutdownSocket(listenfd, 0);
687 | return EXIT_FAILURE;
688 | }
689 |
690 | printf("server active ...\n");
691 |
692 | int datafd = -1;
693 |
694 | while (listenfd != -1 || datafd != -1) {
695 | struct sockaddr_in sa_remote;
696 |
697 | if (pollSocket(listenfd >= 0 ? listenfd : datafd, POLLIN, -1))
698 | break;
699 |
700 | if (listenfd >= 0) {
701 | socklen_t addrlen = sizeof(sa_remote);
702 | datafd = accept(listenfd, (struct sockaddr*)&sa_remote, &addrlen);
703 |
704 | if (datafd < 0 && socketError("accept") != EWOULDBLOCK)
705 | break;
706 |
707 | if (datafd >= 0) {
708 | shutdownSocket(listenfd, 0);
709 | listenfd = -1;
710 | }
711 | } else {
712 | char recvbuf[256];
713 | int len = recv(datafd, recvbuf, sizeof(recvbuf), 0);
714 |
715 | if (len == 0 || (len < 0 && socketError("recv") != EWOULDBLOCK)) {
716 | shutdownSocket(datafd, 0);
717 | datafd = -1;
718 | break;
719 | }
720 |
721 | if (len > 0)
722 | fwrite(recvbuf, 1, len, stdout);
723 | }
724 | }
725 |
726 | if (listenfd >= 0)
727 | shutdownSocket(listenfd, 0);
728 | if (datafd >= 0)
729 | shutdownSocket(datafd, SHUT_RD);
730 |
731 | printf("exiting ... \n");
732 |
733 | return EXIT_SUCCESS;
734 | }
735 |
--------------------------------------------------------------------------------
/src/romfs.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include "types.h"
8 | #include "romfs.h"
9 | #include "filepath.h"
10 |
11 | #include
12 | #include
13 |
14 | struct romfs_fent_ctx;
15 |
16 | typedef struct romfs_dirent_ctx {
17 | filepath_t sum_path;
18 | filepath_t cur_path;
19 | uint32_t entry_offset;
20 | struct romfs_dirent_ctx *parent; /* Parent node */
21 | struct romfs_dirent_ctx *child; /* Child node */
22 | struct romfs_dirent_ctx *sibling; /* Sibling node */
23 | struct romfs_fent_ctx *file; /* File node */
24 | struct romfs_dirent_ctx *next; /* Next node */
25 | } romfs_dirent_ctx_t;
26 |
27 | typedef struct romfs_fent_ctx {
28 | filepath_t sum_path;
29 | filepath_t cur_path;
30 | uint32_t entry_offset;
31 | uint64_t offset;
32 | uint64_t size;
33 | romfs_dirent_ctx_t *parent; /* Parent dir */
34 | struct romfs_fent_ctx *sibling; /* Sibling file */
35 | struct romfs_fent_ctx *next; /* Logical next file */
36 | } romfs_fent_ctx_t;
37 |
38 | typedef struct {
39 | romfs_fent_ctx_t *files;
40 | uint64_t num_dirs;
41 | uint64_t num_files;
42 | uint64_t dir_table_size;
43 | uint64_t file_table_size;
44 | uint64_t dir_hash_table_size;
45 | uint64_t file_hash_table_size;
46 | uint64_t file_partition_size;
47 | } romfs_ctx_t;
48 |
49 | typedef struct {
50 | uint64_t header_size;
51 | uint64_t dir_hash_table_ofs;
52 | uint64_t dir_hash_table_size;
53 | uint64_t dir_table_ofs;
54 | uint64_t dir_table_size;
55 | uint64_t file_hash_table_ofs;
56 | uint64_t file_hash_table_size;
57 | uint64_t file_table_ofs;
58 | uint64_t file_table_size;
59 | uint64_t file_partition_ofs;
60 | } romfs_header_t;
61 |
62 | typedef struct {
63 | uint32_t parent;
64 | uint32_t sibling;
65 | uint32_t child;
66 | uint32_t file;
67 | uint32_t hash;
68 | uint32_t name_size;
69 | char name[];
70 | } romfs_direntry_t;
71 |
72 | typedef struct {
73 | uint32_t parent;
74 | uint32_t sibling;
75 | uint64_t offset;
76 | uint64_t size;
77 | uint32_t hash;
78 | uint32_t name_size;
79 | char name[];
80 | } romfs_fentry_t;
81 |
82 | #define ROMFS_ENTRY_EMPTY 0xFFFFFFFF
83 | #define ROMFS_FILEPARTITION_OFS 0x200
84 |
85 | romfs_direntry_t *romfs_get_direntry(romfs_direntry_t *directories, uint32_t offset) {
86 | return (romfs_direntry_t *)((char *)directories + offset);
87 | }
88 |
89 | romfs_fentry_t *romfs_get_fentry(romfs_fentry_t *files, uint32_t offset) {
90 | return (romfs_fentry_t *)((char *)files + offset);
91 | }
92 |
93 | uint32_t calc_path_hash(uint32_t parent, const unsigned char *path, uint32_t start, size_t path_len) {
94 | uint32_t hash = parent ^ 123456789;
95 | for (uint32_t i = 0; i < path_len; i++) {
96 | hash = (hash >> 5) | (hash << 27);
97 | hash ^= path[start + i];
98 | }
99 |
100 | return hash;
101 | }
102 |
103 | uint32_t align(uint32_t offset, uint32_t alignment) {
104 | uint32_t mask = ~(alignment-1);
105 |
106 | return (offset + (alignment-1)) & mask;
107 | }
108 |
109 | uint64_t align64(uint64_t offset, uint64_t alignment) {
110 | uint64_t mask = ~(uint64_t)(alignment-1);
111 |
112 | return (offset + (alignment-1)) & mask;
113 | }
114 |
115 | uint32_t romfs_get_hash_table_count(uint32_t num_entries) {
116 | if (num_entries < 3) {
117 | return 3;
118 | } else if (num_entries < 19) {
119 | return num_entries | 1;
120 | }
121 | uint32_t count = num_entries;
122 | while (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 || count % 11 == 0 || count % 13 == 0 || count % 17 == 0) {
123 | count++;
124 | }
125 | return count;
126 | }
127 |
128 | void romfs_visit_dir(romfs_dirent_ctx_t *parent, romfs_ctx_t *romfs_ctx) {
129 | osdir_t *dir = NULL;
130 | osdirent_t *cur_dirent = NULL;
131 | romfs_dirent_ctx_t *child_dir_tree = NULL;
132 | romfs_fent_ctx_t *child_file_tree = NULL;
133 | romfs_dirent_ctx_t *cur_dir = NULL;
134 | romfs_fent_ctx_t *cur_file = NULL;
135 | filepath_t cur_path;
136 | filepath_t cur_sum_path;
137 |
138 | os_stat64_t cur_stats;
139 |
140 | if ((dir = os_opendir(parent->sum_path.os_path)) == NULL) {
141 | fprintf(stderr, "Failed to open directory %s!\n", parent->sum_path.char_path);
142 | exit(EXIT_FAILURE);
143 | }
144 |
145 | while ((cur_dirent = os_readdir(dir))) {
146 | filepath_init(&cur_path);
147 | filepath_set(&cur_path, "");
148 | filepath_os_append(&cur_path, cur_dirent->d_name);
149 |
150 | if (strcmp(cur_path.char_path, "/.") == 0 || strcmp(cur_path.char_path, "/..") == 0) {
151 | /* Special case . and .. */
152 | continue;
153 | }
154 |
155 | filepath_copy(&cur_sum_path, &parent->sum_path);
156 | filepath_os_append(&cur_sum_path, cur_dirent->d_name);
157 |
158 | if (os_stat(cur_sum_path.os_path, &cur_stats) == -1) {
159 | fprintf(stderr, "Failed to stat %s\n", cur_sum_path.char_path);
160 | exit(EXIT_FAILURE);
161 | }
162 |
163 | if ((cur_stats.st_mode & S_IFMT) == S_IFDIR) {
164 | /* Directory */
165 | if ((cur_dir = calloc(1, sizeof(romfs_dirent_ctx_t))) == NULL) {
166 | fprintf(stderr, "Failed to allocate RomFS directory context!\n");
167 | exit(EXIT_FAILURE);
168 | }
169 |
170 | romfs_ctx->num_dirs++;
171 |
172 | cur_dir->parent = parent;
173 | filepath_copy(&cur_dir->sum_path, &cur_sum_path);
174 | filepath_copy(&cur_dir->cur_path, &cur_path);
175 |
176 | romfs_ctx->dir_table_size += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);
177 |
178 | /* Ordered insertion on sibling */
179 | if (child_dir_tree == NULL || strcmp(cur_dir->sum_path.char_path, child_dir_tree->sum_path.char_path) < 0) {
180 | cur_dir->sibling = child_dir_tree;
181 | child_dir_tree = cur_dir;
182 | } else {
183 | romfs_dirent_ctx_t *child, *prev;
184 | prev = child_dir_tree;
185 | child = child_dir_tree->sibling;
186 | while (child != NULL) {
187 | if (strcmp(cur_dir->sum_path.char_path, child->sum_path.char_path) < 0) {
188 | break;
189 | }
190 | prev = child;
191 | child = child->sibling;
192 | }
193 |
194 | prev->sibling = cur_dir;
195 | cur_dir->sibling = child;
196 | }
197 |
198 | /* Ordered insertion on next */
199 | romfs_dirent_ctx_t *tmp = parent->next, *tmp_prev = parent;
200 | while (tmp != NULL) {
201 | if (strcmp(cur_dir->sum_path.char_path, tmp->sum_path.char_path) < 0) {
202 | break;
203 | }
204 | tmp_prev = tmp;
205 | tmp = tmp->next;
206 | }
207 | tmp_prev->next = cur_dir;
208 | cur_dir->next = tmp;
209 |
210 | cur_dir = NULL;
211 | } else if ((cur_stats.st_mode & S_IFMT) == S_IFREG) {
212 | /* File */
213 | if ((cur_file = calloc(1, sizeof(romfs_fent_ctx_t))) == NULL) {
214 | fprintf(stderr, "Failed to allocate RomFS File context!\n");
215 | exit(EXIT_FAILURE);
216 | }
217 |
218 | romfs_ctx->num_files++;
219 |
220 | cur_file->parent = parent;
221 | filepath_copy(&cur_file->sum_path, &cur_sum_path);
222 | filepath_copy(&cur_file->cur_path, &cur_path);
223 | cur_file->size = cur_stats.st_size;
224 |
225 | romfs_ctx->file_table_size += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);
226 |
227 | /* Ordered insertion on sibling */
228 | if (child_file_tree == NULL || strcmp(cur_file->sum_path.char_path, child_file_tree->sum_path.char_path) < 0) {
229 | cur_file->sibling = child_file_tree;
230 | child_file_tree = cur_file;
231 | } else {
232 | romfs_fent_ctx_t *child, *prev;
233 | prev = child_file_tree;
234 | child = child_file_tree->sibling;
235 | while (child != NULL) {
236 | if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {
237 | break;
238 | }
239 | prev = child;
240 | child = child->sibling;
241 | }
242 |
243 | prev->sibling = cur_file;
244 | cur_file->sibling = child;
245 | }
246 |
247 | /* Ordered insertion on next */
248 | if (romfs_ctx->files == NULL || strcmp(cur_file->sum_path.char_path, romfs_ctx->files->sum_path.char_path) < 0) {
249 | cur_file->next = romfs_ctx->files;
250 | romfs_ctx->files = cur_file;
251 | } else {
252 | romfs_fent_ctx_t *child, *prev;
253 | prev = romfs_ctx->files;
254 | child = romfs_ctx->files->next;
255 | while (child != NULL) {
256 | if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {
257 | break;
258 | }
259 | prev = child;
260 | child = child->next;
261 | }
262 |
263 | prev->next = cur_file;
264 | cur_file->next = child;
265 | }
266 |
267 | cur_file = NULL;
268 | } else {
269 | fprintf(stderr, "Invalid FS object type for %s!\n", cur_path.char_path);
270 | exit(EXIT_FAILURE);
271 | }
272 | }
273 |
274 | os_closedir(dir);
275 | parent->child = child_dir_tree;
276 | parent->file = child_file_tree;
277 |
278 | cur_dir = child_dir_tree;
279 | while (cur_dir != NULL) {
280 | romfs_visit_dir(cur_dir, romfs_ctx);
281 | cur_dir = cur_dir->sibling;
282 | }
283 | }
284 |
285 | size_t build_romfs_into_file(filepath_t *in_dirpath, FILE *f_out, off_t base_offset) {
286 | romfs_dirent_ctx_t *root_ctx = calloc(1, sizeof(romfs_dirent_ctx_t));
287 | if (root_ctx == NULL) {
288 | fprintf(stderr, "Failed to allocate root context!\n");
289 | exit(EXIT_FAILURE);
290 | }
291 |
292 | root_ctx->parent = root_ctx;
293 |
294 | romfs_ctx_t romfs_ctx;
295 | memset(&romfs_ctx, 0, sizeof(romfs_ctx));
296 |
297 | filepath_copy(&root_ctx->sum_path, in_dirpath);
298 | filepath_init(&root_ctx->cur_path);
299 | filepath_set(&root_ctx->cur_path, "");
300 | romfs_ctx.dir_table_size = 0x18; /* Root directory. */
301 | romfs_ctx.num_dirs = 1;
302 |
303 | /* Visit all directories. */
304 | printf("Visiting directories...\n");
305 | romfs_visit_dir(root_ctx, &romfs_ctx);
306 | uint32_t dir_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_dirs);
307 | uint32_t file_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_files);
308 | romfs_ctx.dir_hash_table_size = 4 * dir_hash_table_entry_count;
309 | romfs_ctx.file_hash_table_size = 4 * file_hash_table_entry_count;
310 |
311 | romfs_header_t header;
312 | memset(&header, 0, sizeof(header));
313 | romfs_fent_ctx_t *cur_file = NULL;
314 | romfs_dirent_ctx_t *cur_dir = NULL;
315 | uint32_t entry_offset = 0;
316 |
317 |
318 | uint32_t *dir_hash_table = malloc(romfs_ctx.dir_hash_table_size);
319 | if (dir_hash_table == NULL) {
320 | fprintf(stderr, "Failed to allocate directory hash table!\n");
321 | exit(EXIT_FAILURE);
322 | }
323 |
324 | for (uint32_t i = 0; i < dir_hash_table_entry_count; i++) {
325 | dir_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);
326 | }
327 |
328 | uint32_t *file_hash_table = malloc(romfs_ctx.file_hash_table_size);
329 | if (file_hash_table == NULL) {
330 | fprintf(stderr, "Failed to allocate file hash table!\n");
331 | exit(EXIT_FAILURE);
332 | }
333 |
334 | for (uint32_t i = 0; i < file_hash_table_entry_count; i++) {
335 | file_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);
336 | }
337 |
338 | romfs_direntry_t *dir_table = calloc(1, romfs_ctx.dir_table_size);
339 | if (dir_table == NULL) {
340 | fprintf(stderr, "Failed to allocate directory table!\n");
341 | exit(EXIT_FAILURE);
342 | }
343 |
344 | romfs_fentry_t *file_table = calloc(1, romfs_ctx.file_table_size);
345 | if (file_table == NULL) {
346 | fprintf(stderr, "Failed to allocate file table!\n");
347 | exit(EXIT_FAILURE);
348 | }
349 |
350 | printf("Calculating metadata...\n");
351 | /* Determine file offsets. */
352 | cur_file = romfs_ctx.files;
353 | entry_offset = 0;
354 | while (cur_file != NULL) {
355 | romfs_ctx.file_partition_size = align64(romfs_ctx.file_partition_size, 0x10);
356 | cur_file->offset = romfs_ctx.file_partition_size;
357 | romfs_ctx.file_partition_size += cur_file->size;
358 | cur_file->entry_offset = entry_offset;
359 | entry_offset += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);
360 | cur_file = cur_file->next;
361 | }
362 |
363 | /* Determine dir offsets. */
364 | cur_dir = root_ctx;
365 | entry_offset = 0;
366 | while (cur_dir != NULL) {
367 | cur_dir->entry_offset = entry_offset;
368 | if (cur_dir == root_ctx) {
369 | entry_offset += 0x18;
370 | } else {
371 | entry_offset += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);
372 | }
373 | cur_dir = cur_dir->next;
374 | }
375 |
376 | /* Populate file tables. */
377 | cur_file = romfs_ctx.files;
378 | while (cur_file != NULL) {
379 | romfs_fentry_t *cur_entry = romfs_get_fentry(file_table, cur_file->entry_offset);
380 | cur_entry->parent = le_word(cur_file->parent->entry_offset);
381 | cur_entry->sibling = le_word(cur_file->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset);
382 | cur_entry->offset = le_dword(cur_file->offset);
383 | cur_entry->size = le_dword(cur_file->size);
384 |
385 | uint32_t name_size = strlen(cur_file->cur_path.char_path)-1;
386 | uint32_t hash = calc_path_hash(cur_file->parent->entry_offset, (unsigned char *)cur_file->cur_path.char_path, 1, name_size);
387 | cur_entry->hash = file_hash_table[hash % file_hash_table_entry_count];
388 | file_hash_table[hash % file_hash_table_entry_count] = le_word(cur_file->entry_offset);
389 |
390 | cur_entry->name_size = name_size;
391 | memcpy(cur_entry->name, cur_file->cur_path.char_path + 1, name_size);
392 |
393 | cur_file = cur_file->next;
394 | }
395 |
396 | /* Populate dir tables. */
397 | cur_dir = root_ctx;
398 | while (cur_dir != NULL) {
399 | romfs_direntry_t *cur_entry = romfs_get_direntry(dir_table, cur_dir->entry_offset);
400 | cur_entry->parent = le_word(cur_dir->parent->entry_offset);
401 | cur_entry->sibling = le_word(cur_dir->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->sibling->entry_offset);
402 | cur_entry->child = le_word(cur_dir->child == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->child->entry_offset);
403 | cur_entry->file = le_word(cur_dir->file == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->file->entry_offset);
404 |
405 | uint32_t name_size = (cur_dir == root_ctx) ? 0 : strlen(cur_dir->cur_path.char_path)-1;
406 | uint32_t hash = calc_path_hash((cur_dir == root_ctx) ? 0 : cur_dir->parent->entry_offset, (unsigned char *)cur_dir->cur_path.char_path, 1, name_size);
407 | cur_entry->hash = dir_hash_table[hash % dir_hash_table_entry_count];
408 | dir_hash_table[hash % dir_hash_table_entry_count] = le_word(cur_dir->entry_offset);
409 |
410 | cur_entry->name_size = name_size;
411 | memcpy(cur_entry->name, cur_dir->cur_path.char_path + 1, name_size);
412 |
413 | cur_dir = cur_dir->next;
414 | }
415 |
416 | header.header_size = le_dword(sizeof(header));
417 | header.file_hash_table_size = le_dword(romfs_ctx.file_hash_table_size);
418 | header.file_table_size = le_dword(romfs_ctx.file_table_size);
419 | header.dir_hash_table_size = le_dword(romfs_ctx.dir_hash_table_size);
420 | header.dir_table_size = le_dword(romfs_ctx.dir_table_size);
421 | header.file_partition_ofs = le_dword(ROMFS_FILEPARTITION_OFS);
422 |
423 | /* Abuse of endianness follows. */
424 | uint64_t dir_hash_table_ofs = align64(romfs_ctx.file_partition_size + ROMFS_FILEPARTITION_OFS, 4);
425 | header.dir_hash_table_ofs = dir_hash_table_ofs;
426 | header.dir_table_ofs = header.dir_hash_table_ofs + romfs_ctx.dir_hash_table_size;
427 | header.file_hash_table_ofs = header.dir_table_ofs + romfs_ctx.dir_table_size;
428 | header.file_table_ofs = header.file_hash_table_ofs + romfs_ctx.file_hash_table_size;
429 | header.dir_hash_table_ofs = le_dword(header.dir_hash_table_ofs);
430 | header.dir_table_ofs = le_dword(header.dir_table_ofs);
431 | header.file_hash_table_ofs = le_dword(header.file_hash_table_ofs);
432 | header.file_table_ofs = le_dword(header.file_table_ofs);
433 |
434 | fseeko64(f_out, base_offset, SEEK_SET);
435 | fwrite(&header, 1, sizeof(header), f_out);
436 |
437 | /* Write files. */
438 | unsigned char *buffer = malloc(0x400000);
439 | if (buffer == NULL) {
440 | fprintf(stderr, "Failed to allocate work buffer!\n");
441 | exit(EXIT_FAILURE);
442 | }
443 | cur_file = romfs_ctx.files;
444 | while (cur_file != NULL) {
445 | FILE *f_in = os_fopen(cur_file->sum_path.os_path, OS_MODE_READ);
446 | if (f_in == NULL) {
447 | fprintf(stderr, "Failed to open %s!\n", cur_file->sum_path.char_path);
448 | exit(EXIT_FAILURE);
449 | }
450 |
451 | printf("Writing %s to RomFS image...\n", cur_file->sum_path.char_path);
452 | fseeko64(f_out, base_offset + cur_file->offset + ROMFS_FILEPARTITION_OFS, SEEK_SET);
453 | uint64_t offset = 0;
454 | uint64_t read_size = 0x400000;
455 | while (offset < cur_file->size) {
456 | if (cur_file->size - offset < read_size) {
457 | read_size = cur_file->size - offset;
458 | }
459 |
460 | if (fread(buffer, 1, read_size, f_in) != read_size) {
461 | fprintf(stderr, "Failed to read from %s!\n", cur_file->sum_path.char_path);
462 | exit(EXIT_FAILURE);
463 | }
464 |
465 | if (fwrite(buffer, 1, read_size, f_out) != read_size) {
466 | fprintf(stderr, "Failed to write to output!\n");
467 | exit(EXIT_FAILURE);
468 | }
469 |
470 | offset += read_size;
471 | }
472 |
473 | os_fclose(f_in);
474 |
475 | cur_file = cur_file->next;
476 | }
477 | free(buffer);
478 |
479 | /* Free all files. */
480 | cur_file = romfs_ctx.files;
481 | while (cur_file != NULL) {
482 | romfs_fent_ctx_t *temp = cur_file;
483 | cur_file = cur_file->next;
484 | free(temp);
485 | }
486 | romfs_ctx.files = NULL;
487 |
488 | /* Free all directories. */
489 | cur_dir = root_ctx;
490 | while (cur_dir != NULL) {
491 | romfs_dirent_ctx_t *temp = cur_dir;
492 | cur_dir = cur_dir->next;
493 | free(temp);
494 | }
495 | root_ctx = NULL;
496 |
497 | fseeko64(f_out, base_offset + dir_hash_table_ofs, SEEK_SET);
498 | if (fwrite(dir_hash_table, 1, romfs_ctx.dir_hash_table_size, f_out) != romfs_ctx.dir_hash_table_size) {
499 | fprintf(stderr, "Failed to write dir hash table!\n");
500 | exit(EXIT_FAILURE);
501 | }
502 | free(dir_hash_table);
503 |
504 | if (fwrite(dir_table, 1, romfs_ctx.dir_table_size, f_out) != romfs_ctx.dir_table_size) {
505 | fprintf(stderr, "Failed to write dir table!\n");
506 | exit(EXIT_FAILURE);
507 | }
508 | free(dir_table);
509 |
510 | if (fwrite(file_hash_table, 1, romfs_ctx.file_hash_table_size, f_out) != romfs_ctx.file_hash_table_size) {
511 | fprintf(stderr, "Failed to write file hash table!\n");
512 | exit(EXIT_FAILURE);
513 | }
514 | free(file_hash_table);
515 |
516 | if (fwrite(file_table, 1, romfs_ctx.file_table_size, f_out) != romfs_ctx.file_table_size) {
517 | fprintf(stderr, "Failed to write file table!\n");
518 | exit(EXIT_FAILURE);
519 | }
520 | free(file_table);
521 |
522 | return dir_hash_table_ofs + romfs_ctx.dir_hash_table_size + romfs_ctx.dir_table_size + romfs_ctx.file_hash_table_size + romfs_ctx.file_table_size;
523 | }
524 |
525 | size_t build_romfs(filepath_t *in_dirpath, filepath_t *out_romfspath) {
526 | FILE *f_out = NULL;
527 |
528 | if ((f_out = os_fopen(out_romfspath->os_path, OS_MODE_WRITE)) == NULL) {
529 | fprintf(stderr, "Failed to open %s!\n", out_romfspath->char_path);
530 | exit(EXIT_FAILURE);
531 | }
532 |
533 | size_t sz = build_romfs_into_file(in_dirpath, f_out, 0);
534 |
535 | fclose(f_out);
536 | return sz;
537 | }
538 |
539 | size_t build_romfs_by_paths(char *dir, char *out_fn) {
540 | filepath_t dirpath;
541 | filepath_t outpath;
542 |
543 | filepath_init(&dirpath);
544 | filepath_init(&outpath);
545 |
546 | filepath_set(&dirpath, dir);
547 | filepath_set(&outpath, out_fn);
548 |
549 | return build_romfs(&dirpath, &outpath);
550 | }
551 |
552 | size_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t offset) {
553 | filepath_t dirpath;
554 |
555 | filepath_init(&dirpath);
556 |
557 | filepath_set(&dirpath, dir);
558 |
559 | return build_romfs_into_file(&dirpath, f_out, offset);
560 | }
561 |
--------------------------------------------------------------------------------
/src/romfs.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "filepath.h"
4 |
5 | size_t build_romfs_by_paths(char *dir, char *out_fn);
6 |
7 | size_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t base_offset);
--------------------------------------------------------------------------------
/src/sha256.c:
--------------------------------------------------------------------------------
1 | /*********************************************************************
2 | * Filename: sha256.c
3 | * Author: Brad Conte (brad AT bradconte.com)
4 | * Copyright:
5 | * Disclaimer: This code is presented "as is" without any guarantees.
6 | * Details: Implementation of the SHA-256 hashing algorithm.
7 | SHA-256 is one of the three algorithms in the SHA2
8 | specification. The others, SHA-384 and SHA-512, are not
9 | offered in this implementation.
10 | Algorithm specification can be found here:
11 | * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
12 | This implementation uses little endian byte order.
13 | *********************************************************************/
14 |
15 | /*************************** HEADER FILES ***************************/
16 | #include
17 | #include
18 | #include "sha256.h"
19 |
20 | /****************************** MACROS ******************************/
21 | #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
22 | #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
23 |
24 | #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
25 | #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
26 | #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
27 | #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
28 | #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
29 | #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
30 |
31 | /**************************** VARIABLES *****************************/
32 | static const WORD k[64] = {
33 | 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
34 | 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
35 | 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
36 | 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
37 | 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
38 | 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
39 | 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
40 | 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
41 | };
42 |
43 | /*********************** FUNCTION DEFINITIONS ***********************/
44 | void sha256_transform(SHA256_CTX *ctx, const BYTE data[])
45 | {
46 | WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
47 |
48 | for (i = 0, j = 0; i < 16; ++i, j += 4)
49 | m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);
50 | for ( ; i < 64; ++i)
51 | m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
52 |
53 | a = ctx->state[0];
54 | b = ctx->state[1];
55 | c = ctx->state[2];
56 | d = ctx->state[3];
57 | e = ctx->state[4];
58 | f = ctx->state[5];
59 | g = ctx->state[6];
60 | h = ctx->state[7];
61 |
62 | for (i = 0; i < 64; ++i) {
63 | t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
64 | t2 = EP0(a) + MAJ(a,b,c);
65 | h = g;
66 | g = f;
67 | f = e;
68 | e = d + t1;
69 | d = c;
70 | c = b;
71 | b = a;
72 | a = t1 + t2;
73 | }
74 |
75 | ctx->state[0] += a;
76 | ctx->state[1] += b;
77 | ctx->state[2] += c;
78 | ctx->state[3] += d;
79 | ctx->state[4] += e;
80 | ctx->state[5] += f;
81 | ctx->state[6] += g;
82 | ctx->state[7] += h;
83 | }
84 |
85 | void sha256_init(SHA256_CTX *ctx)
86 | {
87 | ctx->datalen = 0;
88 | ctx->bitlen = 0;
89 | ctx->state[0] = 0x6a09e667;
90 | ctx->state[1] = 0xbb67ae85;
91 | ctx->state[2] = 0x3c6ef372;
92 | ctx->state[3] = 0xa54ff53a;
93 | ctx->state[4] = 0x510e527f;
94 | ctx->state[5] = 0x9b05688c;
95 | ctx->state[6] = 0x1f83d9ab;
96 | ctx->state[7] = 0x5be0cd19;
97 | }
98 |
99 | void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len)
100 | {
101 | WORD i;
102 |
103 | for (i = 0; i < len; ++i) {
104 | ctx->data[ctx->datalen] = data[i];
105 | ctx->datalen++;
106 | if (ctx->datalen == 64) {
107 | sha256_transform(ctx, ctx->data);
108 | ctx->bitlen += 512;
109 | ctx->datalen = 0;
110 | }
111 | }
112 | }
113 |
114 | void sha256_final(SHA256_CTX *ctx, BYTE hash[])
115 | {
116 | WORD i;
117 |
118 | i = ctx->datalen;
119 |
120 | // Pad whatever data is left in the buffer.
121 | if (ctx->datalen < 56) {
122 | ctx->data[i++] = 0x80;
123 | while (i < 56)
124 | ctx->data[i++] = 0x00;
125 | }
126 | else {
127 | ctx->data[i++] = 0x80;
128 | while (i < 64)
129 | ctx->data[i++] = 0x00;
130 | sha256_transform(ctx, ctx->data);
131 | memset(ctx->data, 0, 56);
132 | }
133 |
134 | // Append to the padding the total message's length in bits and transform.
135 | ctx->bitlen += ctx->datalen * 8;
136 | ctx->data[63] = ctx->bitlen;
137 | ctx->data[62] = ctx->bitlen >> 8;
138 | ctx->data[61] = ctx->bitlen >> 16;
139 | ctx->data[60] = ctx->bitlen >> 24;
140 | ctx->data[59] = ctx->bitlen >> 32;
141 | ctx->data[58] = ctx->bitlen >> 40;
142 | ctx->data[57] = ctx->bitlen >> 48;
143 | ctx->data[56] = ctx->bitlen >> 56;
144 | sha256_transform(ctx, ctx->data);
145 |
146 | // Since this implementation uses little endian byte ordering and SHA uses big endian,
147 | // reverse all the bytes when copying the final state to the output hash.
148 | for (i = 0; i < 4; ++i) {
149 | hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
150 | hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
151 | hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
152 | hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
153 | hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
154 | hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;
155 | hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;
156 | hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/src/sha256.h:
--------------------------------------------------------------------------------
1 | /*********************************************************************
2 | * Filename: sha256.h
3 | * Author: Brad Conte (brad AT bradconte.com)
4 | * Copyright:
5 | * Disclaimer: This code is presented "as is" without any guarantees.
6 | * Details: Defines the API for the corresponding SHA1 implementation.
7 | *********************************************************************/
8 |
9 | #ifndef SHA256_H
10 | #define SHA256_H
11 |
12 | /*************************** HEADER FILES ***************************/
13 | #include
14 |
15 | /****************************** MACROS ******************************/
16 | #define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest
17 |
18 | /**************************** DATA TYPES ****************************/
19 | typedef unsigned char BYTE; // 8-bit byte
20 | typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
21 |
22 | typedef struct {
23 | BYTE data[64];
24 | WORD datalen;
25 | unsigned long long bitlen;
26 | WORD state[8];
27 | } SHA256_CTX;
28 |
29 | /*********************** FUNCTION DECLARATIONS **********************/
30 | void sha256_init(SHA256_CTX *ctx);
31 | void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);
32 | void sha256_final(SHA256_CTX *ctx, BYTE hash[]);
33 |
34 | #endif // SHA256_H
35 |
--------------------------------------------------------------------------------
/src/types.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include
3 |
4 | typedef uint64_t dword_t;
5 | typedef uint32_t word_t;
6 | typedef uint16_t hword_t;
7 | typedef uint8_t byte_t;
8 | typedef int64_t dlong_t;
9 | typedef int32_t long_t;
10 | typedef int16_t short_t;
11 | typedef int8_t char_t;
12 | typedef uint64_t u64;
13 | typedef uint32_t u32;
14 | typedef uint16_t u16;
15 | typedef uint8_t u8;
16 |
17 | #define BIT(n) (1U << (n))
18 |
19 | static inline uint16_t __local_bswap16(uint16_t x) {
20 | return ((x << 8) & 0xff00) | ((x >> 8) & 0x00ff);
21 | }
22 |
23 |
24 | static inline uint32_t __local_bswap32(uint32_t x) {
25 | return ((x << 24) & 0xff000000 ) |
26 | ((x << 8) & 0x00ff0000 ) |
27 | ((x >> 8) & 0x0000ff00 ) |
28 | ((x >> 24) & 0x000000ff );
29 | }
30 |
31 | static inline uint64_t __local_bswap64(uint64_t x)
32 | {
33 | return (uint64_t)__local_bswap32(x>>32) |
34 | ((uint64_t)__local_bswap32(x&0xFFFFFFFF) << 32);
35 | }
36 |
37 | #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
38 | #define be_dword(a) __local_bswap64(a)
39 | #define be_word(a) __local_bswap32(a)
40 | #define be_hword(a) __local_bswap16(a)
41 | #define le_dword(a) (a)
42 | #define le_word(a) (a)
43 | #define le_hword(a) (a)
44 | #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
45 | #define be_dword(a) (a)
46 | #define be_word(a) (a)
47 | #define be_hword(a) (a)
48 | #define le_dword(a) __local_bswap64(a)
49 | #define le_word(a) __local_bswap32(a)
50 | #define le_hword(a) __local_bswap16(a)
51 | #else
52 | #error "What's the endianness of the platform you're targeting?"
53 | #endif
54 |
55 |
--------------------------------------------------------------------------------