Repository: switchbrew/switch-tools
Branch: master
Commit: 22756068dd0e
Files: 28
Total size: 268.1 KB
Directory structure:
gitextract_cljm8jeo/
├── .gitignore
├── AUTHORS
├── COPYING
├── ChangeLog
├── Makefile.am
├── NEWS
├── README
├── autogen.sh
├── configure.ac
└── src/
├── blz.c
├── blz.h
├── 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
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
build*
INSTALL
Makefile.in
aclocal.m4
autom4te.cache
config.guess
config.sub
configure
depcomp
install-sh
missing
compile
.deps
Makefile
config.status
config.log
.dirstamp
elf2nro
elf2nso
elf2kip
nacptool
npdmtool
nxlink
*.o
*.elf
*.kip
*.nro
*.nso
*.npdm
*.json
================================================
FILE: AUTHORS
================================================
================================================
FILE: COPYING
================================================
Copyright 2017 libnx Authors
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.
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.
================================================
FILE: ChangeLog
================================================
================================================
FILE: Makefile.am
================================================
# Makefile.am -- Process this file with automake to produce Makefile.in
bin_PROGRAMS = elf2nso elf2nro elf2kip build_pfs0 build_romfs nacptool npdmtool nxlink
build_pfs0_SOURCES = src/build_pfs0.c src/types.h
build_romfs_SOURCES = src/build_romfs.c src/romfs.c src/romfs.h src/filepath.c src/filepath.h src/types.h
elf2nro_SOURCES = src/elf2nro.c src/elf64.h src/romfs.c src/filepath.c src/filepath.h src/romfs.h src/elf_common.h
elf2nso_SOURCES = src/elf2nso.c src/sha256.c src/sha256.h src/elf64.h src/elf_common.h
elf2kip_SOURCES = src/elf2kip.c src/cJSON.c src/cJSON.h src/blz.c src/blz.h src/elf64.h src/elf_common.h
nacptool_SOURCES = src/nacptool.c
npdmtool_SOURCES = src/npdmtool.c src/cJSON.c src/cJSON.h
nxlink_SOURCES = src/nxlink.c
nxlink_CPPFLAGS = @ZLIB_CFLAGS@
nxlink_LDADD = @ZLIB_LIBS@ @NET_LIBS@
elf2nso_CPPFLAGS = @LZ4_CFLAGS@
elf2nso_LDADD = @LZ4_LIBS@
elf2nro_CPPFLAGS = @LZ4_CFLAGS@
elf2nro_LDADD = @LZ4_LIBS@
EXTRA_DIST = autogen.sh
================================================
FILE: NEWS
================================================
================================================
FILE: README
================================================
================================================
FILE: autogen.sh
================================================
aclocal
autoconf
automake --add-missing -c
================================================
FILE: configure.ac
================================================
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.61)
AC_INIT([switch-tools],[1.13.1],[https://github.com/switchbrew/switch-tools/issues])
AC_CONFIG_SRCDIR([src/build_pfs0.c])
AM_INIT_AUTOMAKE([subdir-objects])
AC_CANONICAL_BUILD
AC_CANONICAL_HOST
AC_PROG_CC
AC_SYS_LARGEFILE
PKG_CHECK_MODULES([LZ4],
[liblz4 >= 1.7.1 liblz4 < 100],
[have_lz4="yes"],
[PKG_CHECK_MODULES([LZ4],
[liblz4 >= 131],
[have_lz4="yes"])
])
PKG_CHECK_MODULES([ZLIB], zlib, [
AC_DEFINE([HAVE_LIBZ], [1], [Define if using zlib.])
])
NET_LIBS=""
case "$host" in
*-*-mingw*)
NET_LIBS="-lws2_32"
CFLAGS="$CFLAGS -D__USE_MINGW_ANSI_STDIO -D_WIN32_WINNT=0x0600"
;;
esac
CFLAGS="$CFLAGS -std=gnu99"
AC_SUBST(ZLIB_CFLAGS)
AC_SUBST(ZLIB_LIBS)
AC_SUBST(NET_LIBS)
AC_SUBST(LZ4_CFLAGS)
AC_SUBST(LZ4_LIBS)
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
================================================
FILE: src/blz.c
================================================
/*----------------------------------------------------------------------------*/
/*-- blz.c - Bottom LZ coding for Nintendo GBA/DS --*/
/*-- Copyright (C) 2011 CUE --*/
/*-- --*/
/*-- This program is free software: you can redistribute it and/or modify --*/
/*-- it under the terms of the GNU General Public License as published by --*/
/*-- the Free Software Foundation, either version 3 of the License, or --*/
/*-- (at your option) any later version. --*/
/*-- --*/
/*-- This program is distributed in the hope that it will be useful, --*/
/*-- but WITHOUT ANY WARRANTY; without even the implied warranty of --*/
/*-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --*/
/*-- GNU General Public License for more details. --*/
/*-- --*/
/*-- You should have received a copy of the GNU General Public License --*/
/*-- along with this program. If not, see . --*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
#include "blz.h"
#include
#include
#include
/*----------------------------------------------------------------------------*/
#define CMD_DECODE 0x00 // decode
#define CMD_ENCODE 0x01 // encode
#define BLZ_SHIFT 1 // bits to shift
#define BLZ_MASK 0x80 // bits to check:
// ((((1 << BLZ_SHIFT) - 1) << (8 - BLZ_SHIFT)
#define BLZ_THRESHOLD 2 // max number of bytes to not encode
#define BLZ_N 0x1002 // max offset ((1 << 12) + 2)
#define BLZ_F 0x12 // max coded ((1 << 4) + BLZ_THRESHOLD)
#define RAW_MINIM 0x00000000 // empty file, 0 bytes
#define RAW_MAXIM 0x00FFFFFF // 3-bytes length, 16MB - 1
#define BLZ_MINIM 0x00000004 // header only (empty RAW file)
#define BLZ_MAXIM 0x01400000 // 0x0120000A, padded to 20MB:
// * length, RAW_MAXIM
// * flags, (RAW_MAXIM + 7) / 8
// * header, 11
// 0x00FFFFFF + 0x00200000 + 12 + padding
/*----------------------------------------------------------------------------*/
#define BREAK(text) { printf(text); return; }
#define EXIT(text) { printf(text); exit(-1); }
/*----------------------------------------------------------------------------*/
u8 *Memory(int length, int size);
u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
void BLZ_Invert(u8 *buffer, int length);
/*----------------------------------------------------------------------------*/
u8 *Memory(int length, int size) {
u8 *fb;
fb = (u8 *) calloc(length * size, size);
if (fb == NULL) EXIT("\nMemory error\n");
return(fb);
}
/*----------------------------------------------------------------------------*/
void BLZ_Decode(char *filename) {
// u8 *pak_buffer, *raw_buffer, *pak, *raw, *pak_end, *raw_end;
// u32 pak_len, raw_len, len, pos, inc_len, hdr_len, enc_len, dec_len;
// u8 flags, mask;
// printf("- decoding '%s'", filename);
// // pak_buffer = Load(filename, &pak_len, BLZ_MINIM, BLZ_MAXIM);
// inc_len = *(u32 *)(pak_buffer + pak_len - 4);
// if (!inc_len) {
// enc_len = 0;
// dec_len = pak_len - 4;
// pak_len = 0;
// raw_len = dec_len;
// } else {
// if (pak_len < 8) EXIT("File has a bad header\n");
// hdr_len = pak_buffer[pak_len - 5];
// if ((hdr_len < 0x08) || (hdr_len > 0x0B)) EXIT("Bad header length\n");
// if (pak_len <= hdr_len) EXIT("Bad length\n");
// enc_len = *(u32 *)(pak_buffer + pak_len - 8) & 0x00FFFFFF;
// dec_len = pak_len - enc_len;
// pak_len = enc_len - hdr_len;
// raw_len = dec_len + enc_len + inc_len;
// if (raw_len > RAW_MAXIM) EXIT("Bad decoded length\n");
// }
// raw_buffer = (u8 *) Memory(raw_len, sizeof(char));
// pak = pak_buffer;
// raw = raw_buffer;
// pak_end = pak_buffer + dec_len + pak_len;
// raw_end = raw_buffer + raw_len;
// for (len = 0; len < dec_len; len++) *(raw++) = *(pak++);
// BLZ_Invert(pak_buffer + dec_len, pak_len);
// mask = 0;
// while (raw < raw_end) {
// if (!(mask >>= BLZ_SHIFT)) {
// if (pak == pak_end) break;
// flags = *pak++;
// mask = BLZ_MASK;
// }
// if (!(flags & mask)) {
// if (pak == pak_end) break;
// *raw++ = *pak++;
// } else {
// if (pak + 1 >= pak_end) break;
// pos = *pak++ << 8;
// pos |= *pak++;
// len = (pos >> 12) + BLZ_THRESHOLD + 1;
// if (raw + len > raw_end) {
// printf(", WARNING: wrong decoded length!");
// len = raw_end - raw;
// }
// pos = (pos & 0xFFF) + 3;
// while (len--) *(raw++) = *(raw - pos);
// }
// }
// BLZ_Invert(raw_buffer + dec_len, raw_len - dec_len);
// raw_len = raw - raw_buffer;
// if (raw != raw_end) printf(", WARNING: unexpected end of encoded file!");
// // Save(filename, raw_buffer, raw_len);
// free(raw_buffer);
// free(pak_buffer);
// printf("\n");
}
u8 *Load(char *filename, u32 *length, int min, int max) {
FILE *fp;
int fs;
u8 *fb;
if ((fp = fopen(filename, "rb")) == NULL) EXIT("\nFile open error\n");
fseek(fp, 0, SEEK_END);
fs = ftell(fp);
fseek(fp, 0, SEEK_SET);
if ((fs < min) || (fs > max)) EXIT("\nFile size error\n");
fb = Memory(fs + 3, sizeof(char));
if (fread(fb, 1, fs, fp) != fs) EXIT("\nFile read error\n");
if (fclose(fp) == EOF) EXIT("\nFile close error\n");
*length = fs;
return(fb);
}
/*----------------------------------------------------------------------------*/
u8* BLZ_Encode(char *filename, u32* pak_len, int mode) {
u8 *raw_buffer, *pak_buffer, *new_buffer;
u32 raw_len, new_len;
raw_buffer = Load(filename, &raw_len, RAW_MINIM, RAW_MAXIM);
pak_buffer = NULL;
*pak_len = BLZ_MAXIM + 1;
new_buffer = BLZ_Code(raw_buffer, raw_len, &new_len, mode);
if (new_len < *pak_len) {
if (pak_buffer != NULL) free(pak_buffer);
pak_buffer = new_buffer;
*pak_len = new_len;
}
return pak_buffer;
}
/*----------------------------------------------------------------------------*/
u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best) {
u8 *pak_buffer, *pak, *raw, *raw_end, *flg = NULL, *tmp;
u32 pak_len, inc_len, hdr_len, enc_len, len, pos, max;
u32 len_best, pos_best = 0, len_next, pos_next, len_post, pos_post;
u32 pak_tmp, raw_tmp;
u8 mask;
#define SEARCH(l,p) { \
l = BLZ_THRESHOLD; \
\
max = raw - raw_buffer >= BLZ_N ? BLZ_N : raw - raw_buffer; \
for (pos = 3; pos <= max; pos++) { \
for (len = 0; len < BLZ_F; len++) { \
if (raw + len == raw_end) break; \
if (len >= pos) break; \
if (*(raw + len) != *(raw + len - pos)) break; \
} \
\
if (len > l) { \
p = pos; \
if ((l = len) == BLZ_F) break; \
} \
} \
}
pak_tmp = 0;
raw_tmp = raw_len;
pak_len = raw_len + ((raw_len + 7) / 8) + 15;
pak_buffer = (u8 *) Memory(pak_len, sizeof(char));
BLZ_Invert(raw_buffer, raw_len);
pak = pak_buffer;
raw = raw_buffer;
raw_end = raw_buffer + raw_len;
mask = 0;
while (raw < raw_end) {
if (!(mask >>= BLZ_SHIFT)) {
*(flg = pak++) = 0;
mask = BLZ_MASK;
}
SEARCH(len_best, pos_best);
// LZ-CUE optimization start
if (best) {
if (len_best > BLZ_THRESHOLD) {
if (raw + len_best < raw_end) {
raw += len_best;
SEARCH(len_next, pos_next);
raw -= len_best - 1;
SEARCH(len_post, pos_post);
raw--;
if (len_next <= BLZ_THRESHOLD) len_next = 1;
if (len_post <= BLZ_THRESHOLD) len_post = 1;
if (len_best + len_next <= 1 + len_post) len_best = 1;
}
}
}
// LZ-CUE optimization end
*flg <<= 1;
if (len_best > BLZ_THRESHOLD) {
raw += len_best;
*flg |= 1;
*pak++ = ((len_best - (BLZ_THRESHOLD+1)) << 4) | ((pos_best - 3) >> 8);
*pak++ = (pos_best - 3) & 0xFF;
} else {
*pak++ = *raw++;
}
if (pak - pak_buffer + raw_len - (raw - raw_buffer) < pak_tmp + raw_tmp) {
pak_tmp = pak - pak_buffer;
raw_tmp = raw_len - (raw - raw_buffer);
}
}
while (mask && (mask != 1)) {
mask >>= BLZ_SHIFT;
*flg <<= 1;
}
pak_len = pak - pak_buffer;
BLZ_Invert(raw_buffer, raw_len);
BLZ_Invert(pak_buffer, pak_len);
if (!pak_tmp || (raw_len + 4 < ((pak_tmp + raw_tmp + 3) & -4) + 8)) {
pak = pak_buffer;
raw = raw_buffer;
raw_end = raw_buffer + raw_len;
while (raw < raw_end) *pak++ = *raw++;
while ((pak - pak_buffer) & 3) *pak++ = 0;
*(u32 *)pak = 0; pak += 4;
} else {
tmp = (u8 *) Memory(raw_tmp + pak_tmp + 15, sizeof(char));
for (len = 0; len < raw_tmp; len++)
tmp[len] = raw_buffer[len];
for (len = 0; len < pak_tmp; len++)
tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];
pak = pak_buffer;
pak_buffer = tmp;
free(pak);
pak = pak_buffer + raw_tmp + pak_tmp;
enc_len = pak_tmp;
hdr_len = 12;
inc_len = raw_len - pak_tmp - raw_tmp;
while ((pak - pak_buffer) & 3) {
*pak++ = 0xFF;
hdr_len++;
}
*(u32 *)pak = enc_len + hdr_len; pak += 4;
*(u32 *)pak = hdr_len; pak += 4;
*(u32 *)pak = inc_len - hdr_len; pak += 4;
}
*new_len = pak - pak_buffer;
return(pak_buffer);
}
/*----------------------------------------------------------------------------*/
void BLZ_Invert(u8 *buffer, int length) {
u8 *bottom, ch;
bottom = buffer + length - 1;
while (buffer < bottom) {
ch = *buffer;
*buffer++ = *bottom;
*bottom-- = ch;
}
}
/*----------------------------------------------------------------------------*/
/*-- EOF Copyright (C) 2011 CUE --*/
/*----------------------------------------------------------------------------*/
================================================
FILE: src/blz.h
================================================
#pragma once
#include
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
#define BLZ_NORMAL 0 // normal mode
#define BLZ_BEST 1 // best mode
u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
================================================
FILE: src/cJSON.c
================================================
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* cJSON */
/* JSON parser in C. */
/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif
#ifdef __GNUC__
#pragma GCC visibility push(default)
#endif
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif
#include
#include
#include
#include
#include
#include
#include
#ifdef ENABLE_LOCALES
#include
#endif
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#ifdef __GNUC__
#pragma GCC visibility pop
#endif
#include "cJSON.h"
/* define our own boolean type */
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)
typedef struct {
const unsigned char *json;
size_t position;
} error;
static error global_error = { NULL, 0 };
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
{
return (const char*) (global_error.json + global_error.position);
}
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) {
if (!cJSON_IsString(item)) {
return NULL;
}
return item->valuestring;
}
/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 6)
#error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif
CJSON_PUBLIC(const char*) cJSON_Version(void)
{
static char version[15];
sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
return version;
}
/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
{
if ((string1 == NULL) || (string2 == NULL))
{
return 1;
}
if (string1 == string2)
{
return 0;
}
for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
{
if (*string1 == '\0')
{
return 0;
}
}
return tolower(*string1) - tolower(*string2);
}
typedef struct internal_hooks
{
void *(*allocate)(size_t size);
void (*deallocate)(void *pointer);
void *(*reallocate)(void *pointer, size_t size);
} internal_hooks;
#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dillimport '...' is not static */
static void *internal_malloc(size_t size)
{
return malloc(size);
}
static void internal_free(void *pointer)
{
free(pointer);
}
static void *internal_realloc(void *pointer, size_t size)
{
return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif
static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
{
size_t length = 0;
unsigned char *copy = NULL;
if (string == NULL)
{
return NULL;
}
length = strlen((const char*)string) + sizeof("");
copy = (unsigned char*)hooks->allocate(length);
if (copy == NULL)
{
return NULL;
}
memcpy(copy, string, length);
return copy;
}
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (hooks == NULL)
{
/* Reset hooks */
global_hooks.allocate = malloc;
global_hooks.deallocate = free;
global_hooks.reallocate = realloc;
return;
}
global_hooks.allocate = malloc;
if (hooks->malloc_fn != NULL)
{
global_hooks.allocate = hooks->malloc_fn;
}
global_hooks.deallocate = free;
if (hooks->free_fn != NULL)
{
global_hooks.deallocate = hooks->free_fn;
}
/* use realloc only if both free and malloc are used */
global_hooks.reallocate = NULL;
if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
{
global_hooks.reallocate = realloc;
}
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
{
cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
if (node)
{
memset(node, '\0', sizeof(cJSON));
}
return node;
}
/* Delete a cJSON structure. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
{
cJSON *next = NULL;
while (item != NULL)
{
next = item->next;
if (!(item->type & cJSON_IsReference) && (item->child != NULL))
{
cJSON_Delete(item->child);
}
if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
{
global_hooks.deallocate(item->valuestring);
}
if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
{
global_hooks.deallocate(item->string);
}
global_hooks.deallocate(item);
item = next;
}
}
/* get the decimal point character of the current locale */
static unsigned char get_decimal_point(void)
{
#ifdef ENABLE_LOCALES
struct lconv *lconv = localeconv();
return (unsigned char) lconv->decimal_point[0];
#else
return '.';
#endif
}
typedef struct
{
const unsigned char *content;
size_t length;
size_t offset;
size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
internal_hooks hooks;
} parse_buffer;
/* check if the given size is left to read in a given parse buffer (starting with 1) */
#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
/* check if the buffer can be accessed at the given index (starting with 0) */
#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
/* get a pointer to the buffer at the position */
#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
/* Parse the input text to generate a number, and populate the result into item. */
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
{
double number = 0;
unsigned char *after_end = NULL;
unsigned char number_c_string[64];
unsigned char decimal_point = get_decimal_point();
size_t i = 0;
if ((input_buffer == NULL) || (input_buffer->content == NULL))
{
return false;
}
/* copy the number into a temporary buffer and replace '.' with the decimal point
* of the current locale (for strtod)
* This also takes care of '\0' not necessarily being available for marking the end of the input */
for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
{
switch (buffer_at_offset(input_buffer)[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
case 'e':
case 'E':
number_c_string[i] = buffer_at_offset(input_buffer)[i];
break;
case '.':
number_c_string[i] = decimal_point;
break;
default:
goto loop_end;
}
}
loop_end:
number_c_string[i] = '\0';
number = strtod((const char*)number_c_string, (char**)&after_end);
if (number_c_string == after_end)
{
return false; /* parse_error */
}
item->valuedouble = number;
/* use saturation in case of overflow */
if (number >= INT_MAX)
{
item->valueint = INT_MAX;
}
else if (number <= INT_MIN)
{
item->valueint = INT_MIN;
}
else
{
item->valueint = (int)number;
}
item->type = cJSON_Number;
input_buffer->offset += (size_t)(after_end - number_c_string);
return true;
}
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
{
if (number >= INT_MAX)
{
object->valueint = INT_MAX;
}
else if (number <= INT_MIN)
{
object->valueint = INT_MIN;
}
else
{
object->valueint = (int)number;
}
return object->valuedouble = number;
}
typedef struct
{
unsigned char *buffer;
size_t length;
size_t offset;
size_t depth; /* current nesting depth (for formatted printing) */
cJSON_bool noalloc;
cJSON_bool format; /* is this print a formatted print */
internal_hooks hooks;
} printbuffer;
/* realloc printbuffer if necessary to have at least "needed" bytes more */
static unsigned char* ensure(printbuffer * const p, size_t needed)
{
unsigned char *newbuffer = NULL;
size_t newsize = 0;
if ((p == NULL) || (p->buffer == NULL))
{
return NULL;
}
if ((p->length > 0) && (p->offset >= p->length))
{
/* make sure that offset is valid */
return NULL;
}
if (needed > INT_MAX)
{
/* sizes bigger than INT_MAX are currently not supported */
return NULL;
}
needed += p->offset + 1;
if (needed <= p->length)
{
return p->buffer + p->offset;
}
if (p->noalloc) {
return NULL;
}
/* calculate new buffer size */
if (needed > (INT_MAX / 2))
{
/* overflow of int, use INT_MAX if possible */
if (needed <= INT_MAX)
{
newsize = INT_MAX;
}
else
{
return NULL;
}
}
else
{
newsize = needed * 2;
}
if (p->hooks.reallocate != NULL)
{
/* reallocate with realloc if available */
newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
if (newbuffer == NULL)
{
p->hooks.deallocate(p->buffer);
p->length = 0;
p->buffer = NULL;
return NULL;
}
}
else
{
/* otherwise reallocate manually */
newbuffer = (unsigned char*)p->hooks.allocate(newsize);
if (!newbuffer)
{
p->hooks.deallocate(p->buffer);
p->length = 0;
p->buffer = NULL;
return NULL;
}
if (newbuffer)
{
memcpy(newbuffer, p->buffer, p->offset + 1);
}
p->hooks.deallocate(p->buffer);
}
p->length = newsize;
p->buffer = newbuffer;
return newbuffer + p->offset;
}
/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
{
const unsigned char *buffer_pointer = NULL;
if ((buffer == NULL) || (buffer->buffer == NULL))
{
return;
}
buffer_pointer = buffer->buffer + buffer->offset;
buffer->offset += strlen((const char*)buffer_pointer);
}
/* Render the number nicely from the given item into a string. */
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
double d = item->valuedouble;
int length = 0;
size_t i = 0;
unsigned char number_buffer[26]; /* temporary buffer to print the number into */
unsigned char decimal_point = get_decimal_point();
double test;
if (output_buffer == NULL)
{
return false;
}
/* This checks for NaN and Infinity */
if ((d * 0) != 0)
{
length = sprintf((char*)number_buffer, "null");
}
else
{
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
length = sprintf((char*)number_buffer, "%1.15g", d);
/* Check whether the original double can be recovered */
if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d))
{
/* If not, print with 17 decimal places of precision */
length = sprintf((char*)number_buffer, "%1.17g", d);
}
}
/* sprintf failed or buffer overrun occured */
if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
{
return false;
}
/* reserve appropriate space in the output */
output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
if (output_pointer == NULL)
{
return false;
}
/* copy the printed number to the output and replace locale
* dependent decimal point with '.' */
for (i = 0; i < ((size_t)length); i++)
{
if (number_buffer[i] == decimal_point)
{
output_pointer[i] = '.';
continue;
}
output_pointer[i] = number_buffer[i];
}
output_pointer[i] = '\0';
output_buffer->offset += (size_t)length;
return true;
}
/* parse 4 digit hexadecimal number */
static unsigned parse_hex4(const unsigned char * const input)
{
unsigned int h = 0;
size_t i = 0;
for (i = 0; i < 4; i++)
{
/* parse digit */
if ((input[i] >= '0') && (input[i] <= '9'))
{
h += (unsigned int) input[i] - '0';
}
else if ((input[i] >= 'A') && (input[i] <= 'F'))
{
h += (unsigned int) 10 + input[i] - 'A';
}
else if ((input[i] >= 'a') && (input[i] <= 'f'))
{
h += (unsigned int) 10 + input[i] - 'a';
}
else /* invalid */
{
return 0;
}
if (i < 3)
{
/* shift left to make place for the next nibble */
h = h << 4;
}
}
return h;
}
/* converts a UTF-16 literal to UTF-8
* A literal can be one or two sequences of the form \uXXXX */
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
{
long unsigned int codepoint = 0;
unsigned int first_code = 0;
const unsigned char *first_sequence = input_pointer;
unsigned char utf8_length = 0;
unsigned char utf8_position = 0;
unsigned char sequence_length = 0;
unsigned char first_byte_mark = 0;
if ((input_end - first_sequence) < 6)
{
/* input ends unexpectedly */
goto fail;
}
/* get the first utf16 sequence */
first_code = parse_hex4(first_sequence + 2);
/* check that the code is valid */
if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
{
goto fail;
}
/* UTF16 surrogate pair */
if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
{
const unsigned char *second_sequence = first_sequence + 6;
unsigned int second_code = 0;
sequence_length = 12; /* \uXXXX\uXXXX */
if ((input_end - second_sequence) < 6)
{
/* input ends unexpectedly */
goto fail;
}
if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
{
/* missing second half of the surrogate pair */
goto fail;
}
/* get the second utf16 sequence */
second_code = parse_hex4(second_sequence + 2);
/* check that the code is valid */
if ((second_code < 0xDC00) || (second_code > 0xDFFF))
{
/* invalid second half of the surrogate pair */
goto fail;
}
/* calculate the unicode codepoint from the surrogate pair */
codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
}
else
{
sequence_length = 6; /* \uXXXX */
codepoint = first_code;
}
/* encode as UTF-8
* takes at maximum 4 bytes to encode:
* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
if (codepoint < 0x80)
{
/* normal ascii, encoding 0xxxxxxx */
utf8_length = 1;
}
else if (codepoint < 0x800)
{
/* two bytes, encoding 110xxxxx 10xxxxxx */
utf8_length = 2;
first_byte_mark = 0xC0; /* 11000000 */
}
else if (codepoint < 0x10000)
{
/* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
utf8_length = 3;
first_byte_mark = 0xE0; /* 11100000 */
}
else if (codepoint <= 0x10FFFF)
{
/* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
utf8_length = 4;
first_byte_mark = 0xF0; /* 11110000 */
}
else
{
/* invalid unicode codepoint */
goto fail;
}
/* encode as utf8 */
for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
{
/* 10xxxxxx */
(*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
codepoint >>= 6;
}
/* encode first byte */
if (utf8_length > 1)
{
(*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
}
else
{
(*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
}
*output_pointer += utf8_length;
return sequence_length;
fail:
return 0;
}
/* Parse the input text into an unescaped cinput, and populate item. */
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
{
const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
unsigned char *output_pointer = NULL;
unsigned char *output = NULL;
/* not a string */
if (buffer_at_offset(input_buffer)[0] != '\"')
{
goto fail;
}
{
/* calculate approximate size of the output (overestimate) */
size_t allocation_length = 0;
size_t skipped_bytes = 0;
while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
{
/* is escape sequence */
if (input_end[0] == '\\')
{
if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
{
/* prevent buffer overflow when last input character is a backslash */
goto fail;
}
skipped_bytes++;
input_end++;
}
input_end++;
}
if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
{
goto fail; /* string ended unexpectedly */
}
/* This is at most how much we need for the output */
allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
if (output == NULL)
{
goto fail; /* allocation failure */
}
}
output_pointer = output;
/* loop through the string literal */
while (input_pointer < input_end)
{
if (*input_pointer != '\\')
{
*output_pointer++ = *input_pointer++;
}
/* escape sequence */
else
{
unsigned char sequence_length = 2;
if ((input_end - input_pointer) < 1)
{
goto fail;
}
switch (input_pointer[1])
{
case 'b':
*output_pointer++ = '\b';
break;
case 'f':
*output_pointer++ = '\f';
break;
case 'n':
*output_pointer++ = '\n';
break;
case 'r':
*output_pointer++ = '\r';
break;
case 't':
*output_pointer++ = '\t';
break;
case '\"':
case '\\':
case '/':
*output_pointer++ = input_pointer[1];
break;
/* UTF-16 literal */
case 'u':
sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
if (sequence_length == 0)
{
/* failed to convert UTF16-literal to UTF-8 */
goto fail;
}
break;
default:
goto fail;
}
input_pointer += sequence_length;
}
}
/* zero terminate the output */
*output_pointer = '\0';
item->type = cJSON_String;
item->valuestring = (char*)output;
input_buffer->offset = (size_t) (input_end - input_buffer->content);
input_buffer->offset++;
return true;
fail:
if (output != NULL)
{
input_buffer->hooks.deallocate(output);
}
if (input_pointer != NULL)
{
input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
}
return false;
}
/* Render the cstring provided to an escaped version that can be printed. */
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
{
const unsigned char *input_pointer = NULL;
unsigned char *output = NULL;
unsigned char *output_pointer = NULL;
size_t output_length = 0;
/* numbers of additional characters needed for escaping */
size_t escape_characters = 0;
if (output_buffer == NULL)
{
return false;
}
/* empty string */
if (input == NULL)
{
output = ensure(output_buffer, sizeof("\"\""));
if (output == NULL)
{
return false;
}
strcpy((char*)output, "\"\"");
return true;
}
/* set "flag" to 1 if something needs to be escaped */
for (input_pointer = input; *input_pointer; input_pointer++)
{
switch (*input_pointer)
{
case '\"':
case '\\':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
/* one character escape sequence */
escape_characters++;
break;
default:
if (*input_pointer < 32)
{
/* UTF-16 escape sequence uXXXX */
escape_characters += 5;
}
break;
}
}
output_length = (size_t)(input_pointer - input) + escape_characters;
output = ensure(output_buffer, output_length + sizeof("\"\""));
if (output == NULL)
{
return false;
}
/* no characters have to be escaped */
if (escape_characters == 0)
{
output[0] = '\"';
memcpy(output + 1, input, output_length);
output[output_length + 1] = '\"';
output[output_length + 2] = '\0';
return true;
}
output[0] = '\"';
output_pointer = output + 1;
/* copy the string */
for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
{
if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
{
/* normal character, copy */
*output_pointer = *input_pointer;
}
else
{
/* character needs to be escaped */
*output_pointer++ = '\\';
switch (*input_pointer)
{
case '\\':
*output_pointer = '\\';
break;
case '\"':
*output_pointer = '\"';
break;
case '\b':
*output_pointer = 'b';
break;
case '\f':
*output_pointer = 'f';
break;
case '\n':
*output_pointer = 'n';
break;
case '\r':
*output_pointer = 'r';
break;
case '\t':
*output_pointer = 't';
break;
default:
/* escape and print as unicode codepoint */
sprintf((char*)output_pointer, "u%04x", *input_pointer);
output_pointer += 4;
break;
}
}
}
output[output_length + 1] = '\"';
output[output_length + 2] = '\0';
return true;
}
/* Invoke print_string_ptr (which is useful) on an item. */
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
{
return print_string_ptr((unsigned char*)item->valuestring, p);
}
/* Predeclare these prototypes. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
/* Utility to jump whitespace and cr/lf */
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
{
if ((buffer == NULL) || (buffer->content == NULL))
{
return NULL;
}
while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
{
buffer->offset++;
}
if (buffer->offset == buffer->length)
{
buffer->offset--;
}
return buffer;
}
/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
{
if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
{
return NULL;
}
if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
{
buffer->offset += 3;
}
return buffer;
}
/* Parse an object - create a new root, and populate. */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
{
parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
cJSON *item = NULL;
/* reset error position */
global_error.json = NULL;
global_error.position = 0;
if (value == NULL)
{
goto fail;
}
buffer.content = (const unsigned char*)value;
buffer.length = strlen((const char*)value) + sizeof("");
buffer.offset = 0;
buffer.hooks = global_hooks;
item = cJSON_New_Item(&global_hooks);
if (item == NULL) /* memory fail */
{
goto fail;
}
if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
{
/* parse failure. ep is set. */
goto fail;
}
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated)
{
buffer_skip_whitespace(&buffer);
if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
{
goto fail;
}
}
if (return_parse_end)
{
*return_parse_end = (const char*)buffer_at_offset(&buffer);
}
return item;
fail:
if (item != NULL)
{
cJSON_Delete(item);
}
if (value != NULL)
{
error local_error;
local_error.json = (const unsigned char*)value;
local_error.position = 0;
if (buffer.offset < buffer.length)
{
local_error.position = buffer.offset;
}
else if (buffer.length > 0)
{
local_error.position = buffer.length - 1;
}
if (return_parse_end != NULL)
{
*return_parse_end = (const char*)local_error.json + local_error.position;
}
global_error = local_error;
}
return NULL;
}
/* Default options for cJSON_Parse */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
{
return cJSON_ParseWithOpts(value, 0, 0);
}
#define cjson_min(a, b) ((a < b) ? a : b)
static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
{
static const size_t default_buffer_size = 256;
printbuffer buffer[1];
unsigned char *printed = NULL;
memset(buffer, 0, sizeof(buffer));
/* create buffer */
buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
buffer->length = default_buffer_size;
buffer->format = format;
buffer->hooks = *hooks;
if (buffer->buffer == NULL)
{
goto fail;
}
/* print the value */
if (!print_value(item, buffer))
{
goto fail;
}
update_offset(buffer);
/* check if reallocate is available */
if (hooks->reallocate != NULL)
{
printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
buffer->buffer = NULL;
if (printed == NULL) {
goto fail;
}
}
else /* otherwise copy the JSON over to a new buffer */
{
printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
if (printed == NULL)
{
goto fail;
}
memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
printed[buffer->offset] = '\0'; /* just to be sure */
/* free the buffer */
hooks->deallocate(buffer->buffer);
}
return printed;
fail:
if (buffer->buffer != NULL)
{
hooks->deallocate(buffer->buffer);
}
if (printed != NULL)
{
hooks->deallocate(printed);
}
return NULL;
}
/* Render a cJSON item/entity/structure to text. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
{
return (char*)print(item, true, &global_hooks);
}
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
{
return (char*)print(item, false, &global_hooks);
}
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
{
printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
if (prebuffer < 0)
{
return NULL;
}
p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
if (!p.buffer)
{
return NULL;
}
p.length = (size_t)prebuffer;
p.offset = 0;
p.noalloc = false;
p.format = fmt;
p.hooks = global_hooks;
if (!print_value(item, &p))
{
global_hooks.deallocate(p.buffer);
return NULL;
}
return (char*)p.buffer;
}
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
{
printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
if ((len < 0) || (buf == NULL))
{
return false;
}
p.buffer = (unsigned char*)buf;
p.length = (size_t)len;
p.offset = 0;
p.noalloc = true;
p.format = fmt;
p.hooks = global_hooks;
return print_value(item, &p);
}
/* Parser core - when encountering text, process appropriately. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
{
if ((input_buffer == NULL) || (input_buffer->content == NULL))
{
return false; /* no input */
}
/* parse the different types of values */
/* null */
if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
{
item->type = cJSON_NULL;
input_buffer->offset += 4;
return true;
}
/* false */
if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
{
item->type = cJSON_False;
input_buffer->offset += 5;
return true;
}
/* true */
if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
{
item->type = cJSON_True;
item->valueint = 1;
input_buffer->offset += 4;
return true;
}
/* string */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
{
return parse_string(item, input_buffer);
}
/* number */
if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
{
return parse_number(item, input_buffer);
}
/* array */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
{
return parse_array(item, input_buffer);
}
/* object */
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
{
return parse_object(item, input_buffer);
}
return false;
}
/* Render a value to text. */
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output = NULL;
if ((item == NULL) || (output_buffer == NULL))
{
return false;
}
switch ((item->type) & 0xFF)
{
case cJSON_NULL:
output = ensure(output_buffer, 5);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "null");
return true;
case cJSON_False:
output = ensure(output_buffer, 6);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "false");
return true;
case cJSON_True:
output = ensure(output_buffer, 5);
if (output == NULL)
{
return false;
}
strcpy((char*)output, "true");
return true;
case cJSON_Number:
return print_number(item, output_buffer);
case cJSON_Raw:
{
size_t raw_length = 0;
if (item->valuestring == NULL)
{
return false;
}
raw_length = strlen(item->valuestring) + sizeof("");
output = ensure(output_buffer, raw_length);
if (output == NULL)
{
return false;
}
memcpy(output, item->valuestring, raw_length);
return true;
}
case cJSON_String:
return print_string(item, output_buffer);
case cJSON_Array:
return print_array(item, output_buffer);
case cJSON_Object:
return print_object(item, output_buffer);
default:
return false;
}
}
/* Build an array from input text. */
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
{
cJSON *head = NULL; /* head of the linked list */
cJSON *current_item = NULL;
if (input_buffer->depth >= CJSON_NESTING_LIMIT)
{
return false; /* to deeply nested */
}
input_buffer->depth++;
if (buffer_at_offset(input_buffer)[0] != '[')
{
/* not an array */
goto fail;
}
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
{
/* empty array */
goto success;
}
/* check if we skipped to the end of the buffer */
if (cannot_access_at_index(input_buffer, 0))
{
input_buffer->offset--;
goto fail;
}
/* step back to character in front of the first element */
input_buffer->offset--;
/* loop through the comma separated array elements */
do
{
/* allocate next item */
cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
if (new_item == NULL)
{
goto fail; /* allocation failure */
}
/* attach next item to list */
if (head == NULL)
{
/* start the linked list */
current_item = head = new_item;
}
else
{
/* add to the end and advance */
current_item->next = new_item;
new_item->prev = current_item;
current_item = new_item;
}
/* parse next value */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_value(current_item, input_buffer))
{
goto fail; /* failed to parse value */
}
buffer_skip_whitespace(input_buffer);
}
while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
{
goto fail; /* expected end of array */
}
success:
input_buffer->depth--;
item->type = cJSON_Array;
item->child = head;
input_buffer->offset++;
return true;
fail:
if (head != NULL)
{
cJSON_Delete(head);
}
return false;
}
/* Render an array to text */
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
size_t length = 0;
cJSON *current_element = item->child;
if (output_buffer == NULL)
{
return false;
}
/* Compose the output array. */
/* opening square bracket */
output_pointer = ensure(output_buffer, 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer = '[';
output_buffer->offset++;
output_buffer->depth++;
while (current_element != NULL)
{
if (!print_value(current_element, output_buffer))
{
return false;
}
update_offset(output_buffer);
if (current_element->next)
{
length = (size_t) (output_buffer->format ? 2 : 1);
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ',';
if(output_buffer->format)
{
*output_pointer++ = ' ';
}
*output_pointer = '\0';
output_buffer->offset += length;
}
current_element = current_element->next;
}
output_pointer = ensure(output_buffer, 2);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ']';
*output_pointer = '\0';
output_buffer->depth--;
return true;
}
/* Build an object from the text. */
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
{
cJSON *head = NULL; /* linked list head */
cJSON *current_item = NULL;
if (input_buffer->depth >= CJSON_NESTING_LIMIT)
{
return false; /* to deeply nested */
}
input_buffer->depth++;
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
{
goto fail; /* not an object */
}
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
{
goto success; /* empty object */
}
/* check if we skipped to the end of the buffer */
if (cannot_access_at_index(input_buffer, 0))
{
input_buffer->offset--;
goto fail;
}
/* step back to character in front of the first element */
input_buffer->offset--;
/* loop through the comma separated array elements */
do
{
/* allocate next item */
cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
if (new_item == NULL)
{
goto fail; /* allocation failure */
}
/* attach next item to list */
if (head == NULL)
{
/* start the linked list */
current_item = head = new_item;
}
else
{
/* add to the end and advance */
current_item->next = new_item;
new_item->prev = current_item;
current_item = new_item;
}
/* parse the name of the child */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_string(current_item, input_buffer))
{
goto fail; /* faile to parse name */
}
buffer_skip_whitespace(input_buffer);
/* swap valuestring and string, because we parsed the name */
current_item->string = current_item->valuestring;
current_item->valuestring = NULL;
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
{
goto fail; /* invalid object */
}
/* parse the value */
input_buffer->offset++;
buffer_skip_whitespace(input_buffer);
if (!parse_value(current_item, input_buffer))
{
goto fail; /* failed to parse value */
}
buffer_skip_whitespace(input_buffer);
}
while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
{
goto fail; /* expected end of object */
}
success:
input_buffer->depth--;
item->type = cJSON_Object;
item->child = head;
input_buffer->offset++;
return true;
fail:
if (head != NULL)
{
cJSON_Delete(head);
}
return false;
}
/* Render an object to text. */
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
{
unsigned char *output_pointer = NULL;
size_t length = 0;
cJSON *current_item = item->child;
if (output_buffer == NULL)
{
return false;
}
/* Compose the output: */
length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = '{';
output_buffer->depth++;
if (output_buffer->format)
{
*output_pointer++ = '\n';
}
output_buffer->offset += length;
while (current_item)
{
if (output_buffer->format)
{
size_t i;
output_pointer = ensure(output_buffer, output_buffer->depth);
if (output_pointer == NULL)
{
return false;
}
for (i = 0; i < output_buffer->depth; i++)
{
*output_pointer++ = '\t';
}
output_buffer->offset += output_buffer->depth;
}
/* print key */
if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
{
return false;
}
update_offset(output_buffer);
length = (size_t) (output_buffer->format ? 2 : 1);
output_pointer = ensure(output_buffer, length);
if (output_pointer == NULL)
{
return false;
}
*output_pointer++ = ':';
if (output_buffer->format)
{
*output_pointer++ = '\t';
}
output_buffer->offset += length;
/* print value */
if (!print_value(current_item, output_buffer))
{
return false;
}
update_offset(output_buffer);
/* print comma if not last */
length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0));
output_pointer = ensure(output_buffer, length + 1);
if (output_pointer == NULL)
{
return false;
}
if (current_item->next)
{
*output_pointer++ = ',';
}
if (output_buffer->format)
{
*output_pointer++ = '\n';
}
*output_pointer = '\0';
output_buffer->offset += length;
current_item = current_item->next;
}
output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
if (output_pointer == NULL)
{
return false;
}
if (output_buffer->format)
{
size_t i;
for (i = 0; i < (output_buffer->depth - 1); i++)
{
*output_pointer++ = '\t';
}
}
*output_pointer++ = '}';
*output_pointer = '\0';
output_buffer->depth--;
return true;
}
/* Get Array size/item / object item. */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
{
cJSON *child = NULL;
size_t size = 0;
if (array == NULL)
{
return 0;
}
child = array->child;
while(child != NULL)
{
size++;
child = child->next;
}
/* FIXME: Can overflow here. Cannot be fixed without breaking the API */
return (int)size;
}
static cJSON* get_array_item(const cJSON *array, size_t index)
{
cJSON *current_child = NULL;
if (array == NULL)
{
return NULL;
}
current_child = array->child;
while ((current_child != NULL) && (index > 0))
{
index--;
current_child = current_child->next;
}
return current_child;
}
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
{
if (index < 0)
{
return NULL;
}
return get_array_item(array, (size_t)index);
}
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
cJSON *current_element = NULL;
if ((object == NULL) || (name == NULL))
{
return NULL;
}
current_element = object->child;
if (case_sensitive)
{
while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
{
current_element = current_element->next;
}
}
else
{
while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
{
current_element = current_element->next;
}
}
return current_element;
}
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
{
return get_object_item(object, string, false);
}
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
{
return get_object_item(object, string, true);
}
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
{
return cJSON_GetObjectItem(object, string) ? 1 : 0;
}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev, cJSON *item)
{
prev->next = item;
item->prev = prev;
}
/* Utility for handling references. */
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
{
cJSON *reference = NULL;
if (item == NULL)
{
return NULL;
}
reference = cJSON_New_Item(hooks);
if (reference == NULL)
{
return NULL;
}
memcpy(reference, item, sizeof(cJSON));
reference->string = NULL;
reference->type |= cJSON_IsReference;
reference->next = reference->prev = NULL;
return reference;
}
static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
{
cJSON *child = NULL;
if ((item == NULL) || (array == NULL))
{
return false;
}
child = array->child;
if (child == NULL)
{
/* list is empty, start new one */
array->child = item;
}
else
{
/* append to the end */
while (child->next)
{
child = child->next;
}
suffix_object(child, item);
}
return true;
}
/* Add item to array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
{
add_item_to_array(array, item);
}
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic push
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
/* helper function to cast away const */
static void* cast_away_const(const void* string)
{
return (void*)string;
}
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic pop
#endif
static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
{
char *new_key = NULL;
int new_type = cJSON_Invalid;
if ((object == NULL) || (string == NULL) || (item == NULL))
{
return false;
}
if (constant_key)
{
new_key = (char*)cast_away_const(string);
new_type = item->type | cJSON_StringIsConst;
}
else
{
new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
if (new_key == NULL)
{
return false;
}
new_type = item->type & ~cJSON_StringIsConst;
}
if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
{
hooks->deallocate(item->string);
}
item->string = new_key;
item->type = new_type;
return add_item_to_array(object, item);
}
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
add_item_to_object(object, string, item, &global_hooks, false);
}
/* Add an item to an object with constant string as key */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
{
add_item_to_object(object, string, item, &global_hooks, true);
}
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
if (array == NULL)
{
return;
}
add_item_to_array(array, create_reference(item, &global_hooks));
}
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
if ((object == NULL) || (string == NULL))
{
return;
}
add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
}
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
{
cJSON *null = cJSON_CreateNull();
if (add_item_to_object(object, name, null, &global_hooks, false))
{
return null;
}
cJSON_Delete(null);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
{
cJSON *true_item = cJSON_CreateTrue();
if (add_item_to_object(object, name, true_item, &global_hooks, false))
{
return true_item;
}
cJSON_Delete(true_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
{
cJSON *false_item = cJSON_CreateFalse();
if (add_item_to_object(object, name, false_item, &global_hooks, false))
{
return false_item;
}
cJSON_Delete(false_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
{
cJSON *bool_item = cJSON_CreateBool(boolean);
if (add_item_to_object(object, name, bool_item, &global_hooks, false))
{
return bool_item;
}
cJSON_Delete(bool_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
{
cJSON *number_item = cJSON_CreateNumber(number);
if (add_item_to_object(object, name, number_item, &global_hooks, false))
{
return number_item;
}
cJSON_Delete(number_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
{
cJSON *string_item = cJSON_CreateString(string);
if (add_item_to_object(object, name, string_item, &global_hooks, false))
{
return string_item;
}
cJSON_Delete(string_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
{
cJSON *raw_item = cJSON_CreateRaw(raw);
if (add_item_to_object(object, name, raw_item, &global_hooks, false))
{
return raw_item;
}
cJSON_Delete(raw_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
{
cJSON *object_item = cJSON_CreateObject();
if (add_item_to_object(object, name, object_item, &global_hooks, false))
{
return object_item;
}
cJSON_Delete(object_item);
return NULL;
}
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
{
cJSON *array = cJSON_CreateArray();
if (add_item_to_object(object, name, array, &global_hooks, false))
{
return array;
}
cJSON_Delete(array);
return NULL;
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
{
if ((parent == NULL) || (item == NULL))
{
return NULL;
}
if (item->prev != NULL)
{
/* not the first element */
item->prev->next = item->next;
}
if (item->next != NULL)
{
/* not the last element */
item->next->prev = item->prev;
}
if (item == parent->child)
{
/* first element */
parent->child = item->next;
}
/* make sure the detached item doesn't point anywhere anymore */
item->prev = NULL;
item->next = NULL;
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
{
if (which < 0)
{
return NULL;
}
return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
{
cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
cJSON *to_detach = cJSON_GetObjectItem(object, string);
return cJSON_DetachItemViaPointer(object, to_detach);
}
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
return cJSON_DetachItemViaPointer(object, to_detach);
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}
/* Replace array/object items with new ones. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
{
cJSON *after_inserted = NULL;
if (which < 0)
{
return;
}
after_inserted = get_array_item(array, (size_t)which);
if (after_inserted == NULL)
{
add_item_to_array(array, newitem);
return;
}
newitem->next = after_inserted;
newitem->prev = after_inserted->prev;
after_inserted->prev = newitem;
if (after_inserted == array->child)
{
array->child = newitem;
}
else
{
newitem->prev->next = newitem;
}
}
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
{
if ((parent == NULL) || (replacement == NULL) || (item == NULL))
{
return false;
}
if (replacement == item)
{
return true;
}
replacement->next = item->next;
replacement->prev = item->prev;
if (replacement->next != NULL)
{
replacement->next->prev = replacement;
}
if (replacement->prev != NULL)
{
replacement->prev->next = replacement;
}
if (parent->child == item)
{
parent->child = replacement;
}
item->next = NULL;
item->prev = NULL;
cJSON_Delete(item);
return true;
}
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
if (which < 0)
{
return;
}
cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
}
static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
{
if ((replacement == NULL) || (string == NULL))
{
return false;
}
/* replace the name in the replacement */
if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
{
cJSON_free(replacement->string);
}
replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
replacement->type &= ~cJSON_StringIsConst;
cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
return true;
}
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
replace_item_in_object(object, string, newitem, false);
}
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
replace_item_in_object(object, string, newitem, true);
}
/* Create basic types: */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_NULL;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_True;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_False;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = b ? cJSON_True : cJSON_False;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_Number;
item->valuedouble = num;
/* use saturation in case of overflow */
if (num >= INT_MAX)
{
item->valueint = INT_MAX;
}
else if (num <= INT_MIN)
{
item->valueint = INT_MIN;
}
else
{
item->valueint = (int)num;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_String;
item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
if(!item->valuestring)
{
cJSON_Delete(item);
return NULL;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL)
{
item->type = cJSON_String | cJSON_IsReference;
item->valuestring = (char*)cast_away_const(string);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL) {
item->type = cJSON_Object | cJSON_IsReference;
item->child = (cJSON*)cast_away_const(child);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
cJSON *item = cJSON_New_Item(&global_hooks);
if (item != NULL) {
item->type = cJSON_Array | cJSON_IsReference;
item->child = (cJSON*)cast_away_const(child);
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type = cJSON_Raw;
item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
if(!item->valuestring)
{
cJSON_Delete(item);
return NULL;
}
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if(item)
{
item->type=cJSON_Array;
}
return item;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
{
cJSON *item = cJSON_New_Item(&global_hooks);
if (item)
{
item->type = cJSON_Object;
}
return item;
}
/* Create Arrays: */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber(numbers[i]);
if (!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber((double)numbers[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (numbers == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for(i = 0;a && (i < (size_t)count); i++)
{
n = cJSON_CreateNumber(numbers[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}
return a;
}
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;
if ((count < 0) || (strings == NULL))
{
return NULL;
}
a = cJSON_CreateArray();
for (i = 0; a && (i < (size_t)count); i++)
{
n = cJSON_CreateString(strings[i]);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p,n);
}
p = n;
}
return a;
}
/* Duplication */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
{
cJSON *newitem = NULL;
cJSON *child = NULL;
cJSON *next = NULL;
cJSON *newchild = NULL;
/* Bail on bad ptr */
if (!item)
{
goto fail;
}
/* Create new item */
newitem = cJSON_New_Item(&global_hooks);
if (!newitem)
{
goto fail;
}
/* Copy over all vars */
newitem->type = item->type & (~cJSON_IsReference);
newitem->valueint = item->valueint;
newitem->valuedouble = item->valuedouble;
if (item->valuestring)
{
newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
if (!newitem->valuestring)
{
goto fail;
}
}
if (item->string)
{
newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
if (!newitem->string)
{
goto fail;
}
}
/* If non-recursive, then we're done! */
if (!recurse)
{
return newitem;
}
/* Walk the ->next chain for the child. */
child = item->child;
while (child != NULL)
{
newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild)
{
goto fail;
}
if (next != NULL)
{
/* If newitem->child already set, then crosswire ->prev and ->next and move on */
next->next = newchild;
newchild->prev = next;
next = newchild;
}
else
{
/* Set newitem->child and move to it */
newitem->child = newchild;
next = newchild;
}
child = child->next;
}
return newitem;
fail:
if (newitem != NULL)
{
cJSON_Delete(newitem);
}
return NULL;
}
CJSON_PUBLIC(void) cJSON_Minify(char *json)
{
unsigned char *into = (unsigned char*)json;
if (json == NULL)
{
return;
}
while (*json)
{
if (*json == ' ')
{
json++;
}
else if (*json == '\t')
{
/* Whitespace characters. */
json++;
}
else if (*json == '\r')
{
json++;
}
else if (*json=='\n')
{
json++;
}
else if ((*json == '/') && (json[1] == '/'))
{
/* double-slash comments, to end of line. */
while (*json && (*json != '\n'))
{
json++;
}
}
else if ((*json == '/') && (json[1] == '*'))
{
/* multiline comments. */
while (*json && !((*json == '*') && (json[1] == '/')))
{
json++;
}
json += 2;
}
else if (*json == '\"')
{
/* string literals, which are \" sensitive. */
*into++ = (unsigned char)*json++;
while (*json && (*json != '\"'))
{
if (*json == '\\')
{
*into++ = (unsigned char)*json++;
}
*into++ = (unsigned char)*json++;
}
*into++ = (unsigned char)*json++;
}
else
{
/* All other characters. */
*into++ = (unsigned char)*json++;
}
}
/* and null-terminate. */
*into = '\0';
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Invalid;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_False;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xff) == cJSON_True;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & (cJSON_True | cJSON_False)) != 0;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_NULL;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Number;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_String;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Array;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Object;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xFF) == cJSON_Raw;
}
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
{
if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
{
return false;
}
/* check if type is valid */
switch (a->type & 0xFF)
{
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
case cJSON_Number:
case cJSON_String:
case cJSON_Raw:
case cJSON_Array:
case cJSON_Object:
break;
default:
return false;
}
/* identical objects are equal */
if (a == b)
{
return true;
}
switch (a->type & 0xFF)
{
/* in these cases and equal type is enough */
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
return true;
case cJSON_Number:
if (a->valuedouble == b->valuedouble)
{
return true;
}
return false;
case cJSON_String:
case cJSON_Raw:
if ((a->valuestring == NULL) || (b->valuestring == NULL))
{
return false;
}
if (strcmp(a->valuestring, b->valuestring) == 0)
{
return true;
}
return false;
case cJSON_Array:
{
cJSON *a_element = a->child;
cJSON *b_element = b->child;
for (; (a_element != NULL) && (b_element != NULL);)
{
if (!cJSON_Compare(a_element, b_element, case_sensitive))
{
return false;
}
a_element = a_element->next;
b_element = b_element->next;
}
/* one of the arrays is longer than the other */
if (a_element != b_element) {
return false;
}
return true;
}
case cJSON_Object:
{
cJSON *a_element = NULL;
cJSON *b_element = NULL;
cJSON_ArrayForEach(a_element, a)
{
/* TODO This has O(n^2) runtime, which is horrible! */
b_element = get_object_item(b, a_element->string, case_sensitive);
if (b_element == NULL)
{
return false;
}
if (!cJSON_Compare(a_element, b_element, case_sensitive))
{
return false;
}
}
/* doing this twice, once on a and b to prevent true comparison if a subset of b
* TODO: Do this the proper way, this is just a fix for now */
cJSON_ArrayForEach(b_element, b)
{
a_element = get_object_item(a, b_element->string, case_sensitive);
if (a_element == NULL)
{
return false;
}
if (!cJSON_Compare(b_element, a_element, case_sensitive))
{
return false;
}
}
return true;
}
default:
return false;
}
}
CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
{
return global_hooks.allocate(size);
}
CJSON_PUBLIC(void) cJSON_free(void *object)
{
global_hooks.deallocate(object);
}
================================================
FILE: src/cJSON.h
================================================
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 6
#include
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* 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:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type __stdcall
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall
#endif
#else /* !WIN32 */
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* 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. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* 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(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* 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 */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* 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 */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* 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. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check if the item is a string and return its valuestring */
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/arrray that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items. */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* 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. */
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif
================================================
FILE: src/elf2kip.c
================================================
// Copyright 2018 SciresM
#include
#include
#include
#include
#include
#include
#include "cJSON.h"
#include "blz.h"
#include "elf64.h"
typedef struct {
u32 DstOff;
u32 DecompSz;
u32 CompSz;
u32 Attribute;
} KipSegment;
typedef struct {
u8 Magic[4];
u8 Name[0xC];
u64 ProgramId;
u32 Version;
u8 MainThreadPriority;
u8 DefaultCpuId;
u8 Unk;
u8 Flags;
KipSegment Segments[6];
u32 Capabilities[0x20];
} KipHeader;
uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
FILE* fd = fopen(fn, "rb");
if (fd == NULL)
return NULL;
fseek(fd, 0, SEEK_END);
size_t len = ftell(fd);
fseek(fd, 0, SEEK_SET);
uint8_t* buf = malloc(len);
if (buf == NULL) {
fclose(fd);
return NULL;
}
size_t rc = fread(buf, 1, len, fd);
if (rc != len) {
fclose(fd);
free(buf);
return NULL;
}
*len_out = len;
return buf;
}
int cJSON_GetString(const cJSON *obj, const char *field, const char **out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config)) {
*out = config->valuestring;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsNumber(config)) {
*out = (u8)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsNumber(config)) {
*out = (u16)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
if (cJSON_IsNumber(config)) {
*out = (u16)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
return 0;
}
}
int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsBool(config)) {
if (cJSON_IsTrue(config)) {
*out = 1;
} else if (cJSON_IsFalse(config)) {
*out = 0;
} else {
fprintf(stderr, "Unknown boolean value in %s.\n", field);
return 0;
}
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsBool(config)) {
if (cJSON_IsTrue(config)) {
*out = 1;
} else if (cJSON_IsFalse(config)) {
*out = 0;
} else {
fprintf(stderr, "Unknown boolean value in %s.\n", field);
return 0;
}
return 1;
} else {
*out = 0;
return 0;
}
}
int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoull(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", field);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", field);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", field);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoull(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", config->string);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", config->string);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", config->string);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", config->string);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
return 0;
}
}
int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoul(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", field);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", field);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", field);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int ParseKipConfiguration(const char *json, KipHeader *kip_hdr) {
const cJSON *capability = NULL;
const cJSON *capabilities = NULL;
int status = 0;
cJSON *npdm_json = cJSON_Parse(json);
if (npdm_json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "JSON Parse Error: %s\n", error_ptr);
}
status = 0;
goto PARSE_CAPS_END;
}
/* Parse name. */
const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, "name");
if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {
strncpy(kip_hdr->Name, title_name->valuestring, sizeof(kip_hdr->Name) - 1);
} else {
fprintf(stderr, "Failed to get title name (name field not present).\n");
status = 0;
goto PARSE_CAPS_END;
}
/* Parse program_id (or deprecated title_id). */
if (!cJSON_GetU64(npdm_json, "program_id", &kip_hdr->ProgramId) && !cJSON_GetU64(npdm_json, "title_id", &kip_hdr->ProgramId)) {
status = 0;
goto PARSE_CAPS_END;
}
/* Parse use secure memory. */
/* This field is optional, and defaults to true (set before this function is called). */
int use_secure_memory = 1;
if (cJSON_GetBooleanOptional(npdm_json, "use_secure_memory", &use_secure_memory)) {
if (use_secure_memory) {
kip_hdr->Flags |= 0x20;
} else {
kip_hdr->Flags &= ~0x20;
}
}
/* Parse immortality. */
/* This field is optional, and defaults to true (set before this function is called). */
int immortal = 1;
if (cJSON_GetBooleanOptional(npdm_json, "immortal", &immortal)) {
if (immortal) {
kip_hdr->Flags |= 0x40;
} else {
kip_hdr->Flags &= ~0x40;
}
}
/* Parse main_thread_stack_size. */
u64 stack_size = 0;
if (!cJSON_GetU64(npdm_json, "main_thread_stack_size", &stack_size)) {
status = 0;
goto PARSE_CAPS_END;
}
if (stack_size >> 32) {
fprintf(stderr, "Error: Main thread stack size must be a u32!\n");
status = 0;
goto PARSE_CAPS_END;
}
kip_hdr->Segments[1].Attribute = (u32)(stack_size & 0xFFFFFFFF);
/* Parse various config. */
if (!cJSON_GetU8(npdm_json, "main_thread_priority", &kip_hdr->MainThreadPriority)) {
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetU8(npdm_json, "default_cpu_id", &kip_hdr->DefaultCpuId)) {
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetU32(npdm_json, "version", &kip_hdr->Version) && !cJSON_GetU32(npdm_json, "process_category", &kip_hdr->Version)) { // optional
kip_hdr->Version = 1;
}
/* Parse capabilities. */
capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, "kernel_capabilities");
if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {
fprintf(stderr, "Kernel Capabilities must be an array!\n");
status = 0;
goto PARSE_CAPS_END;
}
int kac_obj = 0;
if (cJSON_IsObject(capabilities)) {
kac_obj = 1;
fprintf(stderr, "Using deprecated kernel_capabilities format. Please turn it into an array.\n");
}
u32 cur_cap = 0;
u32 desc;
cJSON_ArrayForEach(capability, capabilities) {
desc = 0;
const char *type_str;
const cJSON *value;
if (kac_obj) {
type_str = capability->string;
value = capability;
} else {
if (!cJSON_GetString(capability, "type", &type_str)) {
status = 0;
goto PARSE_CAPS_END;
}
value = cJSON_GetObjectItemCaseSensitive(capability, "value");
}
if (!strcmp(type_str, "kernel_flags")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Kernel Flags Capability value must be object!\n");
status = 0;
goto PARSE_CAPS_END;
}
u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;
if (!cJSON_GetU8(value, "highest_thread_priority", &highest_prio) ||
!cJSON_GetU8(value, "lowest_thread_priority", &lowest_prio) ||
!cJSON_GetU8(value, "highest_cpu_id", &highest_cpu) ||
!cJSON_GetU8(value, "lowest_cpu_id", &lowest_cpu)) {
status = 0;
goto PARSE_CAPS_END;
}
u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;
u8 real_lowest_prio = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;
desc = highest_cpu;
desc <<= 8;
desc |= lowest_cpu;
desc <<= 6;
desc |= (real_highest_prio & 0x3F);
desc <<= 6;
desc |= (real_lowest_prio & 0x3F);
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 4) | (0x0007));
} else if (!strcmp(type_str, "syscalls")) {
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Syscalls Capability value must be object!\n");
status = 0;
goto PARSE_CAPS_END;
}
u32 num_descriptors;
u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */
char field_name[8] = {0};
const cJSON *cur_syscall = NULL;
u64 syscall_value = 0;
cJSON_ArrayForEach(cur_syscall, value) {
if (cJSON_IsNumber(cur_syscall)) {
syscall_value = (u64)cur_syscall->valueint;
} else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {
fprintf(stderr, "Error: Syscall entries must be integers or hex strings.\n");
status = 0;
goto PARSE_CAPS_END;
}
if (syscall_value >= 0xC0) {
fprintf(stderr, "Error: All syscall entries must be numbers in [0, 0xBF]\n");
status = 0;
goto PARSE_CAPS_END;
}
descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));
}
for (unsigned int i = 0; i < 8; i++) {
if (descriptors[i]) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
desc = descriptors[i] | (i << 24);
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 5) | (0x000F));
}
}
} else if (!strcmp(type_str, "map")) {
if (cur_cap + 2 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Map Capability value must be object!\n");
status = 0;
goto PARSE_CAPS_END;
}
u64 map_address = 0;
u64 map_size = 0;
int is_ro;
int is_io;
if (!cJSON_GetU64(value, "address", &map_address) ||
!cJSON_GetU64(value, "size", &map_size) ||
!cJSON_GetBoolean(value, "is_ro", &is_ro) ||
!cJSON_GetBoolean(value, "is_io", &is_io)) {
status = 0;
goto PARSE_CAPS_END;
}
desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);
desc |= is_ro << 24;
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));
desc = (u32)((map_size >> 12) & 0x000FFFFFULL);
desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);
is_io ^= 1;
desc |= is_io << 24;
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));
} else if (!strcmp(type_str, "map_page")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
u64 page_address = 0;
if (!cJSON_GetU64FromObjectValue(value, &page_address)) {
status = 0;
goto PARSE_CAPS_END;
}
desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 8) | (0x007F));
} else if (!strcmp(type_str, "map_region")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsArray(value)) {
fprintf(stderr, "Map Region capability value must be array!\n");
status = 0;
goto PARSE_CAPS_END;
}
u8 regions[3] = {0};
int is_ro[3] = {0};
const cJSON *cur_region = NULL;
int index = 0;
cJSON_ArrayForEach(cur_region, value) {
if (index >= 3) {
fprintf(stderr, "Too many region descriptors!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsObject(cur_region)) {
fprintf(stderr, "Region descriptor value must be object!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetU8(cur_region, "region_type", ®ions[index]) ||
!cJSON_GetBoolean(cur_region, "is_ro", &is_ro[index])) {
status = 0;
goto PARSE_CAPS_END;
}
index++;
}
u32 capability = 0x3FF;
for (int i = 0; i < 3; ++i) {
capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);
}
kip_hdr->Capabilities[cur_cap++] = capability;
} else if (!strcmp(type_str, "irq_pair")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {
fprintf(stderr, "Error: IRQ Pairs must have size 2 array value.\n");
status = 0;
goto PARSE_CAPS_END;
}
const cJSON *irq = NULL;
int desc_idx = 0;
cJSON_ArrayForEach(irq, value) {
if (cJSON_IsNull(irq)) {
desc |= 0x3FF << desc_idx;
} else if (cJSON_IsNumber(irq)) {
desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;
} else {
fprintf(stderr, "Failed to parse IRQ value.\n");
status = 0;
goto PARSE_CAPS_END;
}
desc_idx += 10;
}
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 12) | (0x07FF));
} else if (!strcmp(type_str, "application_type")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
status = 0;
goto PARSE_CAPS_END;
}
desc &= 7;
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 14) | (0x1FFF));
} else if (!strcmp(type_str, "min_kernel_version")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
u64 kern_ver = 0;
if (cJSON_IsNumber(value)) {
kern_ver = (u64)value->valueint;
} else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {
fprintf(stderr, "Error: Kernel version must be integer or hex strings.\n");
status = 0;
goto PARSE_CAPS_END;
}
desc = (kern_ver) & 0xFFFF;
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 15) | (0x3FFF));
} else if (!strcmp(type_str, "handle_table_size")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
status = 0;
goto PARSE_CAPS_END;
}
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 16) | (0x7FFF));
} else if (!strcmp(type_str, "debug_flags")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Debug Flag Capability value must be object!\n");
status = 0;
goto PARSE_CAPS_END;
}
int allow_debug = 0;
int force_debug = 0;
int force_debug_prod = 0;
if (!cJSON_GetBoolean(value, "allow_debug", &allow_debug)) {
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetBoolean(value, "force_debug", &force_debug)) {
status = 0;
goto PARSE_CAPS_END;
}
if (!cJSON_GetBoolean(value, "force_debug_prod", &force_debug_prod)) {
status = 0;
goto PARSE_CAPS_END;
}
desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);
kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 17) | (0xFFFF));
} else {
fprintf(stderr, "Error: unknown capability %s\n", type_str);
status = 0;
goto PARSE_CAPS_END;
}
}
for (u32 i = cur_cap; i < 0x20; i++) {
kip_hdr->Capabilities[i] = 0xFFFFFFFF;
}
status = 1;
PARSE_CAPS_END:
cJSON_Delete(npdm_json);
return status;
}
int main(int argc, char* argv[]) {
if (argc != 4) {
fprintf(stderr, "%s \n", argv[0]);
return EXIT_FAILURE;
}
KipHeader kip_hdr = {0};
memcpy(kip_hdr.Magic, "KIP1", 4);
kip_hdr.Flags = 0x7F;
if (sizeof(KipHeader) != 0x100) {
fprintf(stderr, "Bad compile environment!\n");
return EXIT_FAILURE;
}
size_t json_len;
uint8_t* json = ReadEntireFile(argv[2], &json_len);
if (json == NULL) {
fprintf(stderr, "Failed to read descriptor json!\n");
return EXIT_FAILURE;
}
if (!ParseKipConfiguration(json, &kip_hdr)) {
fprintf(stderr, "Failed to parse kip configuration!\n");
return EXIT_FAILURE;
}
size_t elf_len;
uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
if (elf == NULL) {
fprintf(stderr, "Failed to open input!\n");
return EXIT_FAILURE;
}
if (elf_len < sizeof(Elf64_Ehdr)) {
fprintf(stderr, "Input file doesn't fit ELF header!\n");
return EXIT_FAILURE;
}
Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
if (hdr->e_machine != EM_AARCH64) {
fprintf(stderr, "Invalid ELF: expected AArch64!\n");
return EXIT_FAILURE;
}
Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
if (ph_end < hdr->e_phoff || ph_end > elf_len) {
fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
return EXIT_FAILURE;
}
Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
size_t i, j = 0;
size_t file_off = 0;
size_t dst_off = 0;
size_t tmpsize;
uint8_t* buf[3];
uint8_t* cmp[3];
size_t FileOffsets[3];
for (i=0; i<4; i++) {
Elf64_Phdr* phdr = NULL;
while (j < hdr->e_phnum) {
Elf64_Phdr* cur = &phdrs[j];
if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
if (cur->p_type == PT_LOAD || i == 3) {
phdr = cur;
break;
}
}
if (phdr == NULL) {
fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
return EXIT_FAILURE;
}
kip_hdr.Segments[i].DstOff = dst_off;
// .bss is special
if (i == 3) {
tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
if ( phdr->p_memsz > tmpsize) {
kip_hdr.Segments[i].DecompSz = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
} else {
kip_hdr.Segments[i].DecompSz = 0;
}
kip_hdr.Segments[i].CompSz = 0;
break;
}
FileOffsets[i] = file_off;
kip_hdr.Segments[i].DecompSz = phdr->p_filesz;
buf[i] = malloc(kip_hdr.Segments[i].DecompSz);
if (buf[i] == NULL) {
fprintf(stderr, "Out of memory!\n");
return EXIT_FAILURE;
}
memset(buf[i], 0, kip_hdr.Segments[i].DecompSz);
memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);
cmp[i] = BLZ_Code(buf[i], phdr->p_filesz, &kip_hdr.Segments[i].CompSz, BLZ_BEST);
file_off += kip_hdr.Segments[i].CompSz;
dst_off += kip_hdr.Segments[i].DecompSz;
dst_off = (dst_off + 0xFFF) & ~0xFFF;
}
FILE* out = fopen(argv[3], "wb");
if (out == NULL) {
fprintf(stderr, "Failed to open output file!\n");
return EXIT_FAILURE;
}
// TODO check retvals
for (i=0; i<3; i++)
{
fseek(out, sizeof(kip_hdr) + FileOffsets[i], SEEK_SET);
fwrite(cmp[i], kip_hdr.Segments[i].CompSz, 1, out);
}
fseek(out, 0, SEEK_SET);
fwrite(&kip_hdr, sizeof(kip_hdr), 1, out);
fclose(out);
return EXIT_SUCCESS;
}
================================================
FILE: src/elf2nro.c
================================================
// Copyright 2017 plutoo
#include
#include
#include
#include
#include
#include "sha256.h"
#include "elf64.h"
#include "romfs.h"
typedef struct {
u32 FileOff;
u32 Size;
} NsoSegment;
typedef struct {
u32 unused;
u32 modOffset;
u8 Padding[8];
} NroStart;
typedef struct {
u8 Magic[4];
u32 version;
u32 size;
u32 flags;
NsoSegment Segments[3];
u32 bssSize;
u32 Unk3;
u8 BuildId[0x20];
u8 Padding[0x20];
} NroHeader;
typedef struct {
u64 offset;
u64 size;
} AssetSection;
typedef struct {
u8 magic[4];
u32 version;
AssetSection icon;
AssetSection nacp;
AssetSection romfs;
} AssetHeader;
uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
FILE* fd = fopen(fn, "rb");
if (fd == NULL)
return NULL;
fseek(fd, 0, SEEK_END);
size_t len = ftell(fd);
fseek(fd, 0, SEEK_SET);
uint8_t* buf = malloc(len);
if (buf == NULL) {
fclose(fd);
return NULL;
}
size_t rc = fread(buf, 1, len, fd);
if (rc != len) {
fclose(fd);
free(buf);
return NULL;
}
*len_out = len;
return buf;
}
int main(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "%s [options]\n\n", argv[0]);
fprintf(stderr, "Options:\n");
fprintf(stderr, "--icon= Embeds icon into the output file.\n");
fprintf(stderr, "--nacp= Embeds control.nacp into the output file.\n");
fprintf(stderr, "--romfs= Embeds RomFS into the output file.\n");
fprintf(stderr, "--romfsdir= Builds and embeds RomFS into the output file.\n");
fprintf(stderr, "--alignedheader Sets the \"AlignedHeader\" flag in the output file.\n");
return EXIT_FAILURE;
}
NroStart nro_start;
memset(&nro_start, 0, sizeof(nro_start));
NroHeader nro_hdr;
memset(&nro_hdr, 0, sizeof(nro_hdr));
memcpy(nro_hdr.Magic, "NRO0", 4);
if (sizeof(NroHeader) != 0x70) {
fprintf(stderr, "Bad compile environment!\n");
return EXIT_FAILURE;
}
size_t elf_len;
uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
if (elf == NULL) {
fprintf(stderr, "Failed to open input!\n");
return EXIT_FAILURE;
}
int argi;
char* icon_path = NULL, *nacp_path = NULL, *romfs_path = NULL, *romfs_dir_path = NULL;
u32 aligned_header = 0;
for (argi=3; argie_machine != EM_AARCH64) {
fprintf(stderr, "Invalid ELF: expected AArch64!\n");
return EXIT_FAILURE;
}
Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
if (ph_end < hdr->e_phoff || ph_end > elf_len) {
fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
return EXIT_FAILURE;
}
Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
size_t i, j = 0;
size_t file_off = 0;
size_t tmpsize;
uint8_t* buf[3];
for (i=0; i<4; i++) {
Elf64_Phdr* phdr = NULL;
while (j < hdr->e_phnum) {
Elf64_Phdr* cur = &phdrs[j];
if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
if (cur->p_type == PT_LOAD || i == 3) {
phdr = cur;
break;
}
}
if (phdr == NULL) {
fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
return EXIT_FAILURE;
}
// .bss is special
if (i == 3) {
tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
if ( phdr->p_memsz > tmpsize)
nro_hdr.bssSize = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
else
nro_hdr.bssSize = 0;
break;
}
nro_hdr.Segments[i].FileOff = phdr->p_vaddr;
nro_hdr.Segments[i].Size = (phdr->p_filesz + 0xFFF) & ~0xFFF;
buf[i] = malloc(nro_hdr.Segments[i].Size);
memset(buf[i], 0, nro_hdr.Segments[i].Size);
if (buf[i] == NULL) {
fprintf(stderr, "Out of memory!\n");
return EXIT_FAILURE;
}
memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);
file_off += nro_hdr.Segments[i].Size;
file_off = (file_off + 0xFFF) & ~0xFFF;
}
/* Iterate over sections to find build id. */
size_t cur_sect_hdr_ofs = hdr->e_shoff;
for (unsigned int i = 0; i < hdr->e_shnum; i++) {
Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
if (cur_shdr->sh_type == SHT_NOTE) {
Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
u8 *note_desc = note_name + note_hdr->n_namesz;
if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
size_t build_id_size = note_hdr->n_descsz;
if (build_id_size > 0x20) {
build_id_size = 0x20;
}
memcpy(nro_hdr.BuildId, note_desc, build_id_size);
}
}
cur_sect_hdr_ofs += hdr->e_shentsize;
}
FILE* out = fopen(argv[2], "wb");
if (out == NULL) {
fprintf(stderr, "Failed to open output file!\n");
return EXIT_FAILURE;
}
nro_hdr.size = file_off;
nro_hdr.version = 0;
nro_hdr.flags = (aligned_header << 0);
// TODO check retvals
for (i=0; i<3; i++)
{
fseek(out, nro_hdr.Segments[i].FileOff, SEEK_SET);
fwrite(buf[i], nro_hdr.Segments[i].Size, 1, out);
}
fseek(out, sizeof(nro_start), SEEK_SET);
fwrite(&nro_hdr, sizeof(nro_hdr), 1, out);
if (icon_path==NULL && nacp_path==NULL && romfs_path==NULL) {
fclose(out);
return EXIT_SUCCESS;
}
AssetHeader asset_hdr;
memset(&asset_hdr, 0, sizeof(asset_hdr));
memcpy(asset_hdr.magic, "ASET", 4);
asset_hdr.version = 0;
fseek(out, file_off, SEEK_SET);
uint8_t* icon = NULL, *nacp = NULL, *romfs = NULL;
size_t icon_len = 0, nacp_len = 0, romfs_len = 0;
size_t tmp_off = sizeof(asset_hdr);
if (icon_path) {
icon = ReadEntireFile(icon_path, &icon_len);
if (icon == NULL) {
fprintf(stderr, "Failed to open input icon!\n");
return EXIT_FAILURE;
}
asset_hdr.icon.offset = tmp_off;
asset_hdr.icon.size = icon_len;
tmp_off+= icon_len;
}
if (nacp_path) {
nacp = ReadEntireFile(nacp_path, &nacp_len);
if (nacp == NULL) {
fprintf(stderr, "Failed to open input nacp!\n");
return EXIT_FAILURE;
}
asset_hdr.nacp.offset = tmp_off;
asset_hdr.nacp.size = nacp_len;
tmp_off+= nacp_len;
}
if (romfs_path) {
romfs = ReadEntireFile(romfs_path, &romfs_len);
if (romfs == NULL) {
fprintf(stderr, "Failed to open input romfs!\n");
return EXIT_FAILURE;
}
asset_hdr.romfs.offset = tmp_off;
asset_hdr.romfs.size = romfs_len;
tmp_off+= romfs_len;
} else if (romfs_dir_path) {
asset_hdr.romfs.offset = tmp_off;
asset_hdr.romfs.size = build_romfs_by_path_into_file(romfs_dir_path, out, file_off + tmp_off);
tmp_off+= asset_hdr.romfs.size;
fseek(out, file_off, SEEK_SET);
}
fwrite(&asset_hdr, sizeof(asset_hdr), 1, out);
if (icon_path) {
fseek(out, file_off + asset_hdr.icon.offset, SEEK_SET);
fwrite(icon, icon_len, 1, out);
}
if (nacp_path) {
fseek(out, file_off + asset_hdr.nacp.offset, SEEK_SET);
fwrite(nacp, nacp_len, 1, out);
}
if (romfs_path) {
fseek(out, file_off + asset_hdr.romfs.offset, SEEK_SET);
fwrite(romfs, romfs_len, 1, out);
}
fclose(out);
return EXIT_SUCCESS;
}
================================================
FILE: src/elf2nso.c
================================================
// Copyright 2017 plutoo
#include
#include
#include
#include
#include
#include "sha256.h"
#include "elf64.h"
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint8_t u8;
typedef struct {
u32 FileOff;
u32 DstOff;
u32 DecompSz;
u32 AlignOrTotalSz;
} NsoSegment;
typedef u8 Sha2Hash[0x20];
typedef struct {
u8 Magic[4];
u32 Unk1;
u32 Unk2;
u32 Unk3;
NsoSegment Segments[3];
u8 BuildId[0x20];
u32 CompSz[3];
u8 Padding[0x24];
u64 Unk4;
u64 Unk5;
Sha2Hash Hashes[3];
} NsoHeader;
uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
FILE* fd = fopen(fn, "rb");
if (fd == NULL)
return NULL;
fseek(fd, 0, SEEK_END);
size_t len = ftell(fd);
fseek(fd, 0, SEEK_SET);
uint8_t* buf = malloc(len);
if (buf == NULL) {
fclose(fd);
return NULL;
}
size_t rc = fread(buf, 1, len, fd);
if (rc != len) {
fclose(fd);
free(buf);
return NULL;
}
*len_out = len;
return buf;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "%s \n", argv[0]);
return EXIT_FAILURE;
}
NsoHeader nso_hdr;
memset(&nso_hdr, 0, sizeof(nso_hdr));
memcpy(nso_hdr.Magic, "NSO0", 4);
nso_hdr.Unk3 = 0x3f;
if (sizeof(NsoHeader) != 0x100) {
fprintf(stderr, "Bad compile environment!\n");
return EXIT_FAILURE;
}
size_t elf_len;
uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
if (elf == NULL) {
fprintf(stderr, "Failed to open input!\n");
return EXIT_FAILURE;
}
if (elf_len < sizeof(Elf64_Ehdr)) {
fprintf(stderr, "Input file doesn't fit ELF header!\n");
return EXIT_FAILURE;
}
Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
if (hdr->e_machine != EM_AARCH64) {
fprintf(stderr, "Invalid ELF: expected AArch64!\n");
return EXIT_FAILURE;
}
Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);
if (ph_end < hdr->e_phoff || ph_end > elf_len) {
fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
return EXIT_FAILURE;
}
Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
size_t i, j = 0;
size_t file_off = sizeof(NsoHeader);
uint8_t* comp_buf[3];
int comp_sz[3];
for (i=0; i<3; i++) {
Elf64_Phdr* phdr = NULL;
while (j < hdr->e_phnum) {
Elf64_Phdr* cur = &phdrs[j++];
if (cur->p_type == PT_LOAD) {
phdr = cur;
break;
}
}
if (phdr == NULL) {
fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs!\n");
return EXIT_FAILURE;
}
nso_hdr.Segments[i].FileOff = file_off;
nso_hdr.Segments[i].DstOff = phdr->p_vaddr;
nso_hdr.Segments[i].DecompSz = phdr->p_filesz;
// for .data segment this field contains bss size
if (i == 2)
nso_hdr.Segments[i].AlignOrTotalSz = phdr->p_memsz - phdr->p_filesz;
else
nso_hdr.Segments[i].AlignOrTotalSz = 1;
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, &elf[phdr->p_offset], phdr->p_filesz);
sha256_final(&ctx, (u8*) &nso_hdr.Hashes[i]);
size_t comp_max = LZ4_compressBound(phdr->p_filesz);
comp_buf[i] = malloc(comp_max);
if (comp_buf[i] == NULL) {
fprintf(stderr, "Compressing: Out of memory!\n");
return EXIT_FAILURE;
}
// TODO check p_offset
comp_sz[i] = LZ4_compress_default(&elf[phdr->p_offset], comp_buf[i], phdr->p_filesz, comp_max);
if (comp_sz[i] < 0) {
fprintf(stderr, "Failed to compress!\n");
return EXIT_FAILURE;
}
nso_hdr.CompSz[i] = comp_sz[i];
file_off += comp_sz[i];
}
/* Iterate over sections to find build id. */
size_t cur_sect_hdr_ofs = hdr->e_shoff;
for (unsigned int i = 0; i < hdr->e_shnum; i++) {
Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
if (cur_shdr->sh_type == SHT_NOTE) {
Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
u8 *note_desc = note_name + note_hdr->n_namesz;
if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
size_t build_id_size = note_hdr->n_descsz;
if (build_id_size > 0x20) {
build_id_size = 0x20;
}
memcpy(nso_hdr.BuildId, note_desc, build_id_size);
}
}
cur_sect_hdr_ofs += hdr->e_shentsize;
}
FILE* out = fopen(argv[2], "wb");
if (out == NULL) {
fprintf(stderr, "Failed to open output file!\n");
return EXIT_FAILURE;
}
// TODO check retvals
fwrite(&nso_hdr, sizeof(nso_hdr), 1, out);
for (i=0; i<3; i++)
fwrite(comp_buf[i], comp_sz[i], 1, out);
return EXIT_SUCCESS;
}
================================================
FILE: src/elf64.h
================================================
/*-
* Copyright (c) 1996-1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: head/sys/sys/elf64.h 186667 2009-01-01 02:08:56Z obrien $
*/
#ifndef _SYS_ELF64_H_
#define _SYS_ELF64_H_ 1
#include "elf_common.h"
/*
* ELF definitions common to all 64-bit architectures.
*/
typedef uint64_t Elf64_Addr;
typedef uint16_t Elf64_Half;
typedef uint64_t Elf64_Off;
typedef int32_t Elf64_Sword;
typedef int64_t Elf64_Sxword;
typedef uint32_t Elf64_Word;
typedef uint64_t Elf64_Lword;
typedef uint64_t Elf64_Xword;
/*
* Types of dynamic symbol hash table bucket and chain elements.
*
* This is inconsistent among 64 bit architectures, so a machine dependent
* typedef is required.
*/
typedef Elf64_Word Elf64_Hashelt;
/* Non-standard class-dependent datatype used for abstraction. */
typedef Elf64_Xword Elf64_Size;
typedef Elf64_Sxword Elf64_Ssize;
/*
* ELF header.
*/
typedef struct {
unsigned char e_ident[EI_NIDENT]; /* File identification. */
Elf64_Half e_type; /* File type. */
Elf64_Half e_machine; /* Machine architecture. */
Elf64_Word e_version; /* ELF format version. */
Elf64_Addr e_entry; /* Entry point. */
Elf64_Off e_phoff; /* Program header file offset. */
Elf64_Off e_shoff; /* Section header file offset. */
Elf64_Word e_flags; /* Architecture-specific flags. */
Elf64_Half e_ehsize; /* Size of ELF header in bytes. */
Elf64_Half e_phentsize; /* Size of program header entry. */
Elf64_Half e_phnum; /* Number of program header entries. */
Elf64_Half e_shentsize; /* Size of section header entry. */
Elf64_Half e_shnum; /* Number of section header entries. */
Elf64_Half e_shstrndx; /* Section name strings section. */
} Elf64_Ehdr;
/*
* Section header.
*/
typedef struct {
Elf64_Word sh_name; /* Section name (index into the
section header string table). */
Elf64_Word sh_type; /* Section type. */
Elf64_Xword sh_flags; /* Section flags. */
Elf64_Addr sh_addr; /* Address in memory image. */
Elf64_Off sh_offset; /* Offset in file. */
Elf64_Xword sh_size; /* Size in bytes. */
Elf64_Word sh_link; /* Index of a related section. */
Elf64_Word sh_info; /* Depends on section type. */
Elf64_Xword sh_addralign; /* Alignment in bytes. */
Elf64_Xword sh_entsize; /* Size of each entry in section. */
} Elf64_Shdr;
/*
* Program header.
*/
typedef struct {
Elf64_Word p_type; /* Entry type. */
Elf64_Word p_flags; /* Access permission flags. */
Elf64_Off p_offset; /* File offset of contents. */
Elf64_Addr p_vaddr; /* Virtual address in memory image. */
Elf64_Addr p_paddr; /* Physical address (not used). */
Elf64_Xword p_filesz; /* Size of contents in file. */
Elf64_Xword p_memsz; /* Size of contents in memory. */
Elf64_Xword p_align; /* Alignment in memory and file. */
} Elf64_Phdr;
/*
* Dynamic structure. The ".dynamic" section contains an array of them.
*/
typedef struct {
Elf64_Sxword d_tag; /* Entry type. */
union {
Elf64_Xword d_val; /* Integer value. */
Elf64_Addr d_ptr; /* Address value. */
} d_un;
} Elf64_Dyn;
/*
* Relocation entries.
*/
/* Relocations that don't need an addend field. */
typedef struct {
Elf64_Addr r_offset; /* Location to be relocated. */
Elf64_Xword r_info; /* Relocation type and symbol index. */
} Elf64_Rel;
/* Relocations that need an addend field. */
typedef struct {
Elf64_Addr r_offset; /* Location to be relocated. */
Elf64_Xword r_info; /* Relocation type and symbol index. */
Elf64_Sxword r_addend; /* Addend. */
} Elf64_Rela;
/* Macros for accessing the fields of r_info. */
#define ELF64_R_SYM(info) ((info) >> 32)
#define ELF64_R_TYPE(info) ((info) & 0xffffffffL)
/* Macro for constructing r_info from field values. */
#define ELF64_R_INFO(sym, type) (((sym) << 32) + ((type) & 0xffffffffL))
#define ELF64_R_TYPE_DATA(info) (((Elf64_Xword)(info)<<32)>>40)
#define ELF64_R_TYPE_ID(info) (((Elf64_Xword)(info)<<56)>>56)
#define ELF64_R_TYPE_INFO(data, type) \
(((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))
/*
* Note entry header
*/
typedef Elf_Note Elf64_Nhdr;
/*
* Move entry
*/
typedef struct {
Elf64_Lword m_value; /* symbol value */
Elf64_Xword m_info; /* size + index */
Elf64_Xword m_poffset; /* symbol offset */
Elf64_Half m_repeat; /* repeat count */
Elf64_Half m_stride; /* stride info */
} Elf64_Move;
#define ELF64_M_SYM(info) ((info)>>8)
#define ELF64_M_SIZE(info) ((unsigned char)(info))
#define ELF64_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))
/*
* Hardware/Software capabilities entry
*/
typedef struct {
Elf64_Xword c_tag; /* how to interpret value */
union {
Elf64_Xword c_val;
Elf64_Addr c_ptr;
} c_un;
} Elf64_Cap;
/*
* Symbol table entries.
*/
typedef struct {
Elf64_Word st_name; /* String table index of name. */
unsigned char st_info; /* Type and binding information. */
unsigned char st_other; /* Reserved (not used). */
Elf64_Half st_shndx; /* Section index of symbol. */
Elf64_Addr st_value; /* Symbol value. */
Elf64_Xword st_size; /* Size of associated object. */
} Elf64_Sym;
/* Macros for accessing the fields of st_info. */
#define ELF64_ST_BIND(info) ((info) >> 4)
#define ELF64_ST_TYPE(info) ((info) & 0xf)
/* Macro for constructing st_info from field values. */
#define ELF64_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
/* Macro for accessing the fields of st_other. */
#define ELF64_ST_VISIBILITY(oth) ((oth) & 0x3)
/* Structures used by Sun & GNU-style symbol versioning. */
typedef struct {
Elf64_Half vd_version;
Elf64_Half vd_flags;
Elf64_Half vd_ndx;
Elf64_Half vd_cnt;
Elf64_Word vd_hash;
Elf64_Word vd_aux;
Elf64_Word vd_next;
} Elf64_Verdef;
typedef struct {
Elf64_Word vda_name;
Elf64_Word vda_next;
} Elf64_Verdaux;
typedef struct {
Elf64_Half vn_version;
Elf64_Half vn_cnt;
Elf64_Word vn_file;
Elf64_Word vn_aux;
Elf64_Word vn_next;
} Elf64_Verneed;
typedef struct {
Elf64_Word vna_hash;
Elf64_Half vna_flags;
Elf64_Half vna_other;
Elf64_Word vna_name;
Elf64_Word vna_next;
} Elf64_Vernaux;
typedef Elf64_Half Elf64_Versym;
typedef struct {
Elf64_Half si_boundto; /* direct bindings - symbol bound to */
Elf64_Half si_flags; /* per symbol flags */
} Elf64_Syminfo;
#endif /* !_SYS_ELF64_H_ */
================================================
FILE: src/elf_common.h
================================================
/*-
* Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien
* Copyright (c) 1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: head/sys/sys/elf_common.h 273284 2014-10-19 20:23:31Z andrew $
*/
#ifndef _SYS_ELF_COMMON_H_
#define _SYS_ELF_COMMON_H_ 1
/*
* ELF definitions that are independent of architecture or word size.
*/
/*
* Note header. The ".note" section contains an array of notes. Each
* begins with this header, aligned to a word boundary. Immediately
* following the note header is n_namesz bytes of name, padded to the
* next word boundary. Then comes n_descsz bytes of descriptor, again
* padded to a word boundary. The values of n_namesz and n_descsz do
* not include the padding.
*/
typedef struct {
uint32_t n_namesz; /* Length of name. */
uint32_t n_descsz; /* Length of descriptor. */
uint32_t n_type; /* Type of this note. */
} Elf_Note;
/*
* The header for GNU-style hash sections.
*/
typedef struct {
uint32_t gh_nbuckets; /* Number of hash buckets. */
uint32_t gh_symndx; /* First visible symbol in .dynsym. */
uint32_t gh_maskwords; /* #maskwords used in bloom filter. */
uint32_t gh_shift2; /* Bloom filter shift count. */
} Elf_GNU_Hash_Header;
/* Indexes into the e_ident array. Keep synced with
http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
#define EI_MAG0 0 /* Magic number, byte 0. */
#define EI_MAG1 1 /* Magic number, byte 1. */
#define EI_MAG2 2 /* Magic number, byte 2. */
#define EI_MAG3 3 /* Magic number, byte 3. */
#define EI_CLASS 4 /* Class of machine. */
#define EI_DATA 5 /* Data format. */
#define EI_VERSION 6 /* ELF format version. */
#define EI_OSABI 7 /* Operating system / ABI identification */
#define EI_ABIVERSION 8 /* ABI version */
#define OLD_EI_BRAND 8 /* Start of architecture identification. */
#define EI_PAD 9 /* Start of padding (per SVR4 ABI). */
#define EI_NIDENT 16 /* Size of e_ident array. */
/* Values for the magic number bytes. */
#define ELFMAG0 0x7f
#define ELFMAG1 'E'
#define ELFMAG2 'L'
#define ELFMAG3 'F'
#define ELFMAG "\177ELF" /* magic string */
#define SELFMAG 4 /* magic string size */
/* Values for e_ident[EI_VERSION] and e_version. */
#define EV_NONE 0
#define EV_CURRENT 1
/* Values for e_ident[EI_CLASS]. */
#define ELFCLASSNONE 0 /* Unknown class. */
#define ELFCLASS32 1 /* 32-bit architecture. */
#define ELFCLASS64 2 /* 64-bit architecture. */
/* Values for e_ident[EI_DATA]. */
#define ELFDATANONE 0 /* Unknown data format. */
#define ELFDATA2LSB 1 /* 2's complement little-endian. */
#define ELFDATA2MSB 2 /* 2's complement big-endian. */
/* Values for e_ident[EI_OSABI]. */
#define ELFOSABI_NONE 0 /* UNIX System V ABI */
#define ELFOSABI_HPUX 1 /* HP-UX operating system */
#define ELFOSABI_NETBSD 2 /* NetBSD */
#define ELFOSABI_LINUX 3 /* GNU/Linux */
#define ELFOSABI_HURD 4 /* GNU/Hurd */
#define ELFOSABI_86OPEN 5 /* 86Open common IA32 ABI */
#define ELFOSABI_SOLARIS 6 /* Solaris */
#define ELFOSABI_AIX 7 /* AIX */
#define ELFOSABI_IRIX 8 /* IRIX */
#define ELFOSABI_FREEBSD 9 /* FreeBSD */
#define ELFOSABI_TRU64 10 /* TRU64 UNIX */
#define ELFOSABI_MODESTO 11 /* Novell Modesto */
#define ELFOSABI_OPENBSD 12 /* OpenBSD */
#define ELFOSABI_OPENVMS 13 /* Open VMS */
#define ELFOSABI_NSK 14 /* HP Non-Stop Kernel */
#define ELFOSABI_AROS 15 /* Amiga Research OS */
#define ELFOSABI_ARM 97 /* ARM */
#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */
#define ELFOSABI_SYSV ELFOSABI_NONE /* symbol used in old spec */
#define ELFOSABI_MONTEREY ELFOSABI_AIX /* Monterey */
/* e_ident */
#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
(ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
(ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
(ehdr).e_ident[EI_MAG3] == ELFMAG3)
/* Values for e_type. */
#define ET_NONE 0 /* Unknown type. */
#define ET_REL 1 /* Relocatable. */
#define ET_EXEC 2 /* Executable. */
#define ET_DYN 3 /* Shared object. */
#define ET_CORE 4 /* Core file. */
#define ET_LOOS 0xfe00 /* First operating system specific. */
#define ET_HIOS 0xfeff /* Last operating system-specific. */
#define ET_LOPROC 0xff00 /* First processor-specific. */
#define ET_HIPROC 0xffff /* Last processor-specific. */
/* Values for e_machine. */
#define EM_NONE 0 /* Unknown machine. */
#define EM_M32 1 /* AT&T WE32100. */
#define EM_SPARC 2 /* Sun SPARC. */
#define EM_386 3 /* Intel i386. */
#define EM_68K 4 /* Motorola 68000. */
#define EM_88K 5 /* Motorola 88000. */
#define EM_860 7 /* Intel i860. */
#define EM_MIPS 8 /* MIPS R3000 Big-Endian only. */
#define EM_S370 9 /* IBM System/370. */
#define EM_MIPS_RS3_LE 10 /* MIPS R3000 Little-Endian. */
#define EM_PARISC 15 /* HP PA-RISC. */
#define EM_VPP500 17 /* Fujitsu VPP500. */
#define EM_SPARC32PLUS 18 /* SPARC v8plus. */
#define EM_960 19 /* Intel 80960. */
#define EM_PPC 20 /* PowerPC 32-bit. */
#define EM_PPC64 21 /* PowerPC 64-bit. */
#define EM_S390 22 /* IBM System/390. */
#define EM_V800 36 /* NEC V800. */
#define EM_FR20 37 /* Fujitsu FR20. */
#define EM_RH32 38 /* TRW RH-32. */
#define EM_RCE 39 /* Motorola RCE. */
#define EM_ARM 40 /* ARM. */
#define EM_SH 42 /* Hitachi SH. */
#define EM_SPARCV9 43 /* SPARC v9 64-bit. */
#define EM_TRICORE 44 /* Siemens TriCore embedded processor. */
#define EM_ARC 45 /* Argonaut RISC Core. */
#define EM_H8_300 46 /* Hitachi H8/300. */
#define EM_H8_300H 47 /* Hitachi H8/300H. */
#define EM_H8S 48 /* Hitachi H8S. */
#define EM_H8_500 49 /* Hitachi H8/500. */
#define EM_IA_64 50 /* Intel IA-64 Processor. */
#define EM_MIPS_X 51 /* Stanford MIPS-X. */
#define EM_COLDFIRE 52 /* Motorola ColdFire. */
#define EM_68HC12 53 /* Motorola M68HC12. */
#define EM_MMA 54 /* Fujitsu MMA. */
#define EM_PCP 55 /* Siemens PCP. */
#define EM_NCPU 56 /* Sony nCPU. */
#define EM_NDR1 57 /* Denso NDR1 microprocessor. */
#define EM_STARCORE 58 /* Motorola Star*Core processor. */
#define EM_ME16 59 /* Toyota ME16 processor. */
#define EM_ST100 60 /* STMicroelectronics ST100 processor. */
#define EM_TINYJ 61 /* Advanced Logic Corp. TinyJ processor. */
#define EM_X86_64 62 /* Advanced Micro Devices x86-64 */
#define EM_AMD64 EM_X86_64 /* Advanced Micro Devices x86-64 (compat) */
#define EM_PDSP 63 /* Sony DSP Processor. */
#define EM_FX66 66 /* Siemens FX66 microcontroller. */
#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16
microcontroller. */
#define EM_ST7 68 /* STmicroelectronics ST7 8-bit
microcontroller. */
#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller. */
#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller. */
#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller. */
#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller. */
#define EM_SVX 73 /* Silicon Graphics SVx. */
#define EM_ST19 74 /* STMicroelectronics ST19 8-bit mc. */
#define EM_VAX 75 /* Digital VAX. */
#define EM_CRIS 76 /* Axis Communications 32-bit embedded
processor. */
#define EM_JAVELIN 77 /* Infineon Technologies 32-bit embedded
processor. */
#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor. */
#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor. */
#define EM_MMIX 80 /* Donald Knuth's educational 64-bit proc. */
#define EM_HUANY 81 /* Harvard University machine-independent
object files. */
#define EM_PRISM 82 /* SiTera Prism. */
#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller. */
#define EM_FR30 84 /* Fujitsu FR30. */
#define EM_D10V 85 /* Mitsubishi D10V. */
#define EM_D30V 86 /* Mitsubishi D30V. */
#define EM_V850 87 /* NEC v850. */
#define EM_M32R 88 /* Mitsubishi M32R. */
#define EM_MN10300 89 /* Matsushita MN10300. */
#define EM_MN10200 90 /* Matsushita MN10200. */
#define EM_PJ 91 /* picoJava. */
#define EM_OPENRISC 92 /* OpenRISC 32-bit embedded processor. */
#define EM_ARC_A5 93 /* ARC Cores Tangent-A5. */
#define EM_XTENSA 94 /* Tensilica Xtensa Architecture. */
#define EM_VIDEOCORE 95 /* Alphamosaic VideoCore processor. */
#define EM_TMM_GPP 96 /* Thompson Multimedia General Purpose
Processor. */
#define EM_NS32K 97 /* National Semiconductor 32000 series. */
#define EM_TPC 98 /* Tenor Network TPC processor. */
#define EM_SNP1K 99 /* Trebia SNP 1000 processor. */
#define EM_ST200 100 /* STMicroelectronics ST200 microcontroller. */
#define EM_IP2K 101 /* Ubicom IP2xxx microcontroller family. */
#define EM_MAX 102 /* MAX Processor. */
#define EM_CR 103 /* National Semiconductor CompactRISC
microprocessor. */
#define EM_F2MC16 104 /* Fujitsu F2MC16. */
#define EM_MSP430 105 /* Texas Instruments embedded microcontroller
msp430. */
#define EM_BLACKFIN 106 /* Analog Devices Blackfin (DSP) processor. */
#define EM_SE_C33 107 /* S1C33 Family of Seiko Epson processors. */
#define EM_SEP 108 /* Sharp embedded microprocessor. */
#define EM_ARCA 109 /* Arca RISC Microprocessor. */
#define EM_UNICORE 110 /* Microprocessor series from PKU-Unity Ltd.
and MPRC of Peking University */
#define EM_AARCH64 183 /* AArch64 (64-bit ARM) */
/* Non-standard or deprecated. */
#define EM_486 6 /* Intel i486. */
#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */
#define EM_ALPHA_STD 41 /* Digital Alpha (standard value). */
#define EM_ALPHA 0x9026 /* Alpha (written in the absence of an ABI) */
/* Special section indexes. */
#define SHN_UNDEF 0 /* Undefined, missing, irrelevant. */
#define SHN_LORESERVE 0xff00 /* First of reserved range. */
#define SHN_LOPROC 0xff00 /* First processor-specific. */
#define SHN_HIPROC 0xff1f /* Last processor-specific. */
#define SHN_LOOS 0xff20 /* First operating system-specific. */
#define SHN_HIOS 0xff3f /* Last operating system-specific. */
#define SHN_ABS 0xfff1 /* Absolute values. */
#define SHN_COMMON 0xfff2 /* Common data. */
#define SHN_XINDEX 0xffff /* Escape -- index stored elsewhere. */
#define SHN_HIRESERVE 0xffff /* Last of reserved range. */
/* sh_type */
#define SHT_NULL 0 /* inactive */
#define SHT_PROGBITS 1 /* program defined information */
#define SHT_SYMTAB 2 /* symbol table section */
#define SHT_STRTAB 3 /* string table section */
#define SHT_RELA 4 /* relocation section with addends */
#define SHT_HASH 5 /* symbol hash table section */
#define SHT_DYNAMIC 6 /* dynamic section */
#define SHT_NOTE 7 /* note section */
#define SHT_NOBITS 8 /* no space section */
#define SHT_REL 9 /* relocation section - no addends */
#define SHT_SHLIB 10 /* reserved - purpose unknown */
#define SHT_DYNSYM 11 /* dynamic symbol table section */
#define SHT_INIT_ARRAY 14 /* Initialization function pointers. */
#define SHT_FINI_ARRAY 15 /* Termination function pointers. */
#define SHT_PREINIT_ARRAY 16 /* Pre-initialization function ptrs. */
#define SHT_GROUP 17 /* Section group. */
#define SHT_SYMTAB_SHNDX 18 /* Section indexes (see SHN_XINDEX). */
#define SHT_LOOS 0x60000000 /* First of OS specific semantics */
#define SHT_LOSUNW 0x6ffffff4
#define SHT_SUNW_dof 0x6ffffff4
#define SHT_SUNW_cap 0x6ffffff5
#define SHT_SUNW_SIGNATURE 0x6ffffff6
#define SHT_GNU_HASH 0x6ffffff6
#define SHT_GNU_LIBLIST 0x6ffffff7
#define SHT_SUNW_ANNOTATE 0x6ffffff7
#define SHT_SUNW_DEBUGSTR 0x6ffffff8
#define SHT_SUNW_DEBUG 0x6ffffff9
#define SHT_SUNW_move 0x6ffffffa
#define SHT_SUNW_COMDAT 0x6ffffffb
#define SHT_SUNW_syminfo 0x6ffffffc
#define SHT_SUNW_verdef 0x6ffffffd
#define SHT_GNU_verdef 0x6ffffffd /* Symbol versions provided */
#define SHT_SUNW_verneed 0x6ffffffe
#define SHT_GNU_verneed 0x6ffffffe /* Symbol versions required */
#define SHT_SUNW_versym 0x6fffffff
#define SHT_GNU_versym 0x6fffffff /* Symbol version table */
#define SHT_HISUNW 0x6fffffff
#define SHT_HIOS 0x6fffffff /* Last of OS specific semantics */
#define SHT_LOPROC 0x70000000 /* reserved range for processor */
#define SHT_AMD64_UNWIND 0x70000001 /* unwind information */
#define SHT_ARM_EXIDX 0x70000001 /* Exception index table. */
#define SHT_ARM_PREEMPTMAP 0x70000002 /* BPABI DLL dynamic linking
pre-emption map. */
#define SHT_ARM_ATTRIBUTES 0x70000003 /* Object file compatibility
attributes. */
#define SHT_ARM_DEBUGOVERLAY 0x70000004 /* See DBGOVL for details. */
#define SHT_ARM_OVERLAYSECTION 0x70000005 /* See DBGOVL for details. */
#define SHT_MIPS_REGINFO 0x70000006
#define SHT_MIPS_OPTIONS 0x7000000d
#define SHT_MIPS_DWARF 0x7000001e /* MIPS gcc uses MIPS_DWARF */
#define SHT_HIPROC 0x7fffffff /* specific section header types */
#define SHT_LOUSER 0x80000000 /* reserved range for application */
#define SHT_HIUSER 0xffffffff /* specific indexes */
/* Flags for sh_flags. */
#define SHF_WRITE 0x1 /* Section contains writable data. */
#define SHF_ALLOC 0x2 /* Section occupies memory. */
#define SHF_EXECINSTR 0x4 /* Section contains instructions. */
#define SHF_MERGE 0x10 /* Section may be merged. */
#define SHF_STRINGS 0x20 /* Section contains strings. */
#define SHF_INFO_LINK 0x40 /* sh_info holds section index. */
#define SHF_LINK_ORDER 0x80 /* Special ordering requirements. */
#define SHF_OS_NONCONFORMING 0x100 /* OS-specific processing required. */
#define SHF_GROUP 0x200 /* Member of section group. */
#define SHF_TLS 0x400 /* Section contains TLS data. */
#define SHF_MASKOS 0x0ff00000 /* OS-specific semantics. */
#define SHF_MASKPROC 0xf0000000 /* Processor-specific semantics. */
/* Values for p_type. */
#define PT_NULL 0 /* Unused entry. */
#define PT_LOAD 1 /* Loadable segment. */
#define PT_DYNAMIC 2 /* Dynamic linking information segment. */
#define PT_INTERP 3 /* Pathname of interpreter. */
#define PT_NOTE 4 /* Auxiliary information. */
#define PT_SHLIB 5 /* Reserved (not used). */
#define PT_PHDR 6 /* Location of program header itself. */
#define PT_TLS 7 /* Thread local storage segment */
#define PT_LOOS 0x60000000 /* First OS-specific. */
#define PT_SUNW_UNWIND 0x6464e550 /* amd64 UNWIND program header */
#define PT_GNU_EH_FRAME 0x6474e550
#define PT_GNU_STACK 0x6474e551
#define PT_GNU_RELRO 0x6474e552
#define PT_DUMP_DELTA 0x6fb5d000 /* va->pa map for kernel dumps
(currently arm). */
#define PT_LOSUNW 0x6ffffffa
#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */
#define PT_SUNWSTACK 0x6ffffffb /* describes the stack segment */
#define PT_SUNWDTRACE 0x6ffffffc /* private */
#define PT_SUNWCAP 0x6ffffffd /* hard/soft capabilities segment */
#define PT_HISUNW 0x6fffffff
#define PT_HIOS 0x6fffffff /* Last OS-specific. */
#define PT_LOPROC 0x70000000 /* First processor-specific type. */
#define PT_HIPROC 0x7fffffff /* Last processor-specific type. */
/* Values for p_flags. */
#define PF_X 0x1 /* Executable. */
#define PF_W 0x2 /* Writable. */
#define PF_R 0x4 /* Readable. */
#define PF_MASKOS 0x0ff00000 /* Operating system-specific. */
#define PF_MASKPROC 0xf0000000 /* Processor-specific. */
/* Extended program header index. */
#define PN_XNUM 0xffff
/* Values for d_tag. */
#define DT_NULL 0 /* Terminating entry. */
#define DT_NEEDED 1 /* String table offset of a needed shared
library. */
#define DT_PLTRELSZ 2 /* Total size in bytes of PLT relocations. */
#define DT_PLTGOT 3 /* Processor-dependent address. */
#define DT_HASH 4 /* Address of symbol hash table. */
#define DT_STRTAB 5 /* Address of string table. */
#define DT_SYMTAB 6 /* Address of symbol table. */
#define DT_RELA 7 /* Address of ElfNN_Rela relocations. */
#define DT_RELASZ 8 /* Total size of ElfNN_Rela relocations. */
#define DT_RELAENT 9 /* Size of each ElfNN_Rela relocation entry. */
#define DT_STRSZ 10 /* Size of string table. */
#define DT_SYMENT 11 /* Size of each symbol table entry. */
#define DT_INIT 12 /* Address of initialization function. */
#define DT_FINI 13 /* Address of finalization function. */
#define DT_SONAME 14 /* String table offset of shared object
name. */
#define DT_RPATH 15 /* String table offset of library path. [sup] */
#define DT_SYMBOLIC 16 /* Indicates "symbolic" linking. [sup] */
#define DT_REL 17 /* Address of ElfNN_Rel relocations. */
#define DT_RELSZ 18 /* Total size of ElfNN_Rel relocations. */
#define DT_RELENT 19 /* Size of each ElfNN_Rel relocation. */
#define DT_PLTREL 20 /* Type of relocation used for PLT. */
#define DT_DEBUG 21 /* Reserved (not used). */
#define DT_TEXTREL 22 /* Indicates there may be relocations in
non-writable segments. [sup] */
#define DT_JMPREL 23 /* Address of PLT relocations. */
#define DT_BIND_NOW 24 /* [sup] */
#define DT_INIT_ARRAY 25 /* Address of the array of pointers to
initialization functions */
#define DT_FINI_ARRAY 26 /* Address of the array of pointers to
termination functions */
#define DT_INIT_ARRAYSZ 27 /* Size in bytes of the array of
initialization functions. */
#define DT_FINI_ARRAYSZ 28 /* Size in bytes of the array of
termination functions. */
#define DT_RUNPATH 29 /* String table offset of a null-terminated
library search path string. */
#define DT_FLAGS 30 /* Object specific flag values. */
#define DT_ENCODING 32 /* Values greater than or equal to DT_ENCODING
and less than DT_LOOS follow the rules for
the interpretation of the d_un union
as follows: even == 'd_ptr', odd == 'd_val'
or none */
#define DT_PREINIT_ARRAY 32 /* Address of the array of pointers to
pre-initialization functions. */
#define DT_PREINIT_ARRAYSZ 33 /* Size in bytes of the array of
pre-initialization functions. */
#define DT_MAXPOSTAGS 34 /* number of positive tags */
#define DT_LOOS 0x6000000d /* First OS-specific */
#define DT_SUNW_AUXILIARY 0x6000000d /* symbol auxiliary name */
#define DT_SUNW_RTLDINF 0x6000000e /* ld.so.1 info (private) */
#define DT_SUNW_FILTER 0x6000000f /* symbol filter name */
#define DT_SUNW_CAP 0x60000010 /* hardware/software */
#define DT_HIOS 0x6ffff000 /* Last OS-specific */
/*
* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
* Dyn.d_un.d_val field of the Elf*_Dyn structure.
*/
#define DT_VALRNGLO 0x6ffffd00
#define DT_CHECKSUM 0x6ffffdf8 /* elf checksum */
#define DT_PLTPADSZ 0x6ffffdf9 /* pltpadding size */
#define DT_MOVEENT 0x6ffffdfa /* move table entry size */
#define DT_MOVESZ 0x6ffffdfb /* move table size */
#define DT_FEATURE 0x6ffffdfc /* feature holder */
#define DT_POSFLAG_1 0x6ffffdfd /* flags for DT_* entries, effecting */
/* the following DT_* entry. */
/* See DF_P1_* definitions */
#define DT_SYMINSZ 0x6ffffdfe /* syminfo table size (in bytes) */
#define DT_SYMINENT 0x6ffffdff /* syminfo entry size (in bytes) */
#define DT_VALRNGHI 0x6ffffdff
/*
* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
* Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
*
* If any adjustment is made to the ELF object after it has been
* built, these entries will need to be adjusted.
*/
#define DT_ADDRRNGLO 0x6ffffe00
#define DT_GNU_HASH 0x6ffffef5 /* GNU-style hash table */
#define DT_CONFIG 0x6ffffefa /* configuration information */
#define DT_DEPAUDIT 0x6ffffefb /* dependency auditing */
#define DT_AUDIT 0x6ffffefc /* object auditing */
#define DT_PLTPAD 0x6ffffefd /* pltpadding (sparcv9) */
#define DT_MOVETAB 0x6ffffefe /* move table */
#define DT_SYMINFO 0x6ffffeff /* syminfo table */
#define DT_ADDRRNGHI 0x6ffffeff
#define DT_VERSYM 0x6ffffff0 /* Address of versym section. */
#define DT_RELACOUNT 0x6ffffff9 /* number of RELATIVE relocations */
#define DT_RELCOUNT 0x6ffffffa /* number of RELATIVE relocations */
#define DT_FLAGS_1 0x6ffffffb /* state flags - see DF_1_* defs */
#define DT_VERDEF 0x6ffffffc /* Address of verdef section. */
#define DT_VERDEFNUM 0x6ffffffd /* Number of elems in verdef section */
#define DT_VERNEED 0x6ffffffe /* Address of verneed section. */
#define DT_VERNEEDNUM 0x6fffffff /* Number of elems in verneed section */
#define DT_LOPROC 0x70000000 /* First processor-specific type. */
#define DT_DEPRECATED_SPARC_REGISTER 0x7000001
#define DT_AUXILIARY 0x7ffffffd /* shared library auxiliary name */
#define DT_USED 0x7ffffffe /* ignored - same as needed */
#define DT_FILTER 0x7fffffff /* shared library filter name */
#define DT_HIPROC 0x7fffffff /* Last processor-specific type. */
/* Values for DT_FLAGS */
#define DF_ORIGIN 0x0001 /* Indicates that the object being loaded may
make reference to the $ORIGIN substitution
string */
#define DF_SYMBOLIC 0x0002 /* Indicates "symbolic" linking. */
#define DF_TEXTREL 0x0004 /* Indicates there may be relocations in
non-writable segments. */
#define DF_BIND_NOW 0x0008 /* Indicates that the dynamic linker should
process all relocations for the object
containing this entry before transferring
control to the program. */
#define DF_STATIC_TLS 0x0010 /* Indicates that the shared object or
executable contains code using a static
thread-local storage scheme. */
/* Values for DT_FLAGS_1 */
#define DF_1_BIND_NOW 0x00000001 /* Same as DF_BIND_NOW */
#define DF_1_GLOBAL 0x00000002 /* Set the RTLD_GLOBAL for object */
#define DF_1_NODELETE 0x00000008 /* Set the RTLD_NODELETE for object */
#define DF_1_LOADFLTR 0x00000010 /* Immediate loading of filtees */
#define DF_1_NOOPEN 0x00000040 /* Do not allow loading on dlopen() */
#define DF_1_ORIGIN 0x00000080 /* Process $ORIGIN */
#define DF_1_INTERPOSE 0x00000400 /* Interpose all objects but main */
#define DF_1_NODEFLIB 0x00000800 /* Do not search default paths */
/* Values for n_type. Used in core files. */
#define NT_PRSTATUS 1 /* Process status. */
#define NT_FPREGSET 2 /* Floating point registers. */
#define NT_PRPSINFO 3 /* Process state info. */
#define NT_THRMISC 7 /* Thread miscellaneous info. */
#define NT_PROCSTAT_PROC 8 /* Procstat proc data. */
#define NT_PROCSTAT_FILES 9 /* Procstat files data. */
#define NT_PROCSTAT_VMMAP 10 /* Procstat vmmap data. */
#define NT_PROCSTAT_GROUPS 11 /* Procstat groups data. */
#define NT_PROCSTAT_UMASK 12 /* Procstat umask data. */
#define NT_PROCSTAT_RLIMIT 13 /* Procstat rlimit data. */
#define NT_PROCSTAT_OSREL 14 /* Procstat osreldate data. */
#define NT_PROCSTAT_PSSTRINGS 15 /* Procstat ps_strings data. */
#define NT_PROCSTAT_AUXV 16 /* Procstat auxv data. */
/* Symbol Binding - ELFNN_ST_BIND - st_info */
#define STB_LOCAL 0 /* Local symbol */
#define STB_GLOBAL 1 /* Global symbol */
#define STB_WEAK 2 /* like global - lower precedence */
#define STB_LOOS 10 /* Reserved range for operating system */
#define STB_HIOS 12 /* specific semantics. */
#define STB_LOPROC 13 /* reserved range for processor */
#define STB_HIPROC 15 /* specific semantics. */
/* Symbol type - ELFNN_ST_TYPE - st_info */
#define STT_NOTYPE 0 /* Unspecified type. */
#define STT_OBJECT 1 /* Data object. */
#define STT_FUNC 2 /* Function. */
#define STT_SECTION 3 /* Section. */
#define STT_FILE 4 /* Source file. */
#define STT_COMMON 5 /* Uninitialized common block. */
#define STT_TLS 6 /* TLS object. */
#define STT_NUM 7
#define STT_LOOS 10 /* Reserved range for operating system */
#define STT_GNU_IFUNC 10
#define STT_HIOS 12 /* specific semantics. */
#define STT_LOPROC 13 /* reserved range for processor */
#define STT_HIPROC 15 /* specific semantics. */
/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
#define STV_DEFAULT 0x0 /* Default visibility (see binding). */
#define STV_INTERNAL 0x1 /* Special meaning in relocatable objects. */
#define STV_HIDDEN 0x2 /* Not visible. */
#define STV_PROTECTED 0x3 /* Visible but not preemptible. */
#define STV_EXPORTED 0x4
#define STV_SINGLETON 0x5
#define STV_ELIMINATE 0x6
/* Special symbol table indexes. */
#define STN_UNDEF 0 /* Undefined symbol index. */
/* Symbol versioning flags. */
#define VER_DEF_CURRENT 1
#define VER_DEF_IDX(x) VER_NDX(x)
#define VER_FLG_BASE 0x01
#define VER_FLG_WEAK 0x02
#define VER_NEED_CURRENT 1
#define VER_NEED_WEAK (1u << 15)
#define VER_NEED_HIDDEN VER_NDX_HIDDEN
#define VER_NEED_IDX(x) VER_NDX(x)
#define VER_NDX_LOCAL 0
#define VER_NDX_GLOBAL 1
#define VER_NDX_GIVEN 2
#define VER_NDX_HIDDEN (1u << 15)
#define VER_NDX(x) ((x) & ~(1u << 15))
#define CA_SUNW_NULL 0
#define CA_SUNW_HW_1 1 /* first hardware capabilities entry */
#define CA_SUNW_SF_1 2 /* first software capabilities entry */
/*
* Syminfo flag values
*/
#define SYMINFO_FLG_DIRECT 0x0001 /* symbol ref has direct association */
/* to object containing defn. */
#define SYMINFO_FLG_PASSTHRU 0x0002 /* ignored - see SYMINFO_FLG_FILTER */
#define SYMINFO_FLG_COPY 0x0004 /* symbol is a copy-reloc */
#define SYMINFO_FLG_LAZYLOAD 0x0008 /* object containing defn should be */
/* lazily-loaded */
#define SYMINFO_FLG_DIRECTBIND 0x0010 /* ref should be bound directly to */
/* object containing defn. */
#define SYMINFO_FLG_NOEXTDIRECT 0x0020 /* don't let an external reference */
/* directly bind to this symbol */
#define SYMINFO_FLG_FILTER 0x0002 /* symbol ref is associated to a */
#define SYMINFO_FLG_AUXILIARY 0x0040 /* standard or auxiliary filter */
/*
* Syminfo.si_boundto values.
*/
#define SYMINFO_BT_SELF 0xffff /* symbol bound to self */
#define SYMINFO_BT_PARENT 0xfffe /* symbol bound to parent */
#define SYMINFO_BT_NONE 0xfffd /* no special symbol binding */
#define SYMINFO_BT_EXTERN 0xfffc /* symbol defined as external */
#define SYMINFO_BT_LOWRESERVE 0xff00 /* beginning of reserved entries */
/*
* Syminfo version values.
*/
#define SYMINFO_NONE 0 /* Syminfo version */
#define SYMINFO_CURRENT 1
#define SYMINFO_NUM 2
/*
* Relocation types.
*
* All machine architectures are defined here to allow tools on one to
* handle others.
*/
#define R_386_NONE 0 /* No relocation. */
#define R_386_32 1 /* Add symbol value. */
#define R_386_PC32 2 /* Add PC-relative symbol value. */
#define R_386_GOT32 3 /* Add PC-relative GOT offset. */
#define R_386_PLT32 4 /* Add PC-relative PLT offset. */
#define R_386_COPY 5 /* Copy data from shared object. */
#define R_386_GLOB_DAT 6 /* Set GOT entry to data address. */
#define R_386_JMP_SLOT 7 /* Set GOT entry to code address. */
#define R_386_RELATIVE 8 /* Add load address of shared object. */
#define R_386_GOTOFF 9 /* Add GOT-relative symbol address. */
#define R_386_GOTPC 10 /* Add PC-relative GOT table address. */
#define R_386_TLS_TPOFF 14 /* Negative offset in static TLS block */
#define R_386_TLS_IE 15 /* Absolute address of GOT for -ve static TLS */
#define R_386_TLS_GOTIE 16 /* GOT entry for negative static TLS block */
#define R_386_TLS_LE 17 /* Negative offset relative to static TLS */
#define R_386_TLS_GD 18 /* 32 bit offset to GOT (index,off) pair */
#define R_386_TLS_LDM 19 /* 32 bit offset to GOT (index,zero) pair */
#define R_386_TLS_GD_32 24 /* 32 bit offset to GOT (index,off) pair */
#define R_386_TLS_GD_PUSH 25 /* pushl instruction for Sun ABI GD sequence */
#define R_386_TLS_GD_CALL 26 /* call instruction for Sun ABI GD sequence */
#define R_386_TLS_GD_POP 27 /* popl instruction for Sun ABI GD sequence */
#define R_386_TLS_LDM_32 28 /* 32 bit offset to GOT (index,zero) pair */
#define R_386_TLS_LDM_PUSH 29 /* pushl instruction for Sun ABI LD sequence */
#define R_386_TLS_LDM_CALL 30 /* call instruction for Sun ABI LD sequence */
#define R_386_TLS_LDM_POP 31 /* popl instruction for Sun ABI LD sequence */
#define R_386_TLS_LDO_32 32 /* 32 bit offset from start of TLS block */
#define R_386_TLS_IE_32 33 /* 32 bit offset to GOT static TLS offset entry */
#define R_386_TLS_LE_32 34 /* 32 bit offset within static TLS block */
#define R_386_TLS_DTPMOD32 35 /* GOT entry containing TLS index */
#define R_386_TLS_DTPOFF32 36 /* GOT entry containing TLS offset */
#define R_386_TLS_TPOFF32 37 /* GOT entry of -ve static TLS offset */
#define R_386_IRELATIVE 42 /* PLT entry resolved indirectly at runtime */
#define R_ARM_NONE 0 /* No relocation. */
#define R_ARM_PC24 1
#define R_ARM_ABS32 2
#define R_ARM_REL32 3
#define R_ARM_PC13 4
#define R_ARM_ABS16 5
#define R_ARM_ABS12 6
#define R_ARM_THM_ABS5 7
#define R_ARM_ABS8 8
#define R_ARM_SBREL32 9
#define R_ARM_THM_PC22 10
#define R_ARM_THM_PC8 11
#define R_ARM_AMP_VCALL9 12
#define R_ARM_SWI24 13
#define R_ARM_THM_SWI8 14
#define R_ARM_XPC25 15
#define R_ARM_THM_XPC22 16
/* TLS relocations */
#define R_ARM_TLS_DTPMOD32 17 /* ID of module containing symbol */
#define R_ARM_TLS_DTPOFF32 18 /* Offset in TLS block */
#define R_ARM_TLS_TPOFF32 19 /* Offset in static TLS block */
#define R_ARM_COPY 20 /* Copy data from shared object. */
#define R_ARM_GLOB_DAT 21 /* Set GOT entry to data address. */
#define R_ARM_JUMP_SLOT 22 /* Set GOT entry to code address. */
#define R_ARM_RELATIVE 23 /* Add load address of shared object. */
#define R_ARM_GOTOFF 24 /* Add GOT-relative symbol address. */
#define R_ARM_GOTPC 25 /* Add PC-relative GOT table address. */
#define R_ARM_GOT32 26 /* Add PC-relative GOT offset. */
#define R_ARM_PLT32 27 /* Add PC-relative PLT offset. */
#define R_ARM_GNU_VTENTRY 100
#define R_ARM_GNU_VTINHERIT 101
#define R_ARM_RSBREL32 250
#define R_ARM_THM_RPC22 251
#define R_ARM_RREL32 252
#define R_ARM_RABS32 253
#define R_ARM_RPC24 254
#define R_ARM_RBASE 255
/* Name Value Field Calculation */
#define R_IA_64_NONE 0 /* None */
#define R_IA_64_IMM14 0x21 /* immediate14 S + A */
#define R_IA_64_IMM22 0x22 /* immediate22 S + A */
#define R_IA_64_IMM64 0x23 /* immediate64 S + A */
#define R_IA_64_DIR32MSB 0x24 /* word32 MSB S + A */
#define R_IA_64_DIR32LSB 0x25 /* word32 LSB S + A */
#define R_IA_64_DIR64MSB 0x26 /* word64 MSB S + A */
#define R_IA_64_DIR64LSB 0x27 /* word64 LSB S + A */
#define R_IA_64_GPREL22 0x2a /* immediate22 @gprel(S + A) */
#define R_IA_64_GPREL64I 0x2b /* immediate64 @gprel(S + A) */
#define R_IA_64_GPREL32MSB 0x2c /* word32 MSB @gprel(S + A) */
#define R_IA_64_GPREL32LSB 0x2d /* word32 LSB @gprel(S + A) */
#define R_IA_64_GPREL64MSB 0x2e /* word64 MSB @gprel(S + A) */
#define R_IA_64_GPREL64LSB 0x2f /* word64 LSB @gprel(S + A) */
#define R_IA_64_LTOFF22 0x32 /* immediate22 @ltoff(S + A) */
#define R_IA_64_LTOFF64I 0x33 /* immediate64 @ltoff(S + A) */
#define R_IA_64_PLTOFF22 0x3a /* immediate22 @pltoff(S + A) */
#define R_IA_64_PLTOFF64I 0x3b /* immediate64 @pltoff(S + A) */
#define R_IA_64_PLTOFF64MSB 0x3e /* word64 MSB @pltoff(S + A) */
#define R_IA_64_PLTOFF64LSB 0x3f /* word64 LSB @pltoff(S + A) */
#define R_IA_64_FPTR64I 0x43 /* immediate64 @fptr(S + A) */
#define R_IA_64_FPTR32MSB 0x44 /* word32 MSB @fptr(S + A) */
#define R_IA_64_FPTR32LSB 0x45 /* word32 LSB @fptr(S + A) */
#define R_IA_64_FPTR64MSB 0x46 /* word64 MSB @fptr(S + A) */
#define R_IA_64_FPTR64LSB 0x47 /* word64 LSB @fptr(S + A) */
#define R_IA_64_PCREL60B 0x48 /* immediate60 form1 S + A - P */
#define R_IA_64_PCREL21B 0x49 /* immediate21 form1 S + A - P */
#define R_IA_64_PCREL21M 0x4a /* immediate21 form2 S + A - P */
#define R_IA_64_PCREL21F 0x4b /* immediate21 form3 S + A - P */
#define R_IA_64_PCREL32MSB 0x4c /* word32 MSB S + A - P */
#define R_IA_64_PCREL32LSB 0x4d /* word32 LSB S + A - P */
#define R_IA_64_PCREL64MSB 0x4e /* word64 MSB S + A - P */
#define R_IA_64_PCREL64LSB 0x4f /* word64 LSB S + A - P */
#define R_IA_64_LTOFF_FPTR22 0x52 /* immediate22 @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64I 0x53 /* immediate64 @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR32MSB 0x54 /* word32 MSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR32LSB 0x55 /* word32 LSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64MSB 0x56 /* word64 MSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64LSB 0x57 /* word64 LSB @ltoff(@fptr(S + A)) */
#define R_IA_64_SEGREL32MSB 0x5c /* word32 MSB @segrel(S + A) */
#define R_IA_64_SEGREL32LSB 0x5d /* word32 LSB @segrel(S + A) */
#define R_IA_64_SEGREL64MSB 0x5e /* word64 MSB @segrel(S + A) */
#define R_IA_64_SEGREL64LSB 0x5f /* word64 LSB @segrel(S + A) */
#define R_IA_64_SECREL32MSB 0x64 /* word32 MSB @secrel(S + A) */
#define R_IA_64_SECREL32LSB 0x65 /* word32 LSB @secrel(S + A) */
#define R_IA_64_SECREL64MSB 0x66 /* word64 MSB @secrel(S + A) */
#define R_IA_64_SECREL64LSB 0x67 /* word64 LSB @secrel(S + A) */
#define R_IA_64_REL32MSB 0x6c /* word32 MSB BD + A */
#define R_IA_64_REL32LSB 0x6d /* word32 LSB BD + A */
#define R_IA_64_REL64MSB 0x6e /* word64 MSB BD + A */
#define R_IA_64_REL64LSB 0x6f /* word64 LSB BD + A */
#define R_IA_64_LTV32MSB 0x74 /* word32 MSB S + A */
#define R_IA_64_LTV32LSB 0x75 /* word32 LSB S + A */
#define R_IA_64_LTV64MSB 0x76 /* word64 MSB S + A */
#define R_IA_64_LTV64LSB 0x77 /* word64 LSB S + A */
#define R_IA_64_PCREL21BI 0x79 /* immediate21 form1 S + A - P */
#define R_IA_64_PCREL22 0x7a /* immediate22 S + A - P */
#define R_IA_64_PCREL64I 0x7b /* immediate64 S + A - P */
#define R_IA_64_IPLTMSB 0x80 /* function descriptor MSB special */
#define R_IA_64_IPLTLSB 0x81 /* function descriptor LSB speciaal */
#define R_IA_64_SUB 0x85 /* immediate64 A - S */
#define R_IA_64_LTOFF22X 0x86 /* immediate22 special */
#define R_IA_64_LDXMOV 0x87 /* immediate22 special */
#define R_IA_64_TPREL14 0x91 /* imm14 @tprel(S + A) */
#define R_IA_64_TPREL22 0x92 /* imm22 @tprel(S + A) */
#define R_IA_64_TPREL64I 0x93 /* imm64 @tprel(S + A) */
#define R_IA_64_TPREL64MSB 0x96 /* word64 MSB @tprel(S + A) */
#define R_IA_64_TPREL64LSB 0x97 /* word64 LSB @tprel(S + A) */
#define R_IA_64_LTOFF_TPREL22 0x9a /* imm22 @ltoff(@tprel(S+A)) */
#define R_IA_64_DTPMOD64MSB 0xa6 /* word64 MSB @dtpmod(S + A) */
#define R_IA_64_DTPMOD64LSB 0xa7 /* word64 LSB @dtpmod(S + A) */
#define R_IA_64_LTOFF_DTPMOD22 0xaa /* imm22 @ltoff(@dtpmod(S+A)) */
#define R_IA_64_DTPREL14 0xb1 /* imm14 @dtprel(S + A) */
#define R_IA_64_DTPREL22 0xb2 /* imm22 @dtprel(S + A) */
#define R_IA_64_DTPREL64I 0xb3 /* imm64 @dtprel(S + A) */
#define R_IA_64_DTPREL32MSB 0xb4 /* word32 MSB @dtprel(S + A) */
#define R_IA_64_DTPREL32LSB 0xb5 /* word32 LSB @dtprel(S + A) */
#define R_IA_64_DTPREL64MSB 0xb6 /* word64 MSB @dtprel(S + A) */
#define R_IA_64_DTPREL64LSB 0xb7 /* word64 LSB @dtprel(S + A) */
#define R_IA_64_LTOFF_DTPREL22 0xba /* imm22 @ltoff(@dtprel(S+A)) */
#define R_MIPS_NONE 0 /* No reloc */
#define R_MIPS_16 1 /* Direct 16 bit */
#define R_MIPS_32 2 /* Direct 32 bit */
#define R_MIPS_REL32 3 /* PC relative 32 bit */
#define R_MIPS_26 4 /* Direct 26 bit shifted */
#define R_MIPS_HI16 5 /* High 16 bit */
#define R_MIPS_LO16 6 /* Low 16 bit */
#define R_MIPS_GPREL16 7 /* GP relative 16 bit */
#define R_MIPS_LITERAL 8 /* 16 bit literal entry */
#define R_MIPS_GOT16 9 /* 16 bit GOT entry */
#define R_MIPS_PC16 10 /* PC relative 16 bit */
#define R_MIPS_CALL16 11 /* 16 bit GOT entry for function */
#define R_MIPS_GPREL32 12 /* GP relative 32 bit */
#define R_MIPS_64 18 /* Direct 64 bit */
#define R_MIPS_GOTHI16 21 /* GOT HI 16 bit */
#define R_MIPS_GOTLO16 22 /* GOT LO 16 bit */
#define R_MIPS_CALLHI16 30 /* upper 16 bit GOT entry for function */
#define R_MIPS_CALLLO16 31 /* lower 16 bit GOT entry for function */
#define R_PPC_NONE 0 /* No relocation. */
#define R_PPC_ADDR32 1
#define R_PPC_ADDR24 2
#define R_PPC_ADDR16 3
#define R_PPC_ADDR16_LO 4
#define R_PPC_ADDR16_HI 5
#define R_PPC_ADDR16_HA 6
#define R_PPC_ADDR14 7
#define R_PPC_ADDR14_BRTAKEN 8
#define R_PPC_ADDR14_BRNTAKEN 9
#define R_PPC_REL24 10
#define R_PPC_REL14 11
#define R_PPC_REL14_BRTAKEN 12
#define R_PPC_REL14_BRNTAKEN 13
#define R_PPC_GOT16 14
#define R_PPC_GOT16_LO 15
#define R_PPC_GOT16_HI 16
#define R_PPC_GOT16_HA 17
#define R_PPC_PLTREL24 18
#define R_PPC_COPY 19
#define R_PPC_GLOB_DAT 20
#define R_PPC_JMP_SLOT 21
#define R_PPC_RELATIVE 22
#define R_PPC_LOCAL24PC 23
#define R_PPC_UADDR32 24
#define R_PPC_UADDR16 25
#define R_PPC_REL32 26
#define R_PPC_PLT32 27
#define R_PPC_PLTREL32 28
#define R_PPC_PLT16_LO 29
#define R_PPC_PLT16_HI 30
#define R_PPC_PLT16_HA 31
#define R_PPC_SDAREL16 32
#define R_PPC_SECTOFF 33
#define R_PPC_SECTOFF_LO 34
#define R_PPC_SECTOFF_HI 35
#define R_PPC_SECTOFF_HA 36
/*
* 64-bit relocations
*/
#define R_PPC64_ADDR64 38
#define R_PPC64_ADDR16_HIGHER 39
#define R_PPC64_ADDR16_HIGHERA 40
#define R_PPC64_ADDR16_HIGHEST 41
#define R_PPC64_ADDR16_HIGHESTA 42
#define R_PPC64_UADDR64 43
#define R_PPC64_REL64 44
#define R_PPC64_PLT64 45
#define R_PPC64_PLTREL64 46
#define R_PPC64_TOC16 47
#define R_PPC64_TOC16_LO 48
#define R_PPC64_TOC16_HI 49
#define R_PPC64_TOC16_HA 50
#define R_PPC64_TOC 51
#define R_PPC64_DTPMOD64 68
#define R_PPC64_TPREL64 73
#define R_PPC64_DTPREL64 78
/*
* TLS relocations
*/
#define R_PPC_TLS 67
#define R_PPC_DTPMOD32 68
#define R_PPC_TPREL16 69
#define R_PPC_TPREL16_LO 70
#define R_PPC_TPREL16_HI 71
#define R_PPC_TPREL16_HA 72
#define R_PPC_TPREL32 73
#define R_PPC_DTPREL16 74
#define R_PPC_DTPREL16_LO 75
#define R_PPC_DTPREL16_HI 76
#define R_PPC_DTPREL16_HA 77
#define R_PPC_DTPREL32 78
#define R_PPC_GOT_TLSGD16 79
#define R_PPC_GOT_TLSGD16_LO 80
#define R_PPC_GOT_TLSGD16_HI 81
#define R_PPC_GOT_TLSGD16_HA 82
#define R_PPC_GOT_TLSLD16 83
#define R_PPC_GOT_TLSLD16_LO 84
#define R_PPC_GOT_TLSLD16_HI 85
#define R_PPC_GOT_TLSLD16_HA 86
#define R_PPC_GOT_TPREL16 87
#define R_PPC_GOT_TPREL16_LO 88
#define R_PPC_GOT_TPREL16_HI 89
#define R_PPC_GOT_TPREL16_HA 90
/*
* The remaining relocs are from the Embedded ELF ABI, and are not in the
* SVR4 ELF ABI.
*/
#define R_PPC_EMB_NADDR32 101
#define R_PPC_EMB_NADDR16 102
#define R_PPC_EMB_NADDR16_LO 103
#define R_PPC_EMB_NADDR16_HI 104
#define R_PPC_EMB_NADDR16_HA 105
#define R_PPC_EMB_SDAI16 106
#define R_PPC_EMB_SDA2I16 107
#define R_PPC_EMB_SDA2REL 108
#define R_PPC_EMB_SDA21 109
#define R_PPC_EMB_MRKREF 110
#define R_PPC_EMB_RELSEC16 111
#define R_PPC_EMB_RELST_LO 112
#define R_PPC_EMB_RELST_HI 113
#define R_PPC_EMB_RELST_HA 114
#define R_PPC_EMB_BIT_FLD 115
#define R_PPC_EMB_RELSDA 116
#define R_SPARC_NONE 0
#define R_SPARC_8 1
#define R_SPARC_16 2
#define R_SPARC_32 3
#define R_SPARC_DISP8 4
#define R_SPARC_DISP16 5
#define R_SPARC_DISP32 6
#define R_SPARC_WDISP30 7
#define R_SPARC_WDISP22 8
#define R_SPARC_HI22 9
#define R_SPARC_22 10
#define R_SPARC_13 11
#define R_SPARC_LO10 12
#define R_SPARC_GOT10 13
#define R_SPARC_GOT13 14
#define R_SPARC_GOT22 15
#define R_SPARC_PC10 16
#define R_SPARC_PC22 17
#define R_SPARC_WPLT30 18
#define R_SPARC_COPY 19
#define R_SPARC_GLOB_DAT 20
#define R_SPARC_JMP_SLOT 21
#define R_SPARC_RELATIVE 22
#define R_SPARC_UA32 23
#define R_SPARC_PLT32 24
#define R_SPARC_HIPLT22 25
#define R_SPARC_LOPLT10 26
#define R_SPARC_PCPLT32 27
#define R_SPARC_PCPLT22 28
#define R_SPARC_PCPLT10 29
#define R_SPARC_10 30
#define R_SPARC_11 31
#define R_SPARC_64 32
#define R_SPARC_OLO10 33
#define R_SPARC_HH22 34
#define R_SPARC_HM10 35
#define R_SPARC_LM22 36
#define R_SPARC_PC_HH22 37
#define R_SPARC_PC_HM10 38
#define R_SPARC_PC_LM22 39
#define R_SPARC_WDISP16 40
#define R_SPARC_WDISP19 41
#define R_SPARC_GLOB_JMP 42
#define R_SPARC_7 43
#define R_SPARC_5 44
#define R_SPARC_6 45
#define R_SPARC_DISP64 46
#define R_SPARC_PLT64 47
#define R_SPARC_HIX22 48
#define R_SPARC_LOX10 49
#define R_SPARC_H44 50
#define R_SPARC_M44 51
#define R_SPARC_L44 52
#define R_SPARC_REGISTER 53
#define R_SPARC_UA64 54
#define R_SPARC_UA16 55
#define R_SPARC_TLS_GD_HI22 56
#define R_SPARC_TLS_GD_LO10 57
#define R_SPARC_TLS_GD_ADD 58
#define R_SPARC_TLS_GD_CALL 59
#define R_SPARC_TLS_LDM_HI22 60
#define R_SPARC_TLS_LDM_LO10 61
#define R_SPARC_TLS_LDM_ADD 62
#define R_SPARC_TLS_LDM_CALL 63
#define R_SPARC_TLS_LDO_HIX22 64
#define R_SPARC_TLS_LDO_LOX10 65
#define R_SPARC_TLS_LDO_ADD 66
#define R_SPARC_TLS_IE_HI22 67
#define R_SPARC_TLS_IE_LO10 68
#define R_SPARC_TLS_IE_LD 69
#define R_SPARC_TLS_IE_LDX 70
#define R_SPARC_TLS_IE_ADD 71
#define R_SPARC_TLS_LE_HIX22 72
#define R_SPARC_TLS_LE_LOX10 73
#define R_SPARC_TLS_DTPMOD32 74
#define R_SPARC_TLS_DTPMOD64 75
#define R_SPARC_TLS_DTPOFF32 76
#define R_SPARC_TLS_DTPOFF64 77
#define R_SPARC_TLS_TPOFF32 78
#define R_SPARC_TLS_TPOFF64 79
#define R_X86_64_NONE 0 /* No relocation. */
#define R_X86_64_64 1 /* Add 64 bit symbol value. */
#define R_X86_64_PC32 2 /* PC-relative 32 bit signed sym value. */
#define R_X86_64_GOT32 3 /* PC-relative 32 bit GOT offset. */
#define R_X86_64_PLT32 4 /* PC-relative 32 bit PLT offset. */
#define R_X86_64_COPY 5 /* Copy data from shared object. */
#define R_X86_64_GLOB_DAT 6 /* Set GOT entry to data address. */
#define R_X86_64_JMP_SLOT 7 /* Set GOT entry to code address. */
#define R_X86_64_RELATIVE 8 /* Add load address of shared object. */
#define R_X86_64_GOTPCREL 9 /* Add 32 bit signed pcrel offset to GOT. */
#define R_X86_64_32 10 /* Add 32 bit zero extended symbol value */
#define R_X86_64_32S 11 /* Add 32 bit sign extended symbol value */
#define R_X86_64_16 12 /* Add 16 bit zero extended symbol value */
#define R_X86_64_PC16 13 /* Add 16 bit signed extended pc relative symbol value */
#define R_X86_64_8 14 /* Add 8 bit zero extended symbol value */
#define R_X86_64_PC8 15 /* Add 8 bit signed extended pc relative symbol value */
#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */
#define R_X86_64_DTPOFF64 17 /* Offset in TLS block */
#define R_X86_64_TPOFF64 18 /* Offset in static TLS block */
#define R_X86_64_TLSGD 19 /* PC relative offset to GD GOT entry */
#define R_X86_64_TLSLD 20 /* PC relative offset to LD GOT entry */
#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */
#define R_X86_64_GOTTPOFF 22 /* PC relative offset to IE GOT entry */
#define R_X86_64_TPOFF32 23 /* Offset in static TLS block */
#define R_X86_64_IRELATIVE 37
#define NT_GNU_BUILD_ID 3 /* Note type for .note.gnu.build-id */
#endif /* !_SYS_ELF_COMMON_H_ */
================================================
FILE: src/filepath.c
================================================
#include
#include
#include
#include
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include
#endif
#include "types.h"
#include "filepath.h"
void os_strncpy(oschar_t *dst, const char *src, size_t size) {
#ifdef _WIN32
MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size);
#else
strncpy(dst, src, size);
#endif
}
void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size) {
#ifdef _WIN32
WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, size, NULL, NULL);
#else
strncpy(dst, src, size);
#endif
}
int os_makedir(const oschar_t *dir) {
#ifdef _WIN32
return _wmkdir(dir);
#else
return mkdir(dir, 0777);
#endif
}
int os_rmdir(const oschar_t *dir) {
#ifdef _WIN32
return _wrmdir(dir);
#else
return remove(dir);
#endif
}
void filepath_update(filepath_t *fpath) {
memset(fpath->os_path, 0, MAX_SWITCHPATH * sizeof(oschar_t));
os_strncpy(fpath->os_path, fpath->char_path, MAX_SWITCHPATH);
}
void filepath_init(filepath_t *fpath) {
fpath->valid = VALIDITY_INVALID;
}
void filepath_copy(filepath_t *fpath, filepath_t *copy) {
if (copy != NULL && copy->valid == VALIDITY_VALID)
memcpy(fpath, copy, sizeof(filepath_t));
else
memset(fpath, 0, sizeof(filepath_t));
}
void filepath_os_append(filepath_t *fpath, oschar_t *path) {
char tmppath[MAX_SWITCHPATH];
if (fpath->valid == VALIDITY_INVALID)
return;
memset(tmppath, 0, MAX_SWITCHPATH);
os_strncpy_to_char(tmppath, path, MAX_SWITCHPATH);
strcat(fpath->char_path, OS_PATH_SEPARATOR);
strcat(fpath->char_path, tmppath);
filepath_update(fpath);
}
void filepath_append(filepath_t *fpath, const char *format, ...) {
char tmppath[MAX_SWITCHPATH];
va_list args;
if (fpath->valid == VALIDITY_INVALID)
return;
memset(tmppath, 0, MAX_SWITCHPATH);
va_start(args, format);
vsnprintf(tmppath, sizeof(tmppath), format, args);
va_end(args);
strcat(fpath->char_path, OS_PATH_SEPARATOR);
strcat(fpath->char_path, tmppath);
filepath_update(fpath);
}
void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...) {
char tmppath[MAX_SWITCHPATH];
va_list args;
if (fpath->valid == VALIDITY_INVALID || n > MAX_SWITCHPATH)
return;
memset(tmppath, 0, MAX_SWITCHPATH);
va_start(args, format);
vsnprintf(tmppath, sizeof(tmppath), format, args);
va_end(args);
strcat(fpath->char_path, OS_PATH_SEPARATOR);
strncat(fpath->char_path, tmppath, n);
filepath_update(fpath);
}
void filepath_set(filepath_t *fpath, const char *path) {
if (strlen(path) < MAX_SWITCHPATH) {
fpath->valid = VALIDITY_VALID;
memset(fpath->char_path, 0, MAX_SWITCHPATH);
strncpy(fpath->char_path, path, MAX_SWITCHPATH);
filepath_update(fpath);
} else {
fpath->valid = VALIDITY_INVALID;
}
}
oschar_t *filepath_get(filepath_t *fpath) {
if (fpath->valid == VALIDITY_INVALID)
return NULL;
else
return fpath->os_path;
}
================================================
FILE: src/filepath.h
================================================
#pragma once
#include "types.h"
#include
#ifdef _WIN32
#include
#include
#endif
#define MAX_SWITCHPATH 0x300
typedef enum {
VALIDITY_UNCHECKED = 0,
VALIDITY_INVALID,
VALIDITY_VALID
} validity_t;
#ifdef _MSC_VER
inline int fseeko64(FILE *__stream, long long __off, int __whence)
{
return _fseeki64(__stream, __off, __whence);
}
#else
/* off_t is 64-bit with large file support */
#define fseeko64 fseek
#endif
#ifdef _WIN32
typedef wchar_t oschar_t; /* utf-16 */
typedef _WDIR osdir_t;
typedef struct _wdirent osdirent_t;
typedef struct _stati64 os_stat64_t;
#define os_fopen _wfopen
#define os_opendir _wopendir
#define os_closedir _wclosedir
#define os_readdir _wreaddir
#define os_stat _wstati64
#define os_fclose fclose
#define OS_MODE_READ L"rb"
#define OS_MODE_WRITE L"wb"
#define OS_MODE_EDIT L"rb+"
#else
typedef char oschar_t; /* utf-8 */
typedef DIR osdir_t;
typedef struct dirent osdirent_t;
typedef struct stat os_stat64_t;
#define os_fopen fopen
#define os_opendir opendir
#define os_closedir closedir
#define os_readdir readdir
#define os_stat stat
#define os_fclose fclose
#define OS_MODE_READ "rb"
#define OS_MODE_WRITE "wb"
#define OS_MODE_EDIT "rb+"
#endif
#define OS_PATH_SEPARATOR "/"
typedef struct filepath {
char char_path[MAX_SWITCHPATH];
oschar_t os_path[MAX_SWITCHPATH];
validity_t valid;
} filepath_t;
void os_strncpy(oschar_t *dst, const char *src, size_t size);
void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size);
int os_makedir(const oschar_t *dir);
int os_rmdir(const oschar_t *dir);
void filepath_init(filepath_t *fpath);
void filepath_copy(filepath_t *fpath, filepath_t *copy);
void filepath_os_append(filepath_t *fpath, oschar_t *path);
void filepath_append(filepath_t *fpath, const char *format, ...);
void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...);
void filepath_set(filepath_t *fpath, const char *path);
oschar_t *filepath_get(filepath_t *fpath);
================================================
FILE: src/nacptool.c
================================================
#include
#include
#include
#include
#include
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint8_t u8;
typedef struct {
char name[0x200];
char author[0x100];
} NacpLanguageEntry;
typedef struct {
NacpLanguageEntry lang[12];
NacpLanguageEntry lang_unk[4];//?
u8 x3000_unk[0x24];////Normally all-zero?
u32 x3024_unk;
u32 x3028_unk;
u32 x302C_unk;
u32 x3030_unk;
u32 x3034_unk;
u64 titleid0;
u8 x3040_unk[0x20];
char version[0x10];
u64 titleid_dlcbase;
u64 titleid1;
u32 x3080_unk;
u32 x3084_unk;
u32 x3088_unk;
u8 x308C_unk[0x24];//zeros?
u64 titleid2;
u64 titleids[7];//"Array of application titleIDs, normally the same as the above app-titleIDs. Only set for game-updates?"
u32 x30F0_unk;
u32 x30F4_unk;
u64 titleid3;//"Application titleID. Only set for game-updates?"
char bcat_passphrase[0x40];
u8 x3140_unk[0xEC0];//Normally all-zero?
} NacpStruct;
int main(int argc, char* argv[]) {
if (argc < 6 || strncmp(argv[1], "--create", 8)!=0) {
fprintf(stderr, "%s --create [options]\n\n", argv[0]);
fprintf(stderr, "FLAGS:\n");
fprintf(stderr, "--create : Create control.nacp for use with Switch homebrew applications.\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, "--titleid= Set the application titleID.\n");
return EXIT_FAILURE;
}
NacpStruct nacp;
memset(&nacp, 0, sizeof(nacp));
if (sizeof(NacpStruct) != 0x4000) {
fprintf(stderr, "Bad compile environment!\n");
return EXIT_FAILURE;
}
char *name = argv[2];
char *author = argv[3];
char *names[12];
char *authors[12];
int i;
for (i=0; i<12; i++) {
names[i] = name;
authors[i] = author;
}
int argi;
u64 titleid=0;
for (argi=6; argi
#include
#include
#include
#include
#include
#include "cJSON.h"
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
#define MAGIC_META 0x4154454D
#define MAGIC_ACID 0x44494341
#define MAGIC_ACI0 0x30494341
/* FAC, FAH need to be tightly packed. */
#pragma pack(push, 1)
typedef struct {
u8 Version;
u8 CoiCount;
u8 SdoiCount;
u8 pad;
u64 Perms;
u64 CoiMin;
u64 CoiMax;
u64 SdoiMin;
u64 SdoiMax;
} FilesystemAccessControl;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct {
u32 Version;
u64 Perms;
u32 CoiOffset;
u32 CoiSize;
u32 SdoiOffset;
u32 SdoiSize;
} FilesystemAccessHeader;
#pragma pack(pop)
typedef struct {
u32 Magic;
u8 _0x4[0xC];
u64 ProgramId;
u64 _0x18;
u32 FahOffset;
u32 FahSize;
u32 SacOffset;
u32 SacSize;
u32 KacOffset;
u32 KacSize;
u64 Padding;
} NpdmAci0;
typedef struct {
u8 Signature[0x100];
u8 Modulus[0x100];
u32 Magic;
u32 Size;
u32 _0x208;
u32 Flags;
u64 ProgramIdRangeMin;
u64 ProgramIdRangeMax;
u32 FacOffset;
u32 FacSize;
u32 SacOffset;
u32 SacSize;
u32 KacOffset;
u32 KacSize;
u64 Padding;
} NpdmAcid;
typedef struct {
u32 Magic;
u32 SignatureKeyGeneration;
u32 _0x8;
u8 MmuFlags;
u8 _0xD;
u8 MainThreadPriority;
u8 DefaultCpuId;
u32 _0x10;
u32 SystemResourceSize;
u32 Version;
u32 MainThreadStackSize;
char Name[0x10];
char ProductCode[0x10];
u8 _0x40[0x30];
u32 Aci0Offset;
u32 Aci0Size;
u32 AcidOffset;
u32 AcidSize;
} NpdmHeader;
uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
FILE* fd = fopen(fn, "rb");
if (fd == NULL)
return NULL;
fseek(fd, 0, SEEK_END);
size_t len = ftell(fd);
fseek(fd, 0, SEEK_SET);
uint8_t* buf = malloc(len);
if (buf == NULL) {
fclose(fd);
return NULL;
}
size_t rc = fread(buf, 1, len, fd);
if (rc != len) {
fclose(fd);
free(buf);
return NULL;
}
*len_out = len;
return buf;
}
int cJSON_GetString(const cJSON *obj, const char *field, const char **out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config)) {
*out = config->valuestring;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsNumber(config)) {
*out = (u8)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsNumber(config)) {
*out = (u16)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
if (cJSON_IsNumber(config)) {
*out = (u16)config->valueint;
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
return 0;
}
}
int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsBool(config)) {
if (cJSON_IsTrue(config)) {
*out = 1;
} else if (cJSON_IsFalse(config)) {
*out = 0;
} else {
fprintf(stderr, "Unknown boolean value in %s.\n", field);
return 0;
}
return 1;
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsBool(config)) {
if (cJSON_IsTrue(config)) {
*out = 1;
} else if (cJSON_IsFalse(config)) {
*out = 0;
} else {
fprintf(stderr, "Unknown boolean value in %s.\n", field);
return 0;
}
} else {
*out = 0;
}
return 1;
}
int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoull(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", field);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", field);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", field);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoul(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", field);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", field);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", field);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", field);
return 0;
}
}
int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
if (cJSON_IsString(config) && (config->valuestring != NULL)) {
char *endptr = NULL;
*out = strtoull(config->valuestring, &endptr, 16);
if (config->valuestring == endptr) {
fprintf(stderr, "Failed to get %s (empty string)\n", config->string);
return 0;
} else if (errno == ERANGE) {
fprintf(stderr, "Failed to get %s (value out of range)\n", config->string);
return 0;
} else if (errno == EINVAL) {
fprintf(stderr, "Failed to get %s (not base16 string)\n", config->string);
return 0;
} else if (errno) {
fprintf(stderr, "Failed to get %s (unknown error)\n", config->string);
return 0;
} else {
return 1;
}
} else {
fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
return 0;
}
}
int CreateNpdm(const char *json, void **dst, u32 *dst_size) {
NpdmHeader header = {0};
NpdmAci0 *aci0 = calloc(1, 0x100000);
NpdmAcid *acid = calloc(1, 0x100000);
if (aci0 == NULL || acid == NULL) {
fprintf(stderr, "Failed to allocate NPDM resources!\n");
exit(EXIT_FAILURE);
}
const cJSON *capability = NULL;
const cJSON *capabilities = NULL;
const cJSON *service = NULL;
const cJSON *services = NULL;
const cJSON *fsaccess = NULL;
const cJSON *cois = NULL;
const cJSON *coi = NULL;
const cJSON *sdois = NULL;
const cJSON *sdoi = NULL;
int status = 0;
cJSON *npdm_json = cJSON_Parse(json);
if (npdm_json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "JSON Parse Error: %s\n", error_ptr);
}
status = 0;
goto NPDM_BUILD_END;
}
/* Initialize default NPDM values. */
header.Magic = MAGIC_META; /* "META" */
/* Parse name. */
const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, "name");
if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {
strncpy(header.Name, title_name->valuestring, sizeof(header.Name) - 1);
} else {
fprintf(stderr, "Failed to get title name (name field not present).\n");
status = 0;
goto NPDM_BUILD_END;
}
/* Parse main_thread_stack_size. */
u64 stack_size = 0;
if (!cJSON_GetU64(npdm_json, "main_thread_stack_size", &stack_size)) {
status = 0;
goto NPDM_BUILD_END;
}
if (stack_size >> 32) {
fprintf(stderr, "Error: Main thread stack size must be a u32!\n");
status = 0;
goto NPDM_BUILD_END;
}
header.MainThreadStackSize = (u32)(stack_size & 0xFFFFFFFF);
/* Parse various config. */
if (!cJSON_GetU8(npdm_json, "main_thread_priority", &header.MainThreadPriority)) {
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_GetU8(npdm_json, "default_cpu_id", &header.DefaultCpuId)) {
status = 0;
goto NPDM_BUILD_END;
}
cJSON_GetU32(npdm_json, "system_resource_size", &header.SystemResourceSize); // optional
/* Get version (deprecated name "process_category"). */
if (!cJSON_GetU32(npdm_json, "version", &header.Version) && !cJSON_GetU32(npdm_json, "process_category", &header.Version)) { // optional
header.Version = 0;
}
if (!cJSON_GetU8(npdm_json, "address_space_type", (u8 *)&header.MmuFlags)) {
status = 0;
goto NPDM_BUILD_END;
}
header.MmuFlags &= 3;
header.MmuFlags <<= 1;
int is_64_bit;
if (!cJSON_GetBoolean(npdm_json, "is_64_bit", &is_64_bit)) {
status = 0;
goto NPDM_BUILD_END;
}
header.MmuFlags |= is_64_bit;
int optimize_memory_allocation; // optional
if (cJSON_GetBoolean(npdm_json, "optimize_memory_allocation", &optimize_memory_allocation)) {
header.MmuFlags |= ((optimize_memory_allocation & 1) << 4);
}
int disable_device_address_space_merge; // optional
if (cJSON_GetBoolean(npdm_json, "disable_device_address_space_merge", &disable_device_address_space_merge)) {
header.MmuFlags |= ((disable_device_address_space_merge & 1) << 5);
}
int enable_alias_region_extra_size; // optional
if (cJSON_GetBoolean(npdm_json, "enable_alias_region_extra_size", &enable_alias_region_extra_size)) {
header.MmuFlags |= ((enable_alias_region_extra_size & 1) << 6);
}
int prevent_code_reads; // optional
if (cJSON_GetBoolean(npdm_json, "prevent_code_reads", &prevent_code_reads)) {
header.MmuFlags |= ((prevent_code_reads & 1) << 7);
}
u8 signature_key_generation; // optional
if (cJSON_GetU8(npdm_json, "signature_key_generation", &signature_key_generation)) {
header.SignatureKeyGeneration = signature_key_generation;
} else {
header.SignatureKeyGeneration = 0;
}
/* ACID. */
memset(acid->Signature, 0, sizeof(acid->Signature));
memset(acid->Modulus, 0, sizeof(acid->Modulus));
acid->Magic = MAGIC_ACID; /* "ACID" */
int is_retail;
if (!cJSON_GetBoolean(npdm_json, "is_retail", &is_retail)) {
status = 0;
goto NPDM_BUILD_END;
}
acid->Flags |= is_retail;
u8 pool_partition;
if (!cJSON_GetU8(npdm_json, "pool_partition", &pool_partition)) {
status = 0;
goto NPDM_BUILD_END;
}
acid->Flags |= (pool_partition & 3) << 2;
if (!cJSON_GetU64(npdm_json, "program_id_range_min", &acid->ProgramIdRangeMin) && !cJSON_GetU64(npdm_json, "title_id_range_min", &acid->ProgramIdRangeMin)) {
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_GetU64(npdm_json, "program_id_range_max", &acid->ProgramIdRangeMax) && !cJSON_GetU64(npdm_json, "title_id_range_max", &acid->ProgramIdRangeMax)) {
status = 0;
goto NPDM_BUILD_END;
}
/* ACI0. */
aci0->Magic = MAGIC_ACI0; /* "ACI0" */
/* Parse program_id (or deprecated title_id). */
if (!cJSON_GetU64(npdm_json, "program_id", &aci0->ProgramId) && !cJSON_GetU64(npdm_json, "title_id", &aci0->ProgramId)) {
status = 0;
goto NPDM_BUILD_END;
}
/* Fac. */
fsaccess = cJSON_GetObjectItemCaseSensitive(npdm_json, "filesystem_access");
if (!cJSON_IsObject(fsaccess)) {
fprintf(stderr, "Filesystem Access must be an object!\n");
status = 0;
goto NPDM_BUILD_END;
}
FilesystemAccessControl *fac = (FilesystemAccessControl *)((u8 *)acid + sizeof(NpdmAcid));
fac->Version = 1;
if (!cJSON_GetU64(fsaccess, "permissions", &fac->Perms)) {
status = 0;
goto NPDM_BUILD_END;
}
fac->CoiMin = 0;
fac->CoiMax = 0;
fac->SdoiMin = 0;
fac->SdoiMax = 0;
fac->CoiCount = 0;
fac->SdoiCount = 0;
acid->FacOffset = sizeof(NpdmAcid);
acid->FacSize = sizeof(FilesystemAccessControl);
acid->SacOffset = (acid->FacOffset + acid->FacSize + 0xF) & ~0xF;
/* Fah. */
FilesystemAccessHeader *fah = (FilesystemAccessHeader *)((u8 *)aci0 + sizeof(NpdmAci0));
fah->Version = 1;
fah->Perms = fac->Perms;
fah->CoiOffset = sizeof(FilesystemAccessHeader);
fah->CoiSize = 0;
cois = cJSON_GetObjectItemCaseSensitive(fsaccess, "content_owner_ids");
if (cJSON_IsArray(cois)) {
u32 *count = (u32 *)((u8 *)fah + fah->CoiOffset);
u64 *id = (u64 *)((u8 *)count + sizeof(u32));
cJSON_ArrayForEach(coi, cois) {
if (!cJSON_GetU64FromObjectValue(coi, id)) {
status = 0;
goto NPDM_BUILD_END;
}
++id;
++(*count);
}
if (*count > 0) {
fah->CoiSize = sizeof(u32) + sizeof(u64) * (*count);
}
}
fah->SdoiOffset = fah->CoiOffset + fah->CoiSize;
fah->SdoiSize = 0;
sdois = cJSON_GetObjectItemCaseSensitive(fsaccess, "save_data_owner_ids");
if (cJSON_IsArray(sdois)) {
u32 *count = (u32 *)((u8 *)fah + fah->SdoiOffset);
cJSON_ArrayForEach(sdoi, sdois) {
if (!cJSON_IsObject(sdoi)) {
status = 0;
goto NPDM_BUILD_END;
}
++(*count);
}
u8 *accessibility = (u8 *)count + sizeof(u32);
u64 *id = (u64 *)(accessibility + (((*count) + 3ULL) & ~3ULL));
cJSON_ArrayForEach(sdoi, sdois) {
if (!cJSON_GetU8(sdoi, "accessibility", accessibility)) {
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_GetU64(sdoi, "id", id)) {
status = 0;
goto NPDM_BUILD_END;
}
++accessibility;
++id;
}
if (*count > 0) {
fah->SdoiSize = sizeof(u32) + sizeof(u8) * ((((*count) + 3ULL) & ~3ULL)) + sizeof(u64) * (*count);
}
}
aci0->FahOffset = sizeof(NpdmAci0);
aci0->FahSize = sizeof(FilesystemAccessHeader) + fah->CoiSize + fah->SdoiSize;
aci0->SacOffset = (aci0->FahOffset + aci0->FahSize + 0xF) & ~0xF;
/* Sac. */
u8 *sac = (u8*)aci0 + aci0->SacOffset;
u32 sac_size = 0;
services = cJSON_GetObjectItemCaseSensitive(npdm_json, "service_host");
if (services != NULL && !cJSON_IsArray(services)) {
fprintf(stderr, "Service Host must be an array!\n");
status = 0;
goto NPDM_BUILD_END;
}
cJSON_ArrayForEach(service, services) {
int is_host = 1;
char *service_name;
if (!cJSON_IsString(service)) {
fprintf(stderr, "service_access must be an array of string\n");
status = 0;
goto NPDM_BUILD_END;
}
service_name = service->valuestring;
int cur_srv_len = strlen(service_name);
if (cur_srv_len > 8 || cur_srv_len == 0) {
fprintf(stderr, "Services must have name length 1 <= len <= 8!\n");
status = 0;
goto NPDM_BUILD_END;
}
u8 ctrl = (u8)(cur_srv_len - 1);
if (is_host) {
ctrl |= 0x80;
}
sac[sac_size++] = ctrl;
memcpy(sac + sac_size, service_name, cur_srv_len);
sac_size += cur_srv_len;
}
services = cJSON_GetObjectItemCaseSensitive(npdm_json, "service_access");
if (!(services == NULL || cJSON_IsObject(services) || cJSON_IsArray(services))) {
fprintf(stderr, "Service Access must be an array!\n");
status = 0;
goto NPDM_BUILD_END;
}
int sac_obj = 0;
if (services != NULL && cJSON_IsObject(services)) {
sac_obj = 1;
fprintf(stderr, "Using deprecated service_access format. Please turn it into an array.\n");
}
cJSON_ArrayForEach(service, services) {
int is_host = 0;
char *service_name;
if (sac_obj) {
if (!cJSON_IsBool(service)) {
fprintf(stderr, "Services must be of form service_name (str) : is_host (bool)\n");
status = 0;
goto NPDM_BUILD_END;
}
is_host = cJSON_IsTrue(service);
service_name = service->string;
} else {
if (!cJSON_IsString(service)) {
fprintf(stderr, "service_access must be an array of string\n");
status = 0;
goto NPDM_BUILD_END;
}
is_host = 0;
service_name = service->valuestring;
}
int cur_srv_len = strlen(service_name);
if (cur_srv_len > 8 || cur_srv_len == 0) {
fprintf(stderr, "Services must have name length 1 <= len <= 8!\n");
status = 0;
goto NPDM_BUILD_END;
}
u8 ctrl = (u8)(cur_srv_len - 1);
if (is_host) {
ctrl |= 0x80;
}
sac[sac_size++] = ctrl;
memcpy(sac + sac_size, service_name, cur_srv_len);
sac_size += cur_srv_len;
}
memcpy((u8 *)acid + acid->SacOffset, sac, sac_size);
aci0->SacSize = sac_size;
acid->SacSize = sac_size;
aci0->KacOffset = (aci0->SacOffset + aci0->SacSize + 0xF) & ~0xF;
acid->KacOffset = (acid->SacOffset + acid->SacSize + 0xF) & ~0xF;
/* Parse capabilities. */
capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, "kernel_capabilities");
if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {
fprintf(stderr, "Kernel Capabilities must be an array!\n");
status = 0;
goto NPDM_BUILD_END;
}
int kac_obj = 0;
if (cJSON_IsObject(capabilities)) {
kac_obj = 1;
fprintf(stderr, "Using deprecated kernel_capabilities format. Please turn it into an array.\n");
}
u32 *caps = (u32 *)((u8 *)aci0 + aci0->KacOffset);
u32 cur_cap = 0;
u32 desc;
cJSON_ArrayForEach(capability, capabilities) {
desc = 0;
const char *type_str;
const cJSON *value;
if (kac_obj) {
type_str = capability->string;
value = capability;
} else {
if (!cJSON_GetString(capability, "type", &type_str)) {
status = 0;
goto NPDM_BUILD_END;
}
value = cJSON_GetObjectItemCaseSensitive(capability, "value");
}
if (!strcmp(type_str, "kernel_flags")) {
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Kernel Flags Capability value must be object!\n");
status = 0;
goto NPDM_BUILD_END;
}
u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;
if (!cJSON_GetU8(value, "highest_thread_priority", &highest_prio) ||
!cJSON_GetU8(value, "lowest_thread_priority", &lowest_prio) ||
!cJSON_GetU8(value, "highest_cpu_id", &highest_cpu) ||
!cJSON_GetU8(value, "lowest_cpu_id", &lowest_cpu)) {
status = 0;
goto NPDM_BUILD_END;
}
u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;
u8 real_lowest_prio = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;
desc = highest_cpu;
desc <<= 8;
desc |= lowest_cpu;
desc <<= 6;
desc |= (real_highest_prio & 0x3F);
desc <<= 6;
desc |= (real_lowest_prio & 0x3F);
caps[cur_cap++] = (u32)((desc << 4) | (0x0007));
} else if (!strcmp(type_str, "syscalls")) {
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Syscalls Capability value must be object!\n");
status = 0;
goto NPDM_BUILD_END;
}
u32 num_descriptors;
u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */
char field_name[8] = {0};
const cJSON *cur_syscall = NULL;
u64 syscall_value = 0;
cJSON_ArrayForEach(cur_syscall, value) {
if (cJSON_IsNumber(cur_syscall)) {
syscall_value = (u64)cur_syscall->valueint;
} else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {
fprintf(stderr, "Error: Syscall entries must be integers or hex strings.\n");
status = 0;
goto NPDM_BUILD_END;
}
if (syscall_value >= 0xC0) {
fprintf(stderr, "Error: All syscall entries must be numbers in [0, 0xBF]\n");
status = 0;
goto NPDM_BUILD_END;
}
descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));
}
for (unsigned int i = 0; i < 8; i++) {
if (descriptors[i]) {
desc = descriptors[i] | (i << 24);
caps[cur_cap++] = (u32)((desc << 5) | (0x000F));
}
}
} else if (!strcmp(type_str, "map")) {
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Map Capability value must be object!\n");
status = 0;
goto NPDM_BUILD_END;
}
u64 map_address = 0;
u64 map_size = 0;
int is_ro;
int is_io;
if (!cJSON_GetU64(value, "address", &map_address) ||
!cJSON_GetU64(value, "size", &map_size) ||
!cJSON_GetBoolean(value, "is_ro", &is_ro) ||
!cJSON_GetBoolean(value, "is_io", &is_io)) {
status = 0;
goto NPDM_BUILD_END;
}
desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);
desc |= is_ro << 24;
caps[cur_cap++] = (u32)((desc << 7) | (0x003F));
desc = (u32)((map_size >> 12) & 0x000FFFFFULL);
desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);
is_io ^= 1;
desc |= is_io << 24;
caps[cur_cap++] = (u32)((desc << 7) | (0x003F));
} else if (!strcmp(type_str, "map_page")) {
u64 page_address = 0;
if (!cJSON_GetU64FromObjectValue(value, &page_address)) {
status = 0;
goto NPDM_BUILD_END;
}
desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);
caps[cur_cap++] = (u32)((desc << 8) | (0x007F));
} else if (!strcmp(type_str, "map_region")) {
if (cur_cap + 1 > 0x20) {
fprintf(stderr, "Error: Too many capabilities!\n");
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_IsArray(value)) {
fprintf(stderr, "Map Region capability value must be array!\n");
status = 0;
goto NPDM_BUILD_END;
}
u8 regions[3] = {0};
int is_ro[3] = {0};
const cJSON *cur_region = NULL;
int index = 0;
cJSON_ArrayForEach(cur_region, value) {
if (index >= 3) {
fprintf(stderr, "Too many region descriptors!\n");
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_IsObject(cur_region)) {
fprintf(stderr, "Region descriptor value must be object!\n");
status = 0;
goto NPDM_BUILD_END;
}
if (!cJSON_GetU8(cur_region, "region_type", ®ions[index]) ||
!cJSON_GetBoolean(cur_region, "is_ro", &is_ro[index])) {
status = 0;
goto NPDM_BUILD_END;
}
index++;
}
u32 capability = 0x3FF;
for (int i = 0; i < 3; ++i) {
capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);
}
caps[cur_cap++] = capability;
} else if (!strcmp(type_str, "irq_pair")) {
if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {
fprintf(stderr, "Error: IRQ Pairs must have size 2 array value.\n");
status = 0;
goto NPDM_BUILD_END;
}
const cJSON *irq = NULL;
int desc_idx = 0;
cJSON_ArrayForEach(irq, value) {
if (cJSON_IsNull(irq)) {
desc |= 0x3FF << desc_idx;
} else if (cJSON_IsNumber(irq)) {
desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;
} else {
fprintf(stderr, "Failed to parse IRQ value.\n");
status = 0;
goto NPDM_BUILD_END;
}
desc_idx += 10;
}
caps[cur_cap++] = (u32)((desc << 12) | (0x07FF));
} else if (!strcmp(type_str, "application_type")) {
if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
status = 0;
goto NPDM_BUILD_END;
}
desc &= 7;
caps[cur_cap++] = (u32)((desc << 14) | (0x1FFF));
} else if (!strcmp(type_str, "min_kernel_version")) {
u64 kern_ver = 0;
if (cJSON_IsNumber(value)) {
kern_ver = (u64)value->valueint;
} else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {
fprintf(stderr, "Error: Kernel version must be integer or hex strings.\n");
status = 0;
goto NPDM_BUILD_END;
}
desc = (kern_ver) & 0xFFFF;
caps[cur_cap++] = (u32)((desc << 15) | (0x3FFF));
} else if (!strcmp(type_str, "handle_table_size")) {
if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
status = 0;
goto NPDM_BUILD_END;
}
caps[cur_cap++] = (u32)((desc << 16) | (0x7FFF));
} else if (!strcmp(type_str, "debug_flags")) {
if (!cJSON_IsObject(value)) {
fprintf(stderr, "Debug Flag Capability value must be object!\n");
status = 0;
goto NPDM_BUILD_END;
}
int allow_debug = 0;
int force_debug = 0;
int force_debug_prod = 0;
cJSON_GetBoolean(value, "allow_debug", &allow_debug);
cJSON_GetBoolean(value, "force_debug", &force_debug);
cJSON_GetBoolean(value, "force_debug_prod", &force_debug_prod);
if ( allow_debug + force_debug + force_debug_prod > 1 ) {
fprintf(stderr, "Only one of allow_debug, force_debug, or force_debug_prod can be set!\n");
status = 0;
goto NPDM_BUILD_END;
}
desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);
caps[cur_cap++] = (u32)((desc << 17) | (0xFFFF));
}
}
aci0->KacSize = cur_cap * sizeof(u32);
acid->KacSize = aci0->KacSize;
memcpy((u8 *)acid + acid->KacOffset, caps, aci0->KacSize);
header.AcidOffset = sizeof(header);
header.AcidSize = acid->KacOffset + acid->KacSize;
acid->Size = header.AcidSize - sizeof(acid->Signature);
header.Aci0Offset = (header.AcidOffset + header.AcidSize + 0xF) & ~0xF;
header.Aci0Size = aci0->KacOffset + aci0->KacSize;
u32 total_size = header.Aci0Offset + header.Aci0Size;
u8 *npdm = calloc(1, total_size);
if (npdm == NULL) {
fprintf(stderr, "Failed to allocate output!\n");
exit(EXIT_FAILURE);
}
memcpy(npdm, &header, sizeof(header));
memcpy(npdm + header.AcidOffset, acid, header.AcidSize);
memcpy(npdm + header.Aci0Offset, aci0, header.Aci0Size);
free(acid);
free(aci0);
*dst = npdm;
*dst_size = total_size;
status = 1;
NPDM_BUILD_END:
cJSON_Delete(npdm_json);
return status;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "%s \n", argv[0]);
return EXIT_FAILURE;
}
void *npdm;
u32 npdm_size;
if (sizeof(NpdmHeader) != 0x80 || sizeof(NpdmAcid) != 0x240 || sizeof(NpdmAci0) != 0x40) {
fprintf(stderr, "Bad compile environment!\n");
return EXIT_FAILURE;
}
size_t json_len;
uint8_t* json = ReadEntireFile(argv[1], &json_len);
if (json == NULL) {
fprintf(stderr, "Failed to read descriptor json!\n");
return EXIT_FAILURE;
}
if (!CreateNpdm(json, &npdm, &npdm_size)) {
fprintf(stderr, "Failed to parse descriptor json!\n");
return EXIT_FAILURE;
}
FILE *f_out = fopen(argv[2], "wb");
if (f_out == NULL) {
fprintf(stderr, "Failed to open %s for writing!\n", argv[2]);
return EXIT_FAILURE;
}
if (fwrite(npdm, 1, npdm_size, f_out) != npdm_size) {
fprintf(stderr, "Failed to write NPDM to %s!\n", argv[2]);
return EXIT_FAILURE;
}
fclose(f_out);
free(npdm);
return EXIT_SUCCESS;
}
================================================
FILE: src/nxlink.c
================================================
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifndef __WIN32__
#include
#include
#include
#include
#include
#define closesocket close
#else
#include
#include
typedef int socklen_t;
typedef uint32_t in_addr_t;
#define SHUT_RD SD_RECEIVE
#define SHUT_WR SD_SEND
#define SHUT_RDWR SD_BOTH
#ifdef EWOULDBLOCK
#undef EWOULDBLOCK
#endif
#define EWOULDBLOCK WSAEWOULDBLOCK
#define poll WSAPoll
#endif
#include
#include
#define ZLIB_CHUNK (16 * 1024)
#define NETLOADER_SERVER_PORT 28280
#define NETLOADER_CLIENT_PORT 28771
static char cmdbuf[3072];
static uint32_t cmdlen=0;
//---------------------------------------------------------------------------------
static void shutdownSocket(int socket, int flags) {
//---------------------------------------------------------------------------------
if (flags)
shutdown(socket, flags);
closesocket(socket);
}
//---------------------------------------------------------------------------------
static int setSocketNonblocking(int sock) {
//---------------------------------------------------------------------------------
#ifndef __WIN32__
int flags = fcntl(sock, F_GETFL);
if (flags == -1) return -1;
int rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
if (rc != 0) return -1;
#else
u_long iMode = 1; // non-blocking
int rc = ioctlsocket(sock, FIONBIO, &iMode);
if (rc != NO_ERROR) return -1;
#endif
return 0;
}
//---------------------------------------------------------------------------------
static int socketError(const char *msg) {
//---------------------------------------------------------------------------------
#ifndef _WIN32
int ret = errno;
if (ret == EAGAIN)
ret = EWOULDBLOCK;
perror(msg);
#else
int ret = WSAGetLastError();
wchar_t *s = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ret,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&s, 0, NULL);
fprintf(stderr, "%S\n", s);
LocalFree(s);
if (ret == WSAEWOULDBLOCK)
ret = EWOULDBLOCK;
#endif
return ret;
}
//---------------------------------------------------------------------------------
int pollSocket(int fd, int events, int timeout) {
//---------------------------------------------------------------------------------
#ifndef __WIN32__
struct pollfd pfd;
#else
WSAPOLLFD pfd;
#endif
pfd.fd = fd;
pfd.events = events;
pfd.revents = 0;
int ret = poll(&pfd, 1, timeout);
if (ret < 0) {
socketError("poll");
return -1;
}
if (ret == 0)
return -1;
if (!(pfd.revents & events)) {
int err = 0;
int len = sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len);
fprintf(stderr, "socket error 0x%x on poll\n", err);
return -1;
}
return 0;
}
//---------------------------------------------------------------------------------
static struct in_addr findSwitch(int retries) {
//---------------------------------------------------------------------------------
printf("pinging switch\n");
struct sockaddr_in s, remote, rs;
char recvbuf[256];
char mess[] = "nxboot";
int broadcastSock = socket(PF_INET, SOCK_DGRAM, 0);
if (broadcastSock < 0) socketError("create send socket");
int optval = 1, len;
setsockopt(broadcastSock, SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval));
memset(&s, '\0', sizeof(struct sockaddr_in));
s.sin_family = AF_INET;
s.sin_port = htons(NETLOADER_SERVER_PORT);
s.sin_addr.s_addr = INADDR_BROADCAST;
memset(&rs, '\0', sizeof(struct sockaddr_in));
rs.sin_family = AF_INET;
rs.sin_port = htons(NETLOADER_CLIENT_PORT);
rs.sin_addr.s_addr = INADDR_ANY;
int recvSock = socket(PF_INET, SOCK_DGRAM, 0);
if (recvSock < 0) socketError("create receive socket");
if (bind(recvSock, (struct sockaddr*) &rs, sizeof(rs)) < 0) socketError("bind receive socket");
setSocketNonblocking(recvSock);
while (retries) {
if (sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(s)) < 0)
socketError("sendto");
if (pollSocket(recvSock, POLLIN, 150) == 0) {
socklen_t socklen = sizeof(remote);
len = recvfrom(recvSock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&remote, &socklen);
if (len != -1) {
if (strncmp("bootnx", recvbuf, strlen("bootnx")) == 0) {
break;
}
}
}
--retries;
}
if (retries == 0)
remote.sin_addr.s_addr = INADDR_NONE;
shutdownSocket(broadcastSock, 0);
shutdownSocket(recvSock, SHUT_RD);
return remote.sin_addr;
}
//---------------------------------------------------------------------------------
static int sendData(int sock, int sendsize, void *buffer) {
//---------------------------------------------------------------------------------
char *buf = (char*)buffer;
while (sendsize) {
if (pollSocket(sock, POLLOUT, -1))
return 1;
int len = send(sock, buf, sendsize, 0);
if (len == 0)
return 1;
if (len == -1) {
if (socketError("send") != EWOULDBLOCK)
return 1;
} else {
sendsize -= len;
buf += len;
}
}
return sendsize != 0;
}
//---------------------------------------------------------------------------------
static int recvData(int sock, void *buffer, int size, int flags) {
//---------------------------------------------------------------------------------
int len, sizeleft = size;
char *buf = (char*)buffer;
while (sizeleft) {
if (pollSocket(sock, POLLIN, -1))
return 0;
len = recv(sock,buf,sizeleft,flags);
if (len == 0)
return 0;
if (len == -1) {
if (socketError("recv") != EWOULDBLOCK)
return 0;
} else {
sizeleft -=len;
buf +=len;
}
}
return size;
}
//---------------------------------------------------------------------------------
static int sendInt32LE(int socket, uint32_t size) {
//---------------------------------------------------------------------------------
unsigned char lenbuf[4];
lenbuf[0] = size & 0xff;
lenbuf[1] = (size >> 8) & 0xff;
lenbuf[2] = (size >> 16) & 0xff;
lenbuf[3] = (size >> 24) & 0xff;
return sendData(socket, 4, lenbuf);
}
//---------------------------------------------------------------------------------
static int recvInt32LE(int socket, int32_t *data) {
//---------------------------------------------------------------------------------
unsigned char intbuf[4];
int len = recvData(socket, intbuf, 4, 0);
if (len == 4) {
*data = intbuf[0] & 0xff + (intbuf[1] << 8) + (intbuf[2] << 16) + (intbuf[3] << 24);
return 0;
}
return -1;
}
static unsigned char in[ZLIB_CHUNK];
static unsigned char out[ZLIB_CHUNK];
//---------------------------------------------------------------------------------
static int sendNROFile(in_addr_t nxaddr, char *name, size_t filesize, FILE *fh) {
//---------------------------------------------------------------------------------
int retval = 0;
int ret, flush;
unsigned have;
z_stream strm;
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
if (ret != Z_OK) return ret;
int sock = socket(AF_INET,SOCK_STREAM,0);
if (sock < 0) {
socketError("create connection socket");
return -1;
}
struct sockaddr_in s;
memset(&s, '\0', sizeof(struct sockaddr_in));
s.sin_family = AF_INET;
s.sin_port = htons(NETLOADER_SERVER_PORT);
s.sin_addr.s_addr = nxaddr;
if (connect(sock,(struct sockaddr *)&s,sizeof(s)) < 0) {
struct in_addr address;
address.s_addr = nxaddr;
fprintf(stderr,"Connection to %s failed\n",inet_ntoa(address));
return -1;
}
int namelen = strlen(name);
if (sendInt32LE(sock,namelen)) {
fprintf(stderr,"Failed sending filename length\n");
retval = -1;
goto error;
}
if (sendData(sock,namelen,name)) {
fprintf(stderr,"Failed sending filename\n");
retval = -1;
goto error;
}
if (sendInt32LE(sock,filesize)) {
fprintf(stderr,"Failed sending file length\n");
retval = -1;
goto error;
}
int response;
if (recvInt32LE(sock,&response)!=0) {
fprintf(stderr,"Invalid response\n");
retval = 1;
goto error;
}
if (response!=0) {
switch(response) {
case -1:
fprintf(stderr,"Failed to create file\n");
break;
case -2:
fprintf(stderr,"Insufficient space\n");
break;
case -3:
fprintf(stderr,"Insufficient memory\n");
break;
}
retval = 1;
goto error;
}
printf("Sending %s, %zd bytes\n",name, filesize);
size_t totalsent = 0, blocks = 0;
do {
strm.avail_in = fread(in, 1, ZLIB_CHUNK, fh);
if (ferror(fh)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(fh) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = ZLIB_CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = ZLIB_CHUNK - strm.avail_out;
if (have != 0) {
if (sendInt32LE(sock,have)) {
fprintf(stderr,"Failed sending chunk size\n");
retval = -1;
goto error;
}
if (sendData(sock,have,out)) {
fprintf(stderr,"Failed sending %s\n", name);
retval = 1;
(void)deflateEnd(&strm);
goto error;
}
totalsent += have;
blocks++;
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
/* done when last data in file processed */
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /* stream will be complete */
(void)deflateEnd(&strm);
printf("%zu sent (%.2f%%), %zd blocks\n",totalsent, (float)(totalsent * 100.0)/ filesize, blocks);
if (recvInt32LE(sock,&response)!=0) {
fprintf(stderr,"Failed sending %s\n",name);
retval = 1;
goto error;
}
if (sendData(sock,cmdlen+4,(unsigned char*)cmdbuf)) {
fprintf(stderr,"Failed sending command line\n");
retval = 1;
}
error:
shutdownSocket(sock, SHUT_WR);
return retval;
}
//---------------------------------------------------------------------------------
static void showHelp() {
//---------------------------------------------------------------------------------
puts("Usage: nxlink [options] nrofile\n");
puts("--help, -h Display this information");
puts("--address, -a Hostname or IPv4 address of Switch");
puts("--retries, -r number of times to ping before giving up");
puts("--path , -p set upload path for file");
puts("--args args to send to nro");
puts("--server , -s start server after completed upload");
puts("\n");
}
//---------------------------------------------------------------------------------
static int addExtraArgs(int len, char *buf, char *extra_args) {
//---------------------------------------------------------------------------------
if (NULL==extra_args) return len;
int extra_len = strlen(extra_args);
char *dst = &buf[len];
char *src = extra_args;
do {
int c;
do {
c = *src++;
extra_len--;
} while (c ==' ' && extra_len >= 0);
if (c == '\"' || c == '\'') {
int quote = c;
do {
c = *src++;
if (c != quote) *dst++ = c;
extra_len--;
} while (c != quote && extra_len >= 0);
*dst++ = '\0';
continue;
}
do {
*dst++ = c;
extra_len--;
c = *src++;
} while (c != ' ' && extra_len >= 0);
*dst++ = '\0';
} while (extra_len >= 0);
return dst - buf;
}
#define NRO_ARGS 1000
#ifdef __WIN32__
static void win32_socket_cleanup(void) {
WSACleanup();
}
#endif
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
char *address = NULL;
char *basepath = NULL;
char *finalpath = NULL;
char *endarg = NULL;
char *extra_args = NULL;
int retries = 10;
static int server = 0;
if (argc < 2) {
showHelp();
return EXIT_FAILURE;
}
while (1) {
static struct option long_options[] = {
{"address", required_argument, 0, 'a'},
{"retries", required_argument, 0, 'r'},
{"path", required_argument, 0, 'p'},
{"args", required_argument, 0, NRO_ARGS},
{"help", no_argument, 0, 'h'},
{"server", no_argument, &server, 1 },
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0, c;
c = getopt_long (argc, argv, "a:r:hp:s", long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch(c) {
case 'a':
address = optarg;
break;
case 'r':
errno = 0;
retries = strtoul(optarg, &endarg, 0);
if (endarg == optarg) errno = EINVAL;
if (errno != 0) {
perror("--retries");
exit(1);
}
break;
case 'p':
basepath = optarg;
break;
case 's':
server = 1;
break;
case 'h':
showHelp();
return EXIT_FAILURE;
case NRO_ARGS:
extra_args=optarg;
break;
}
}
char *filename = argv[optind++];
if (filename== NULL) {
showHelp();
return EXIT_FAILURE;
}
memset(cmdbuf, '\0', sizeof(cmdbuf));
FILE *fh = fopen(filename,"rb");
if (fh == NULL) {
fprintf(stderr,"Failed to open %s\n",filename);
return EXIT_FAILURE;
}
#ifdef _WIN32
setvbuf(stdout, 0, _IONBF, 0);
#endif
fseek(fh,0,SEEK_END);
size_t filesize = ftell(fh);
fseek(fh,0,SEEK_SET);
char *basename = NULL;
if ((basename=strrchr(filename,'/'))!=NULL) {
basename++;
} else if ((basename=strrchr(filename,'\\'))!=NULL) {
basename++;
} else {
basename = filename;
}
if (basepath) {
size_t finalpath_len = strlen(basepath);
if (basepath[finalpath_len] == '/') {
finalpath_len += (strlen(basename) + 1);
finalpath = malloc(finalpath_len);
sprintf(finalpath, "%s%s", basepath, basename);
} else {
finalpath = basepath;
}
} else {
finalpath = basename;
}
cmdlen = 0;
for (int index = optind; index < argc; index++) {
int len=strlen(argv[index]);
if ((cmdlen + len + 5) >= (sizeof(cmdbuf) - 2)) break;
strcpy(&cmdbuf[cmdlen+4],argv[index]);
cmdlen+= len + 1;
}
cmdlen = addExtraArgs(cmdlen, &cmdbuf[4], extra_args);
cmdbuf[0] = cmdlen & 0xff;
cmdbuf[1] = (cmdlen>>8) & 0xff;
cmdbuf[2] = (cmdlen>>16) & 0xff;
cmdbuf[3] = (cmdlen>>24) & 0xff;
#ifdef __WIN32__
WSADATA wsa_data;
if (WSAStartup (MAKEWORD(2,2), &wsa_data)) {
printf ("WSAStartup failed\n");
return EXIT_FAILURE;
}
atexit(&win32_socket_cleanup);
#endif
struct in_addr nxaddr;
nxaddr.s_addr = INADDR_NONE;
if (address == NULL) {
nxaddr = findSwitch(retries);
if (nxaddr.s_addr == INADDR_NONE) {
printf("No response from Switch!\n");
return EXIT_FAILURE;
}
} else {
struct addrinfo *info;
if (getaddrinfo(address, NULL, NULL, &info) == 0) {
nxaddr = ((struct sockaddr_in*)info->ai_addr)->sin_addr;
freeaddrinfo(info);
}
}
if (nxaddr.s_addr == INADDR_NONE) {
fprintf(stderr,"Invalid address\n");
return EXIT_FAILURE;
}
int res = sendNROFile(nxaddr.s_addr,finalpath,filesize,fh);
fclose(fh);
if (res != 0)
return EXIT_FAILURE;
if (!server)
return EXIT_SUCCESS;
printf("starting server\n");
struct sockaddr_in serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(NETLOADER_CLIENT_PORT);
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
socketError("socket");
return EXIT_FAILURE;
}
int rc = bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if (rc != 0) {
socketError("bind listen socket");
shutdownSocket(listenfd, 0);
return EXIT_FAILURE;
}
rc = setSocketNonblocking(listenfd);
if (rc == -1) {
socketError("listen fcntl");
shutdownSocket(listenfd, 0);
return EXIT_FAILURE;
}
rc = listen(listenfd, 10);
if (rc != 0) {
socketError("listen");
shutdownSocket(listenfd, 0);
return EXIT_FAILURE;
}
printf("server active ...\n");
int datafd = -1;
while (listenfd != -1 || datafd != -1) {
struct sockaddr_in sa_remote;
if (pollSocket(listenfd >= 0 ? listenfd : datafd, POLLIN, -1))
break;
if (listenfd >= 0) {
socklen_t addrlen = sizeof(sa_remote);
datafd = accept(listenfd, (struct sockaddr*)&sa_remote, &addrlen);
if (datafd < 0 && socketError("accept") != EWOULDBLOCK)
break;
if (datafd >= 0) {
shutdownSocket(listenfd, 0);
listenfd = -1;
}
} else {
char recvbuf[256];
int len = recv(datafd, recvbuf, sizeof(recvbuf), 0);
if (len == 0 || (len < 0 && socketError("recv") != EWOULDBLOCK)) {
shutdownSocket(datafd, 0);
datafd = -1;
break;
}
if (len > 0)
fwrite(recvbuf, 1, len, stdout);
}
}
if (listenfd >= 0)
shutdownSocket(listenfd, 0);
if (datafd >= 0)
shutdownSocket(datafd, SHUT_RD);
printf("exiting ... \n");
return EXIT_SUCCESS;
}
================================================
FILE: src/romfs.c
================================================
#include
#include
#include
#include
#include
#include "types.h"
#include "romfs.h"
#include "filepath.h"
#include
#include
struct romfs_fent_ctx;
typedef struct romfs_dirent_ctx {
filepath_t sum_path;
filepath_t cur_path;
uint32_t entry_offset;
struct romfs_dirent_ctx *parent; /* Parent node */
struct romfs_dirent_ctx *child; /* Child node */
struct romfs_dirent_ctx *sibling; /* Sibling node */
struct romfs_fent_ctx *file; /* File node */
struct romfs_dirent_ctx *next; /* Next node */
} romfs_dirent_ctx_t;
typedef struct romfs_fent_ctx {
filepath_t sum_path;
filepath_t cur_path;
uint32_t entry_offset;
uint64_t offset;
uint64_t size;
romfs_dirent_ctx_t *parent; /* Parent dir */
struct romfs_fent_ctx *sibling; /* Sibling file */
struct romfs_fent_ctx *next; /* Logical next file */
} romfs_fent_ctx_t;
typedef struct {
romfs_fent_ctx_t *files;
uint64_t num_dirs;
uint64_t num_files;
uint64_t dir_table_size;
uint64_t file_table_size;
uint64_t dir_hash_table_size;
uint64_t file_hash_table_size;
uint64_t file_partition_size;
} romfs_ctx_t;
typedef struct {
uint64_t header_size;
uint64_t dir_hash_table_ofs;
uint64_t dir_hash_table_size;
uint64_t dir_table_ofs;
uint64_t dir_table_size;
uint64_t file_hash_table_ofs;
uint64_t file_hash_table_size;
uint64_t file_table_ofs;
uint64_t file_table_size;
uint64_t file_partition_ofs;
} romfs_header_t;
typedef struct {
uint32_t parent;
uint32_t sibling;
uint32_t child;
uint32_t file;
uint32_t hash;
uint32_t name_size;
char name[];
} romfs_direntry_t;
typedef struct {
uint32_t parent;
uint32_t sibling;
uint64_t offset;
uint64_t size;
uint32_t hash;
uint32_t name_size;
char name[];
} romfs_fentry_t;
#define ROMFS_ENTRY_EMPTY 0xFFFFFFFF
#define ROMFS_FILEPARTITION_OFS 0x200
romfs_direntry_t *romfs_get_direntry(romfs_direntry_t *directories, uint32_t offset) {
return (romfs_direntry_t *)((char *)directories + offset);
}
romfs_fentry_t *romfs_get_fentry(romfs_fentry_t *files, uint32_t offset) {
return (romfs_fentry_t *)((char *)files + offset);
}
uint32_t calc_path_hash(uint32_t parent, const unsigned char *path, uint32_t start, size_t path_len) {
uint32_t hash = parent ^ 123456789;
for (uint32_t i = 0; i < path_len; i++) {
hash = (hash >> 5) | (hash << 27);
hash ^= path[start + i];
}
return hash;
}
uint32_t align(uint32_t offset, uint32_t alignment) {
uint32_t mask = ~(alignment-1);
return (offset + (alignment-1)) & mask;
}
uint64_t align64(uint64_t offset, uint64_t alignment) {
uint64_t mask = ~(uint64_t)(alignment-1);
return (offset + (alignment-1)) & mask;
}
uint32_t romfs_get_hash_table_count(uint32_t num_entries) {
if (num_entries < 3) {
return 3;
} else if (num_entries < 19) {
return num_entries | 1;
}
uint32_t count = num_entries;
while (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 || count % 11 == 0 || count % 13 == 0 || count % 17 == 0) {
count++;
}
return count;
}
void romfs_visit_dir(romfs_dirent_ctx_t *parent, romfs_ctx_t *romfs_ctx) {
osdir_t *dir = NULL;
osdirent_t *cur_dirent = NULL;
romfs_dirent_ctx_t *child_dir_tree = NULL;
romfs_fent_ctx_t *child_file_tree = NULL;
romfs_dirent_ctx_t *cur_dir = NULL;
romfs_fent_ctx_t *cur_file = NULL;
filepath_t cur_path;
filepath_t cur_sum_path;
os_stat64_t cur_stats;
if ((dir = os_opendir(parent->sum_path.os_path)) == NULL) {
fprintf(stderr, "Failed to open directory %s!\n", parent->sum_path.char_path);
exit(EXIT_FAILURE);
}
while ((cur_dirent = os_readdir(dir))) {
filepath_init(&cur_path);
filepath_set(&cur_path, "");
filepath_os_append(&cur_path, cur_dirent->d_name);
if (strcmp(cur_path.char_path, "/.") == 0 || strcmp(cur_path.char_path, "/..") == 0) {
/* Special case . and .. */
continue;
}
filepath_copy(&cur_sum_path, &parent->sum_path);
filepath_os_append(&cur_sum_path, cur_dirent->d_name);
if (os_stat(cur_sum_path.os_path, &cur_stats) == -1) {
fprintf(stderr, "Failed to stat %s\n", cur_sum_path.char_path);
exit(EXIT_FAILURE);
}
if ((cur_stats.st_mode & S_IFMT) == S_IFDIR) {
/* Directory */
if ((cur_dir = calloc(1, sizeof(romfs_dirent_ctx_t))) == NULL) {
fprintf(stderr, "Failed to allocate RomFS directory context!\n");
exit(EXIT_FAILURE);
}
romfs_ctx->num_dirs++;
cur_dir->parent = parent;
filepath_copy(&cur_dir->sum_path, &cur_sum_path);
filepath_copy(&cur_dir->cur_path, &cur_path);
romfs_ctx->dir_table_size += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);
/* Ordered insertion on sibling */
if (child_dir_tree == NULL || strcmp(cur_dir->sum_path.char_path, child_dir_tree->sum_path.char_path) < 0) {
cur_dir->sibling = child_dir_tree;
child_dir_tree = cur_dir;
} else {
romfs_dirent_ctx_t *child, *prev;
prev = child_dir_tree;
child = child_dir_tree->sibling;
while (child != NULL) {
if (strcmp(cur_dir->sum_path.char_path, child->sum_path.char_path) < 0) {
break;
}
prev = child;
child = child->sibling;
}
prev->sibling = cur_dir;
cur_dir->sibling = child;
}
/* Ordered insertion on next */
romfs_dirent_ctx_t *tmp = parent->next, *tmp_prev = parent;
while (tmp != NULL) {
if (strcmp(cur_dir->sum_path.char_path, tmp->sum_path.char_path) < 0) {
break;
}
tmp_prev = tmp;
tmp = tmp->next;
}
tmp_prev->next = cur_dir;
cur_dir->next = tmp;
cur_dir = NULL;
} else if ((cur_stats.st_mode & S_IFMT) == S_IFREG) {
/* File */
if ((cur_file = calloc(1, sizeof(romfs_fent_ctx_t))) == NULL) {
fprintf(stderr, "Failed to allocate RomFS File context!\n");
exit(EXIT_FAILURE);
}
romfs_ctx->num_files++;
cur_file->parent = parent;
filepath_copy(&cur_file->sum_path, &cur_sum_path);
filepath_copy(&cur_file->cur_path, &cur_path);
cur_file->size = cur_stats.st_size;
romfs_ctx->file_table_size += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);
/* Ordered insertion on sibling */
if (child_file_tree == NULL || strcmp(cur_file->sum_path.char_path, child_file_tree->sum_path.char_path) < 0) {
cur_file->sibling = child_file_tree;
child_file_tree = cur_file;
} else {
romfs_fent_ctx_t *child, *prev;
prev = child_file_tree;
child = child_file_tree->sibling;
while (child != NULL) {
if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {
break;
}
prev = child;
child = child->sibling;
}
prev->sibling = cur_file;
cur_file->sibling = child;
}
/* Ordered insertion on next */
if (romfs_ctx->files == NULL || strcmp(cur_file->sum_path.char_path, romfs_ctx->files->sum_path.char_path) < 0) {
cur_file->next = romfs_ctx->files;
romfs_ctx->files = cur_file;
} else {
romfs_fent_ctx_t *child, *prev;
prev = romfs_ctx->files;
child = romfs_ctx->files->next;
while (child != NULL) {
if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {
break;
}
prev = child;
child = child->next;
}
prev->next = cur_file;
cur_file->next = child;
}
cur_file = NULL;
} else {
fprintf(stderr, "Invalid FS object type for %s!\n", cur_path.char_path);
exit(EXIT_FAILURE);
}
}
os_closedir(dir);
parent->child = child_dir_tree;
parent->file = child_file_tree;
cur_dir = child_dir_tree;
while (cur_dir != NULL) {
romfs_visit_dir(cur_dir, romfs_ctx);
cur_dir = cur_dir->sibling;
}
}
size_t build_romfs_into_file(filepath_t *in_dirpath, FILE *f_out, off_t base_offset) {
romfs_dirent_ctx_t *root_ctx = calloc(1, sizeof(romfs_dirent_ctx_t));
if (root_ctx == NULL) {
fprintf(stderr, "Failed to allocate root context!\n");
exit(EXIT_FAILURE);
}
root_ctx->parent = root_ctx;
romfs_ctx_t romfs_ctx;
memset(&romfs_ctx, 0, sizeof(romfs_ctx));
filepath_copy(&root_ctx->sum_path, in_dirpath);
filepath_init(&root_ctx->cur_path);
filepath_set(&root_ctx->cur_path, "");
romfs_ctx.dir_table_size = 0x18; /* Root directory. */
romfs_ctx.num_dirs = 1;
/* Visit all directories. */
printf("Visiting directories...\n");
romfs_visit_dir(root_ctx, &romfs_ctx);
uint32_t dir_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_dirs);
uint32_t file_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_files);
romfs_ctx.dir_hash_table_size = 4 * dir_hash_table_entry_count;
romfs_ctx.file_hash_table_size = 4 * file_hash_table_entry_count;
romfs_header_t header;
memset(&header, 0, sizeof(header));
romfs_fent_ctx_t *cur_file = NULL;
romfs_dirent_ctx_t *cur_dir = NULL;
uint32_t entry_offset = 0;
uint32_t *dir_hash_table = malloc(romfs_ctx.dir_hash_table_size);
if (dir_hash_table == NULL) {
fprintf(stderr, "Failed to allocate directory hash table!\n");
exit(EXIT_FAILURE);
}
for (uint32_t i = 0; i < dir_hash_table_entry_count; i++) {
dir_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);
}
uint32_t *file_hash_table = malloc(romfs_ctx.file_hash_table_size);
if (file_hash_table == NULL) {
fprintf(stderr, "Failed to allocate file hash table!\n");
exit(EXIT_FAILURE);
}
for (uint32_t i = 0; i < file_hash_table_entry_count; i++) {
file_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);
}
romfs_direntry_t *dir_table = calloc(1, romfs_ctx.dir_table_size);
if (dir_table == NULL) {
fprintf(stderr, "Failed to allocate directory table!\n");
exit(EXIT_FAILURE);
}
romfs_fentry_t *file_table = calloc(1, romfs_ctx.file_table_size);
if (file_table == NULL) {
fprintf(stderr, "Failed to allocate file table!\n");
exit(EXIT_FAILURE);
}
printf("Calculating metadata...\n");
/* Determine file offsets. */
cur_file = romfs_ctx.files;
entry_offset = 0;
while (cur_file != NULL) {
romfs_ctx.file_partition_size = align64(romfs_ctx.file_partition_size, 0x10);
cur_file->offset = romfs_ctx.file_partition_size;
romfs_ctx.file_partition_size += cur_file->size;
cur_file->entry_offset = entry_offset;
entry_offset += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);
cur_file = cur_file->next;
}
/* Determine dir offsets. */
cur_dir = root_ctx;
entry_offset = 0;
while (cur_dir != NULL) {
cur_dir->entry_offset = entry_offset;
if (cur_dir == root_ctx) {
entry_offset += 0x18;
} else {
entry_offset += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);
}
cur_dir = cur_dir->next;
}
/* Populate file tables. */
cur_file = romfs_ctx.files;
while (cur_file != NULL) {
romfs_fentry_t *cur_entry = romfs_get_fentry(file_table, cur_file->entry_offset);
cur_entry->parent = le_word(cur_file->parent->entry_offset);
cur_entry->sibling = le_word(cur_file->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset);
cur_entry->offset = le_dword(cur_file->offset);
cur_entry->size = le_dword(cur_file->size);
uint32_t name_size = strlen(cur_file->cur_path.char_path)-1;
uint32_t hash = calc_path_hash(cur_file->parent->entry_offset, (unsigned char *)cur_file->cur_path.char_path, 1, name_size);
cur_entry->hash = file_hash_table[hash % file_hash_table_entry_count];
file_hash_table[hash % file_hash_table_entry_count] = le_word(cur_file->entry_offset);
cur_entry->name_size = name_size;
memcpy(cur_entry->name, cur_file->cur_path.char_path + 1, name_size);
cur_file = cur_file->next;
}
/* Populate dir tables. */
cur_dir = root_ctx;
while (cur_dir != NULL) {
romfs_direntry_t *cur_entry = romfs_get_direntry(dir_table, cur_dir->entry_offset);
cur_entry->parent = le_word(cur_dir->parent->entry_offset);
cur_entry->sibling = le_word(cur_dir->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->sibling->entry_offset);
cur_entry->child = le_word(cur_dir->child == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->child->entry_offset);
cur_entry->file = le_word(cur_dir->file == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->file->entry_offset);
uint32_t name_size = (cur_dir == root_ctx) ? 0 : strlen(cur_dir->cur_path.char_path)-1;
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);
cur_entry->hash = dir_hash_table[hash % dir_hash_table_entry_count];
dir_hash_table[hash % dir_hash_table_entry_count] = le_word(cur_dir->entry_offset);
cur_entry->name_size = name_size;
memcpy(cur_entry->name, cur_dir->cur_path.char_path + 1, name_size);
cur_dir = cur_dir->next;
}
header.header_size = le_dword(sizeof(header));
header.file_hash_table_size = le_dword(romfs_ctx.file_hash_table_size);
header.file_table_size = le_dword(romfs_ctx.file_table_size);
header.dir_hash_table_size = le_dword(romfs_ctx.dir_hash_table_size);
header.dir_table_size = le_dword(romfs_ctx.dir_table_size);
header.file_partition_ofs = le_dword(ROMFS_FILEPARTITION_OFS);
/* Abuse of endianness follows. */
uint64_t dir_hash_table_ofs = align64(romfs_ctx.file_partition_size + ROMFS_FILEPARTITION_OFS, 4);
header.dir_hash_table_ofs = dir_hash_table_ofs;
header.dir_table_ofs = header.dir_hash_table_ofs + romfs_ctx.dir_hash_table_size;
header.file_hash_table_ofs = header.dir_table_ofs + romfs_ctx.dir_table_size;
header.file_table_ofs = header.file_hash_table_ofs + romfs_ctx.file_hash_table_size;
header.dir_hash_table_ofs = le_dword(header.dir_hash_table_ofs);
header.dir_table_ofs = le_dword(header.dir_table_ofs);
header.file_hash_table_ofs = le_dword(header.file_hash_table_ofs);
header.file_table_ofs = le_dword(header.file_table_ofs);
fseeko64(f_out, base_offset, SEEK_SET);
fwrite(&header, 1, sizeof(header), f_out);
/* Write files. */
unsigned char *buffer = malloc(0x400000);
if (buffer == NULL) {
fprintf(stderr, "Failed to allocate work buffer!\n");
exit(EXIT_FAILURE);
}
cur_file = romfs_ctx.files;
while (cur_file != NULL) {
FILE *f_in = os_fopen(cur_file->sum_path.os_path, OS_MODE_READ);
if (f_in == NULL) {
fprintf(stderr, "Failed to open %s!\n", cur_file->sum_path.char_path);
exit(EXIT_FAILURE);
}
printf("Writing %s to RomFS image...\n", cur_file->sum_path.char_path);
fseeko64(f_out, base_offset + cur_file->offset + ROMFS_FILEPARTITION_OFS, SEEK_SET);
uint64_t offset = 0;
uint64_t read_size = 0x400000;
while (offset < cur_file->size) {
if (cur_file->size - offset < read_size) {
read_size = cur_file->size - offset;
}
if (fread(buffer, 1, read_size, f_in) != read_size) {
fprintf(stderr, "Failed to read from %s!\n", cur_file->sum_path.char_path);
exit(EXIT_FAILURE);
}
if (fwrite(buffer, 1, read_size, f_out) != read_size) {
fprintf(stderr, "Failed to write to output!\n");
exit(EXIT_FAILURE);
}
offset += read_size;
}
os_fclose(f_in);
cur_file = cur_file->next;
}
free(buffer);
/* Free all files. */
cur_file = romfs_ctx.files;
while (cur_file != NULL) {
romfs_fent_ctx_t *temp = cur_file;
cur_file = cur_file->next;
free(temp);
}
romfs_ctx.files = NULL;
/* Free all directories. */
cur_dir = root_ctx;
while (cur_dir != NULL) {
romfs_dirent_ctx_t *temp = cur_dir;
cur_dir = cur_dir->next;
free(temp);
}
root_ctx = NULL;
fseeko64(f_out, base_offset + dir_hash_table_ofs, SEEK_SET);
if (fwrite(dir_hash_table, 1, romfs_ctx.dir_hash_table_size, f_out) != romfs_ctx.dir_hash_table_size) {
fprintf(stderr, "Failed to write dir hash table!\n");
exit(EXIT_FAILURE);
}
free(dir_hash_table);
if (fwrite(dir_table, 1, romfs_ctx.dir_table_size, f_out) != romfs_ctx.dir_table_size) {
fprintf(stderr, "Failed to write dir table!\n");
exit(EXIT_FAILURE);
}
free(dir_table);
if (fwrite(file_hash_table, 1, romfs_ctx.file_hash_table_size, f_out) != romfs_ctx.file_hash_table_size) {
fprintf(stderr, "Failed to write file hash table!\n");
exit(EXIT_FAILURE);
}
free(file_hash_table);
if (fwrite(file_table, 1, romfs_ctx.file_table_size, f_out) != romfs_ctx.file_table_size) {
fprintf(stderr, "Failed to write file table!\n");
exit(EXIT_FAILURE);
}
free(file_table);
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;
}
size_t build_romfs(filepath_t *in_dirpath, filepath_t *out_romfspath) {
FILE *f_out = NULL;
if ((f_out = os_fopen(out_romfspath->os_path, OS_MODE_WRITE)) == NULL) {
fprintf(stderr, "Failed to open %s!\n", out_romfspath->char_path);
exit(EXIT_FAILURE);
}
size_t sz = build_romfs_into_file(in_dirpath, f_out, 0);
fclose(f_out);
return sz;
}
size_t build_romfs_by_paths(char *dir, char *out_fn) {
filepath_t dirpath;
filepath_t outpath;
filepath_init(&dirpath);
filepath_init(&outpath);
filepath_set(&dirpath, dir);
filepath_set(&outpath, out_fn);
return build_romfs(&dirpath, &outpath);
}
size_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t offset) {
filepath_t dirpath;
filepath_init(&dirpath);
filepath_set(&dirpath, dir);
return build_romfs_into_file(&dirpath, f_out, offset);
}
================================================
FILE: src/romfs.h
================================================
#pragma once
#include "filepath.h"
size_t build_romfs_by_paths(char *dir, char *out_fn);
size_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t base_offset);
================================================
FILE: src/sha256.c
================================================
/*********************************************************************
* Filename: sha256.c
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Implementation of the SHA-256 hashing algorithm.
SHA-256 is one of the three algorithms in the SHA2
specification. The others, SHA-384 and SHA-512, are not
offered in this implementation.
Algorithm specification can be found here:
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
This implementation uses little endian byte order.
*********************************************************************/
/*************************** HEADER FILES ***************************/
#include
#include
#include "sha256.h"
/****************************** MACROS ******************************/
#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
/**************************** VARIABLES *****************************/
static const WORD k[64] = {
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
};
/*********************** FUNCTION DEFINITIONS ***********************/
void sha256_transform(SHA256_CTX *ctx, const BYTE data[])
{
WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
for (i = 0, j = 0; i < 16; ++i, j += 4)
m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);
for ( ; i < 64; ++i)
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
a = ctx->state[0];
b = ctx->state[1];
c = ctx->state[2];
d = ctx->state[3];
e = ctx->state[4];
f = ctx->state[5];
g = ctx->state[6];
h = ctx->state[7];
for (i = 0; i < 64; ++i) {
t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
t2 = EP0(a) + MAJ(a,b,c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
ctx->state[0] += a;
ctx->state[1] += b;
ctx->state[2] += c;
ctx->state[3] += d;
ctx->state[4] += e;
ctx->state[5] += f;
ctx->state[6] += g;
ctx->state[7] += h;
}
void sha256_init(SHA256_CTX *ctx)
{
ctx->datalen = 0;
ctx->bitlen = 0;
ctx->state[0] = 0x6a09e667;
ctx->state[1] = 0xbb67ae85;
ctx->state[2] = 0x3c6ef372;
ctx->state[3] = 0xa54ff53a;
ctx->state[4] = 0x510e527f;
ctx->state[5] = 0x9b05688c;
ctx->state[6] = 0x1f83d9ab;
ctx->state[7] = 0x5be0cd19;
}
void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len)
{
WORD i;
for (i = 0; i < len; ++i) {
ctx->data[ctx->datalen] = data[i];
ctx->datalen++;
if (ctx->datalen == 64) {
sha256_transform(ctx, ctx->data);
ctx->bitlen += 512;
ctx->datalen = 0;
}
}
}
void sha256_final(SHA256_CTX *ctx, BYTE hash[])
{
WORD i;
i = ctx->datalen;
// Pad whatever data is left in the buffer.
if (ctx->datalen < 56) {
ctx->data[i++] = 0x80;
while (i < 56)
ctx->data[i++] = 0x00;
}
else {
ctx->data[i++] = 0x80;
while (i < 64)
ctx->data[i++] = 0x00;
sha256_transform(ctx, ctx->data);
memset(ctx->data, 0, 56);
}
// Append to the padding the total message's length in bits and transform.
ctx->bitlen += ctx->datalen * 8;
ctx->data[63] = ctx->bitlen;
ctx->data[62] = ctx->bitlen >> 8;
ctx->data[61] = ctx->bitlen >> 16;
ctx->data[60] = ctx->bitlen >> 24;
ctx->data[59] = ctx->bitlen >> 32;
ctx->data[58] = ctx->bitlen >> 40;
ctx->data[57] = ctx->bitlen >> 48;
ctx->data[56] = ctx->bitlen >> 56;
sha256_transform(ctx, ctx->data);
// Since this implementation uses little endian byte ordering and SHA uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i) {
hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;
hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;
hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;
}
}
================================================
FILE: src/sha256.h
================================================
/*********************************************************************
* Filename: sha256.h
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Defines the API for the corresponding SHA1 implementation.
*********************************************************************/
#ifndef SHA256_H
#define SHA256_H
/*************************** HEADER FILES ***************************/
#include
/****************************** MACROS ******************************/
#define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest
/**************************** DATA TYPES ****************************/
typedef unsigned char BYTE; // 8-bit byte
typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
typedef struct {
BYTE data[64];
WORD datalen;
unsigned long long bitlen;
WORD state[8];
} SHA256_CTX;
/*********************** FUNCTION DECLARATIONS **********************/
void sha256_init(SHA256_CTX *ctx);
void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);
void sha256_final(SHA256_CTX *ctx, BYTE hash[]);
#endif // SHA256_H
================================================
FILE: src/types.h
================================================
#pragma once
#include
typedef uint64_t dword_t;
typedef uint32_t word_t;
typedef uint16_t hword_t;
typedef uint8_t byte_t;
typedef int64_t dlong_t;
typedef int32_t long_t;
typedef int16_t short_t;
typedef int8_t char_t;
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
#define BIT(n) (1U << (n))
static inline uint16_t __local_bswap16(uint16_t x) {
return ((x << 8) & 0xff00) | ((x >> 8) & 0x00ff);
}
static inline uint32_t __local_bswap32(uint32_t x) {
return ((x << 24) & 0xff000000 ) |
((x << 8) & 0x00ff0000 ) |
((x >> 8) & 0x0000ff00 ) |
((x >> 24) & 0x000000ff );
}
static inline uint64_t __local_bswap64(uint64_t x)
{
return (uint64_t)__local_bswap32(x>>32) |
((uint64_t)__local_bswap32(x&0xFFFFFFFF) << 32);
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define be_dword(a) __local_bswap64(a)
#define be_word(a) __local_bswap32(a)
#define be_hword(a) __local_bswap16(a)
#define le_dword(a) (a)
#define le_word(a) (a)
#define le_hword(a) (a)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define be_dword(a) (a)
#define be_word(a) (a)
#define be_hword(a) (a)
#define le_dword(a) __local_bswap64(a)
#define le_word(a) __local_bswap32(a)
#define le_hword(a) __local_bswap16(a)
#else
#error "What's the endianness of the platform you're targeting?"
#endif