[
  {
    "path": ".gitignore",
    "content": "build*\nINSTALL\nMakefile.in\naclocal.m4\nautom4te.cache\nconfig.guess\nconfig.sub\nconfigure\ndepcomp\ninstall-sh\nmissing\ncompile\n.deps\nMakefile\nconfig.status\nconfig.log\n.dirstamp\nelf2nro\nelf2nso\nelf2kip\nnacptool\nnpdmtool\nnxlink\n*.o\n*.elf\n*.kip\n*.nro\n*.nso\n*.npdm\n*.json\n"
  },
  {
    "path": "AUTHORS",
    "content": ""
  },
  {
    "path": "COPYING",
    "content": "Copyright 2017 libnx Authors\n\nPermission 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.\n\nTHE 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."
  },
  {
    "path": "ChangeLog",
    "content": ""
  },
  {
    "path": "Makefile.am",
    "content": "# Makefile.am -- Process this file with automake to produce Makefile.in\nbin_PROGRAMS = elf2nso elf2nro elf2kip build_pfs0 build_romfs nacptool npdmtool nxlink\n\nbuild_pfs0_SOURCES\t=\tsrc/build_pfs0.c src/types.h\n\nbuild_romfs_SOURCES = src/build_romfs.c src/romfs.c src/romfs.h src/filepath.c src/filepath.h src/types.h\n\nelf2nro_SOURCES\t=\tsrc/elf2nro.c src/elf64.h src/romfs.c src/filepath.c src/filepath.h src/romfs.h src/elf_common.h\n\nelf2nso_SOURCES\t=\tsrc/elf2nso.c src/sha256.c src/sha256.h src/elf64.h src/elf_common.h\n\nelf2kip_SOURCES\t=\tsrc/elf2kip.c src/cJSON.c src/cJSON.h src/blz.c src/blz.h src/elf64.h src/elf_common.h\n\nnacptool_SOURCES\t=\tsrc/nacptool.c\n\nnpdmtool_SOURCES\t=\tsrc/npdmtool.c src/cJSON.c src/cJSON.h\n\nnxlink_SOURCES = src/nxlink.c\n\nnxlink_CPPFLAGS = @ZLIB_CFLAGS@\nnxlink_LDADD = @ZLIB_LIBS@ @NET_LIBS@\n\nelf2nso_CPPFLAGS = @LZ4_CFLAGS@\nelf2nso_LDADD = @LZ4_LIBS@\n\nelf2nro_CPPFLAGS = @LZ4_CFLAGS@\nelf2nro_LDADD = @LZ4_LIBS@\n\n\nEXTRA_DIST = autogen.sh\n"
  },
  {
    "path": "NEWS",
    "content": ""
  },
  {
    "path": "README",
    "content": ""
  },
  {
    "path": "autogen.sh",
    "content": "aclocal\nautoconf\nautomake --add-missing -c\n"
  },
  {
    "path": "configure.ac",
    "content": "#                                               -*- Autoconf -*-\n# Process this file with autoconf to produce a configure script.\n\nAC_PREREQ(2.61)\nAC_INIT([switch-tools],[1.13.1],[https://github.com/switchbrew/switch-tools/issues])\nAC_CONFIG_SRCDIR([src/build_pfs0.c])\n\nAM_INIT_AUTOMAKE([subdir-objects])\n\nAC_CANONICAL_BUILD\nAC_CANONICAL_HOST\n\nAC_PROG_CC\n\nAC_SYS_LARGEFILE\n\nPKG_CHECK_MODULES([LZ4],\n\t\t[liblz4 >= 1.7.1 liblz4 < 100],\n\t\t[have_lz4=\"yes\"],\n\t\t[PKG_CHECK_MODULES([LZ4],\n\t\t\t[liblz4 >= 131],\n\t\t\t[have_lz4=\"yes\"])\n])\n\nPKG_CHECK_MODULES([ZLIB], zlib, [\n  AC_DEFINE([HAVE_LIBZ], [1], [Define if using zlib.])\n])\n\nNET_LIBS=\"\"\n\ncase \"$host\" in\n   *-*-mingw*)\n      NET_LIBS=\"-lws2_32\"\n      CFLAGS=\"$CFLAGS -D__USE_MINGW_ANSI_STDIO -D_WIN32_WINNT=0x0600\"\n      ;;\nesac\n\nCFLAGS=\"$CFLAGS -std=gnu99\"\n\nAC_SUBST(ZLIB_CFLAGS)\nAC_SUBST(ZLIB_LIBS)\nAC_SUBST(NET_LIBS)\nAC_SUBST(LZ4_CFLAGS)\nAC_SUBST(LZ4_LIBS)\nAC_CONFIG_FILES([Makefile])\nAC_OUTPUT\n"
  },
  {
    "path": "src/blz.c",
    "content": "/*----------------------------------------------------------------------------*/\n/*--  blz.c - Bottom LZ coding for Nintendo GBA/DS                          --*/\n/*--  Copyright (C) 2011 CUE                                                --*/\n/*--                                                                        --*/\n/*--  This program is free software: you can redistribute it and/or modify  --*/\n/*--  it under the terms of the GNU General Public License as published by  --*/\n/*--  the Free Software Foundation, either version 3 of the License, or     --*/\n/*--  (at your option) any later version.                                   --*/\n/*--                                                                        --*/\n/*--  This program is distributed in the hope that it will be useful,       --*/\n/*--  but WITHOUT ANY WARRANTY; without even the implied warranty of        --*/\n/*--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the          --*/\n/*--  GNU General Public License for more details.                          --*/\n/*--                                                                        --*/\n/*--  You should have received a copy of the GNU General Public License     --*/\n/*--  along with this program. If not, see <http://www.gnu.org/licenses/>.  --*/\n/*----------------------------------------------------------------------------*/\n\n/*----------------------------------------------------------------------------*/\n#include \"blz.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n/*----------------------------------------------------------------------------*/\n#define CMD_DECODE    0x00       // decode\n#define CMD_ENCODE    0x01       // encode\n\n#define BLZ_SHIFT     1          // bits to shift\n#define BLZ_MASK      0x80       // bits to check:\n                                 // ((((1 << BLZ_SHIFT) - 1) << (8 - BLZ_SHIFT)\n\n#define BLZ_THRESHOLD 2          // max number of bytes to not encode\n#define BLZ_N         0x1002     // max offset ((1 << 12) + 2)\n#define BLZ_F         0x12       // max coded ((1 << 4) + BLZ_THRESHOLD)\n\n#define RAW_MINIM     0x00000000 // empty file, 0 bytes\n#define RAW_MAXIM     0x00FFFFFF // 3-bytes length, 16MB - 1\n\n#define BLZ_MINIM     0x00000004 // header only (empty RAW file)\n#define BLZ_MAXIM     0x01400000 // 0x0120000A, padded to 20MB:\n                                 // * length, RAW_MAXIM\n                                 // * flags, (RAW_MAXIM + 7) / 8\n                                 // * header, 11\n                                 // 0x00FFFFFF + 0x00200000 + 12 + padding\n\n/*----------------------------------------------------------------------------*/\n#define BREAK(text)   { printf(text); return; }\n#define EXIT(text)    { printf(text); exit(-1); }\n\n/*----------------------------------------------------------------------------*/\nu8 *Memory(int length, int size);\n\nu8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);\nvoid  BLZ_Invert(u8 *buffer, int length);\n\n/*----------------------------------------------------------------------------*/\nu8 *Memory(int length, int size) {\n  u8 *fb;\n\n  fb = (u8 *) calloc(length * size, size);\n  if (fb == NULL) EXIT(\"\\nMemory error\\n\");\n\n  return(fb);\n}\n\n/*----------------------------------------------------------------------------*/\nvoid BLZ_Decode(char *filename) {\n  // u8 *pak_buffer, *raw_buffer, *pak, *raw, *pak_end, *raw_end;\n  // u32   pak_len, raw_len, len, pos, inc_len, hdr_len, enc_len, dec_len;\n  // u8  flags, mask;\n\n  // printf(\"- decoding '%s'\", filename);\n\n  // // pak_buffer = Load(filename, &pak_len, BLZ_MINIM, BLZ_MAXIM);\n\n  // inc_len = *(u32 *)(pak_buffer + pak_len - 4);\n  // if (!inc_len) {\n  //   enc_len = 0;\n  //   dec_len = pak_len - 4;\n  //   pak_len = 0;\n  //   raw_len = dec_len;\n  // } else {\n  //   if (pak_len < 8) EXIT(\"File has a bad header\\n\");\n  //   hdr_len = pak_buffer[pak_len - 5];\n  //   if ((hdr_len < 0x08) || (hdr_len > 0x0B)) EXIT(\"Bad header length\\n\");\n  //   if (pak_len <= hdr_len) EXIT(\"Bad length\\n\");\n  //   enc_len = *(u32 *)(pak_buffer + pak_len - 8) & 0x00FFFFFF;\n  //   dec_len = pak_len - enc_len;\n  //   pak_len = enc_len - hdr_len;\n  //   raw_len = dec_len + enc_len + inc_len;\n  //   if (raw_len > RAW_MAXIM) EXIT(\"Bad decoded length\\n\");\n  // }\n\n  // raw_buffer = (u8 *) Memory(raw_len, sizeof(char));\n\n  // pak = pak_buffer;\n  // raw = raw_buffer;\n  // pak_end = pak_buffer + dec_len + pak_len;\n  // raw_end = raw_buffer + raw_len;\n\n  // for (len = 0; len < dec_len; len++) *(raw++) = *(pak++);\n\n  // BLZ_Invert(pak_buffer + dec_len, pak_len);\n\n  // mask = 0;\n\n  // while (raw < raw_end) {\n  //   if (!(mask >>= BLZ_SHIFT)) {\n  //     if (pak == pak_end) break;\n  //     flags = *pak++;\n  //     mask = BLZ_MASK;\n  //   }\n\n  //   if (!(flags & mask)) {\n  //     if (pak == pak_end) break;\n  //     *raw++ = *pak++;\n  //   } else {\n  //     if (pak + 1 >= pak_end) break;\n  //     pos = *pak++ << 8;\n  //     pos |= *pak++;\n  //     len = (pos >> 12) + BLZ_THRESHOLD + 1;\n  //     if (raw + len > raw_end) {\n  //       printf(\", WARNING: wrong decoded length!\");\n  //       len = raw_end - raw;\n  //     }\n  //     pos = (pos & 0xFFF) + 3;\n  //     while (len--) *(raw++) = *(raw - pos);\n  //   }\n  // }\n\n  // BLZ_Invert(raw_buffer + dec_len, raw_len - dec_len);\n\n  // raw_len = raw - raw_buffer;\n\n  // if (raw != raw_end) printf(\", WARNING: unexpected end of encoded file!\");\n\n  // // Save(filename, raw_buffer, raw_len);\n\n  // free(raw_buffer);\n  // free(pak_buffer);\n\n  // printf(\"\\n\");\n}\n\nu8 *Load(char *filename, u32 *length, int min, int max) {\n  FILE *fp;\n  int   fs;\n  u8 *fb;\n\n  if ((fp = fopen(filename, \"rb\")) == NULL) EXIT(\"\\nFile open error\\n\");\n  fseek(fp, 0, SEEK_END);\n  fs = ftell(fp);\n  fseek(fp, 0, SEEK_SET);\n  if ((fs < min) || (fs > max)) EXIT(\"\\nFile size error\\n\");\n  fb = Memory(fs + 3, sizeof(char));\n  if (fread(fb, 1, fs, fp) != fs) EXIT(\"\\nFile read error\\n\");\n  if (fclose(fp) == EOF) EXIT(\"\\nFile close error\\n\");\n\n  *length = fs;\n\n  return(fb);\n}\n\n/*----------------------------------------------------------------------------*/\nu8* BLZ_Encode(char *filename, u32* pak_len, int mode) {\n  u8 *raw_buffer, *pak_buffer, *new_buffer;\n  u32   raw_len, new_len;\n\n  raw_buffer = Load(filename, &raw_len, RAW_MINIM, RAW_MAXIM);\n\n  pak_buffer = NULL;\n  *pak_len = BLZ_MAXIM + 1;\n\n  new_buffer = BLZ_Code(raw_buffer, raw_len, &new_len, mode);\n  if (new_len < *pak_len) {\n    if (pak_buffer != NULL) free(pak_buffer);\n    pak_buffer = new_buffer;\n    *pak_len = new_len;\n  }\n\n  return pak_buffer;\n}\n\n/*----------------------------------------------------------------------------*/\nu8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best) {\n  u8 *pak_buffer, *pak, *raw, *raw_end, *flg = NULL, *tmp;\n  u32   pak_len, inc_len, hdr_len, enc_len, len, pos, max;\n  u32   len_best, pos_best = 0, len_next, pos_next, len_post, pos_post;\n  u32   pak_tmp, raw_tmp;\n  u8  mask;\n\n#define SEARCH(l,p) { \\\n  l = BLZ_THRESHOLD;                                          \\\n                                                              \\\n  max = raw - raw_buffer >= BLZ_N ? BLZ_N : raw - raw_buffer; \\\n  for (pos = 3; pos <= max; pos++) {                          \\\n    for (len = 0; len < BLZ_F; len++) {                       \\\n      if (raw + len == raw_end) break;                        \\\n      if (len >= pos) break;                                  \\\n      if (*(raw + len) != *(raw + len - pos)) break;          \\\n    }                                                         \\\n                                                              \\\n    if (len > l) {                                            \\\n      p = pos;                                                \\\n      if ((l = len) == BLZ_F) break;                          \\\n    }                                                         \\\n  }                                                           \\\n}\n\n  pak_tmp = 0;\n  raw_tmp = raw_len;\n\n  pak_len = raw_len + ((raw_len + 7) / 8) + 15;\n  pak_buffer = (u8 *) Memory(pak_len, sizeof(char));\n\n  BLZ_Invert(raw_buffer, raw_len);\n\n  pak = pak_buffer;\n  raw = raw_buffer;\n  raw_end = raw_buffer + raw_len;\n\n  mask = 0;\n\n  while (raw < raw_end) {\n    if (!(mask >>= BLZ_SHIFT)) {\n      *(flg = pak++) = 0;\n      mask = BLZ_MASK;\n    }\n\n    SEARCH(len_best, pos_best);\n\n    // LZ-CUE optimization start\n    if (best) {\n      if (len_best > BLZ_THRESHOLD) {\n        if (raw + len_best < raw_end) {\n          raw += len_best;\n          SEARCH(len_next, pos_next);\n          raw -= len_best - 1;\n          SEARCH(len_post, pos_post);\n          raw--;\n\n          if (len_next <= BLZ_THRESHOLD) len_next = 1;\n          if (len_post <= BLZ_THRESHOLD) len_post = 1;\n\n          if (len_best + len_next <= 1 + len_post) len_best = 1;\n        }\n      }\n    }\n    // LZ-CUE optimization end\n\n    *flg <<= 1;\n    if (len_best > BLZ_THRESHOLD) {\n      raw += len_best;\n      *flg |= 1;\n      *pak++ = ((len_best - (BLZ_THRESHOLD+1)) << 4) | ((pos_best - 3) >> 8);\n      *pak++ = (pos_best - 3) & 0xFF;\n    } else {\n      *pak++ = *raw++;\n    }\n\n    if (pak - pak_buffer + raw_len - (raw - raw_buffer) < pak_tmp + raw_tmp) {\n      pak_tmp = pak - pak_buffer;\n      raw_tmp = raw_len - (raw - raw_buffer);\n    }\n  }\n\n  while (mask && (mask != 1)) {\n    mask >>= BLZ_SHIFT;\n    *flg <<= 1;\n  }\n\n  pak_len = pak - pak_buffer;\n\n  BLZ_Invert(raw_buffer, raw_len);\n  BLZ_Invert(pak_buffer, pak_len);\n\n  if (!pak_tmp || (raw_len + 4 < ((pak_tmp + raw_tmp + 3) & -4) + 8)) {\n    pak = pak_buffer;\n    raw = raw_buffer;\n    raw_end = raw_buffer + raw_len;\n\n    while (raw < raw_end) *pak++ = *raw++;\n\n    while ((pak - pak_buffer) & 3) *pak++ = 0;\n\n    *(u32 *)pak = 0; pak += 4;\n  } else {\n    tmp = (u8 *) Memory(raw_tmp + pak_tmp + 15, sizeof(char));\n\n    for (len = 0; len < raw_tmp; len++)\n      tmp[len] = raw_buffer[len];\n\n    for (len = 0; len < pak_tmp; len++)\n      tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];\n\n    pak = pak_buffer;\n    pak_buffer = tmp;\n\n    free(pak);\n\n    pak = pak_buffer + raw_tmp + pak_tmp;\n\n    enc_len = pak_tmp;\n    hdr_len = 12;\n    inc_len = raw_len - pak_tmp - raw_tmp;\n\n    while ((pak - pak_buffer) & 3) {\n      *pak++ = 0xFF;\n      hdr_len++;\n    }\n\n    *(u32 *)pak = enc_len + hdr_len; pak += 4;\n    *(u32 *)pak = hdr_len;           pak += 4;\n    *(u32 *)pak = inc_len - hdr_len; pak += 4;\n  }\n\n  *new_len = pak - pak_buffer;\n\n  return(pak_buffer);\n}\n\n/*----------------------------------------------------------------------------*/\nvoid BLZ_Invert(u8 *buffer, int length) {\n  u8 *bottom, ch;\n\n  bottom = buffer + length - 1;\n\n  while (buffer < bottom) {\n    ch = *buffer;\n    *buffer++ = *bottom;\n    *bottom-- = ch;\n  }\n}\n\n/*----------------------------------------------------------------------------*/\n/*--  EOF                                           Copyright (C) 2011 CUE  --*/\n/*----------------------------------------------------------------------------*/\n"
  },
  {
    "path": "src/blz.h",
    "content": "#pragma once\n\n#include <stdint.h>\n\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define BLZ_NORMAL    0          // normal mode\n#define BLZ_BEST      1          // best mode\n\nu8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);"
  },
  {
    "path": "src/cJSON.c",
    "content": "/*\n  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to deal\n  in the Software without restriction, including without limitation the rights\n  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n  copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n  THE SOFTWARE.\n*/\n\n/* cJSON */\n/* JSON parser in C. */\n\n/* disable warnings about old C89 functions in MSVC */\n#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)\n#define _CRT_SECURE_NO_DEPRECATE\n#endif\n\n#ifdef __GNUC__\n#pragma GCC visibility push(default)\n#endif\n#if defined(_MSC_VER)\n#pragma warning (push)\n/* disable warning about single line comments in system headers */\n#pragma warning (disable : 4001)\n#endif\n\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <float.h>\n#include <limits.h>\n#include <ctype.h>\n\n#ifdef ENABLE_LOCALES\n#include <locale.h>\n#endif\n\n#if defined(_MSC_VER)\n#pragma warning (pop)\n#endif\n#ifdef __GNUC__\n#pragma GCC visibility pop\n#endif\n\n#include \"cJSON.h\"\n\n/* define our own boolean type */\n#define true ((cJSON_bool)1)\n#define false ((cJSON_bool)0)\n\ntypedef struct {\n    const unsigned char *json;\n    size_t position;\n} error;\nstatic error global_error = { NULL, 0 };\n\nCJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)\n{\n    return (const char*) (global_error.json + global_error.position);\n}\n\nCJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) {\n    if (!cJSON_IsString(item)) {\n        return NULL;\n    }\n\n    return item->valuestring;\n}\n\n/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */\n#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 6)\n    #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.\n#endif\n\nCJSON_PUBLIC(const char*) cJSON_Version(void)\n{\n    static char version[15];\n    sprintf(version, \"%i.%i.%i\", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);\n\n    return version;\n}\n\n/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */\nstatic int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)\n{\n    if ((string1 == NULL) || (string2 == NULL))\n    {\n        return 1;\n    }\n\n    if (string1 == string2)\n    {\n        return 0;\n    }\n\n    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)\n    {\n        if (*string1 == '\\0')\n        {\n            return 0;\n        }\n    }\n\n    return tolower(*string1) - tolower(*string2);\n}\n\ntypedef struct internal_hooks\n{\n    void *(*allocate)(size_t size);\n    void (*deallocate)(void *pointer);\n    void *(*reallocate)(void *pointer, size_t size);\n} internal_hooks;\n\n#if defined(_MSC_VER)\n/* work around MSVC error C2322: '...' address of dillimport '...' is not static */\nstatic void *internal_malloc(size_t size)\n{\n    return malloc(size);\n}\nstatic void internal_free(void *pointer)\n{\n    free(pointer);\n}\nstatic void *internal_realloc(void *pointer, size_t size)\n{\n    return realloc(pointer, size);\n}\n#else\n#define internal_malloc malloc\n#define internal_free free\n#define internal_realloc realloc\n#endif\n\nstatic internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };\n\nstatic unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)\n{\n    size_t length = 0;\n    unsigned char *copy = NULL;\n\n    if (string == NULL)\n    {\n        return NULL;\n    }\n\n    length = strlen((const char*)string) + sizeof(\"\");\n    copy = (unsigned char*)hooks->allocate(length);\n    if (copy == NULL)\n    {\n        return NULL;\n    }\n    memcpy(copy, string, length);\n\n    return copy;\n}\n\nCJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)\n{\n    if (hooks == NULL)\n    {\n        /* Reset hooks */\n        global_hooks.allocate = malloc;\n        global_hooks.deallocate = free;\n        global_hooks.reallocate = realloc;\n        return;\n    }\n\n    global_hooks.allocate = malloc;\n    if (hooks->malloc_fn != NULL)\n    {\n        global_hooks.allocate = hooks->malloc_fn;\n    }\n\n    global_hooks.deallocate = free;\n    if (hooks->free_fn != NULL)\n    {\n        global_hooks.deallocate = hooks->free_fn;\n    }\n\n    /* use realloc only if both free and malloc are used */\n    global_hooks.reallocate = NULL;\n    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))\n    {\n        global_hooks.reallocate = realloc;\n    }\n}\n\n/* Internal constructor. */\nstatic cJSON *cJSON_New_Item(const internal_hooks * const hooks)\n{\n    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));\n    if (node)\n    {\n        memset(node, '\\0', sizeof(cJSON));\n    }\n\n    return node;\n}\n\n/* Delete a cJSON structure. */\nCJSON_PUBLIC(void) cJSON_Delete(cJSON *item)\n{\n    cJSON *next = NULL;\n    while (item != NULL)\n    {\n        next = item->next;\n        if (!(item->type & cJSON_IsReference) && (item->child != NULL))\n        {\n            cJSON_Delete(item->child);\n        }\n        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))\n        {\n            global_hooks.deallocate(item->valuestring);\n        }\n        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))\n        {\n            global_hooks.deallocate(item->string);\n        }\n        global_hooks.deallocate(item);\n        item = next;\n    }\n}\n\n/* get the decimal point character of the current locale */\nstatic unsigned char get_decimal_point(void)\n{\n#ifdef ENABLE_LOCALES\n    struct lconv *lconv = localeconv();\n    return (unsigned char) lconv->decimal_point[0];\n#else\n    return '.';\n#endif\n}\n\ntypedef struct\n{\n    const unsigned char *content;\n    size_t length;\n    size_t offset;\n    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */\n    internal_hooks hooks;\n} parse_buffer;\n\n/* check if the given size is left to read in a given parse buffer (starting with 1) */\n#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))\n/* check if the buffer can be accessed at the given index (starting with 0) */\n#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))\n#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))\n/* get a pointer to the buffer at the position */\n#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)\n\n/* Parse the input text to generate a number, and populate the result into item. */\nstatic cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)\n{\n    double number = 0;\n    unsigned char *after_end = NULL;\n    unsigned char number_c_string[64];\n    unsigned char decimal_point = get_decimal_point();\n    size_t i = 0;\n\n    if ((input_buffer == NULL) || (input_buffer->content == NULL))\n    {\n        return false;\n    }\n\n    /* copy the number into a temporary buffer and replace '.' with the decimal point\n     * of the current locale (for strtod)\n     * This also takes care of '\\0' not necessarily being available for marking the end of the input */\n    for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)\n    {\n        switch (buffer_at_offset(input_buffer)[i])\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            case '+':\n            case '-':\n            case 'e':\n            case 'E':\n                number_c_string[i] = buffer_at_offset(input_buffer)[i];\n                break;\n\n            case '.':\n                number_c_string[i] = decimal_point;\n                break;\n\n            default:\n                goto loop_end;\n        }\n    }\nloop_end:\n    number_c_string[i] = '\\0';\n\n    number = strtod((const char*)number_c_string, (char**)&after_end);\n    if (number_c_string == after_end)\n    {\n        return false; /* parse_error */\n    }\n\n    item->valuedouble = number;\n\n    /* use saturation in case of overflow */\n    if (number >= INT_MAX)\n    {\n        item->valueint = INT_MAX;\n    }\n    else if (number <= INT_MIN)\n    {\n        item->valueint = INT_MIN;\n    }\n    else\n    {\n        item->valueint = (int)number;\n    }\n\n    item->type = cJSON_Number;\n\n    input_buffer->offset += (size_t)(after_end - number_c_string);\n    return true;\n}\n\n/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */\nCJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)\n{\n    if (number >= INT_MAX)\n    {\n        object->valueint = INT_MAX;\n    }\n    else if (number <= INT_MIN)\n    {\n        object->valueint = INT_MIN;\n    }\n    else\n    {\n        object->valueint = (int)number;\n    }\n\n    return object->valuedouble = number;\n}\n\ntypedef struct\n{\n    unsigned char *buffer;\n    size_t length;\n    size_t offset;\n    size_t depth; /* current nesting depth (for formatted printing) */\n    cJSON_bool noalloc;\n    cJSON_bool format; /* is this print a formatted print */\n    internal_hooks hooks;\n} printbuffer;\n\n/* realloc printbuffer if necessary to have at least \"needed\" bytes more */\nstatic unsigned char* ensure(printbuffer * const p, size_t needed)\n{\n    unsigned char *newbuffer = NULL;\n    size_t newsize = 0;\n\n    if ((p == NULL) || (p->buffer == NULL))\n    {\n        return NULL;\n    }\n\n    if ((p->length > 0) && (p->offset >= p->length))\n    {\n        /* make sure that offset is valid */\n        return NULL;\n    }\n\n    if (needed > INT_MAX)\n    {\n        /* sizes bigger than INT_MAX are currently not supported */\n        return NULL;\n    }\n\n    needed += p->offset + 1;\n    if (needed <= p->length)\n    {\n        return p->buffer + p->offset;\n    }\n\n    if (p->noalloc) {\n        return NULL;\n    }\n\n    /* calculate new buffer size */\n    if (needed > (INT_MAX / 2))\n    {\n        /* overflow of int, use INT_MAX if possible */\n        if (needed <= INT_MAX)\n        {\n            newsize = INT_MAX;\n        }\n        else\n        {\n            return NULL;\n        }\n    }\n    else\n    {\n        newsize = needed * 2;\n    }\n\n    if (p->hooks.reallocate != NULL)\n    {\n        /* reallocate with realloc if available */\n        newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);\n        if (newbuffer == NULL)\n        {\n            p->hooks.deallocate(p->buffer);\n            p->length = 0;\n            p->buffer = NULL;\n\n            return NULL;\n        }\n    }\n    else\n    {\n        /* otherwise reallocate manually */\n        newbuffer = (unsigned char*)p->hooks.allocate(newsize);\n        if (!newbuffer)\n        {\n            p->hooks.deallocate(p->buffer);\n            p->length = 0;\n            p->buffer = NULL;\n\n            return NULL;\n        }\n        if (newbuffer)\n        {\n            memcpy(newbuffer, p->buffer, p->offset + 1);\n        }\n        p->hooks.deallocate(p->buffer);\n    }\n    p->length = newsize;\n    p->buffer = newbuffer;\n\n    return newbuffer + p->offset;\n}\n\n/* calculate the new length of the string in a printbuffer and update the offset */\nstatic void update_offset(printbuffer * const buffer)\n{\n    const unsigned char *buffer_pointer = NULL;\n    if ((buffer == NULL) || (buffer->buffer == NULL))\n    {\n        return;\n    }\n    buffer_pointer = buffer->buffer + buffer->offset;\n\n    buffer->offset += strlen((const char*)buffer_pointer);\n}\n\n/* Render the number nicely from the given item into a string. */\nstatic cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)\n{\n    unsigned char *output_pointer = NULL;\n    double d = item->valuedouble;\n    int length = 0;\n    size_t i = 0;\n    unsigned char number_buffer[26]; /* temporary buffer to print the number into */\n    unsigned char decimal_point = get_decimal_point();\n    double test;\n\n    if (output_buffer == NULL)\n    {\n        return false;\n    }\n\n    /* This checks for NaN and Infinity */\n    if ((d * 0) != 0)\n    {\n        length = sprintf((char*)number_buffer, \"null\");\n    }\n    else\n    {\n        /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */\n        length = sprintf((char*)number_buffer, \"%1.15g\", d);\n\n        /* Check whether the original double can be recovered */\n        if ((sscanf((char*)number_buffer, \"%lg\", &test) != 1) || ((double)test != d))\n        {\n            /* If not, print with 17 decimal places of precision */\n            length = sprintf((char*)number_buffer, \"%1.17g\", d);\n        }\n    }\n\n    /* sprintf failed or buffer overrun occured */\n    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))\n    {\n        return false;\n    }\n\n    /* reserve appropriate space in the output */\n    output_pointer = ensure(output_buffer, (size_t)length + sizeof(\"\"));\n    if (output_pointer == NULL)\n    {\n        return false;\n    }\n\n    /* copy the printed number to the output and replace locale\n     * dependent decimal point with '.' */\n    for (i = 0; i < ((size_t)length); i++)\n    {\n        if (number_buffer[i] == decimal_point)\n        {\n            output_pointer[i] = '.';\n            continue;\n        }\n\n        output_pointer[i] = number_buffer[i];\n    }\n    output_pointer[i] = '\\0';\n\n    output_buffer->offset += (size_t)length;\n\n    return true;\n}\n\n/* parse 4 digit hexadecimal number */\nstatic unsigned parse_hex4(const unsigned char * const input)\n{\n    unsigned int h = 0;\n    size_t i = 0;\n\n    for (i = 0; i < 4; i++)\n    {\n        /* parse digit */\n        if ((input[i] >= '0') && (input[i] <= '9'))\n        {\n            h += (unsigned int) input[i] - '0';\n        }\n        else if ((input[i] >= 'A') && (input[i] <= 'F'))\n        {\n            h += (unsigned int) 10 + input[i] - 'A';\n        }\n        else if ((input[i] >= 'a') && (input[i] <= 'f'))\n        {\n            h += (unsigned int) 10 + input[i] - 'a';\n        }\n        else /* invalid */\n        {\n            return 0;\n        }\n\n        if (i < 3)\n        {\n            /* shift left to make place for the next nibble */\n            h = h << 4;\n        }\n    }\n\n    return h;\n}\n\n/* converts a UTF-16 literal to UTF-8\n * A literal can be one or two sequences of the form \\uXXXX */\nstatic unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)\n{\n    long unsigned int codepoint = 0;\n    unsigned int first_code = 0;\n    const unsigned char *first_sequence = input_pointer;\n    unsigned char utf8_length = 0;\n    unsigned char utf8_position = 0;\n    unsigned char sequence_length = 0;\n    unsigned char first_byte_mark = 0;\n\n    if ((input_end - first_sequence) < 6)\n    {\n        /* input ends unexpectedly */\n        goto fail;\n    }\n\n    /* get the first utf16 sequence */\n    first_code = parse_hex4(first_sequence + 2);\n\n    /* check that the code is valid */\n    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))\n    {\n        goto fail;\n    }\n\n    /* UTF16 surrogate pair */\n    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))\n    {\n        const unsigned char *second_sequence = first_sequence + 6;\n        unsigned int second_code = 0;\n        sequence_length = 12; /* \\uXXXX\\uXXXX */\n\n        if ((input_end - second_sequence) < 6)\n        {\n            /* input ends unexpectedly */\n            goto fail;\n        }\n\n        if ((second_sequence[0] != '\\\\') || (second_sequence[1] != 'u'))\n        {\n            /* missing second half of the surrogate pair */\n            goto fail;\n        }\n\n        /* get the second utf16 sequence */\n        second_code = parse_hex4(second_sequence + 2);\n        /* check that the code is valid */\n        if ((second_code < 0xDC00) || (second_code > 0xDFFF))\n        {\n            /* invalid second half of the surrogate pair */\n            goto fail;\n        }\n\n\n        /* calculate the unicode codepoint from the surrogate pair */\n        codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));\n    }\n    else\n    {\n        sequence_length = 6; /* \\uXXXX */\n        codepoint = first_code;\n    }\n\n    /* encode as UTF-8\n     * takes at maximum 4 bytes to encode:\n     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */\n    if (codepoint < 0x80)\n    {\n        /* normal ascii, encoding 0xxxxxxx */\n        utf8_length = 1;\n    }\n    else if (codepoint < 0x800)\n    {\n        /* two bytes, encoding 110xxxxx 10xxxxxx */\n        utf8_length = 2;\n        first_byte_mark = 0xC0; /* 11000000 */\n    }\n    else if (codepoint < 0x10000)\n    {\n        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */\n        utf8_length = 3;\n        first_byte_mark = 0xE0; /* 11100000 */\n    }\n    else if (codepoint <= 0x10FFFF)\n    {\n        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */\n        utf8_length = 4;\n        first_byte_mark = 0xF0; /* 11110000 */\n    }\n    else\n    {\n        /* invalid unicode codepoint */\n        goto fail;\n    }\n\n    /* encode as utf8 */\n    for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)\n    {\n        /* 10xxxxxx */\n        (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);\n        codepoint >>= 6;\n    }\n    /* encode first byte */\n    if (utf8_length > 1)\n    {\n        (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);\n    }\n    else\n    {\n        (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);\n    }\n\n    *output_pointer += utf8_length;\n\n    return sequence_length;\n\nfail:\n    return 0;\n}\n\n/* Parse the input text into an unescaped cinput, and populate item. */\nstatic cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)\n{\n    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;\n    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;\n    unsigned char *output_pointer = NULL;\n    unsigned char *output = NULL;\n\n    /* not a string */\n    if (buffer_at_offset(input_buffer)[0] != '\\\"')\n    {\n        goto fail;\n    }\n\n    {\n        /* calculate approximate size of the output (overestimate) */\n        size_t allocation_length = 0;\n        size_t skipped_bytes = 0;\n        while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\\\"'))\n        {\n            /* is escape sequence */\n            if (input_end[0] == '\\\\')\n            {\n                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)\n                {\n                    /* prevent buffer overflow when last input character is a backslash */\n                    goto fail;\n                }\n                skipped_bytes++;\n                input_end++;\n            }\n            input_end++;\n        }\n        if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\\\"'))\n        {\n            goto fail; /* string ended unexpectedly */\n        }\n\n        /* This is at most how much we need for the output */\n        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;\n        output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(\"\"));\n        if (output == NULL)\n        {\n            goto fail; /* allocation failure */\n        }\n    }\n\n    output_pointer = output;\n    /* loop through the string literal */\n    while (input_pointer < input_end)\n    {\n        if (*input_pointer != '\\\\')\n        {\n            *output_pointer++ = *input_pointer++;\n        }\n        /* escape sequence */\n        else\n        {\n            unsigned char sequence_length = 2;\n            if ((input_end - input_pointer) < 1)\n            {\n                goto fail;\n            }\n\n            switch (input_pointer[1])\n            {\n                case 'b':\n                    *output_pointer++ = '\\b';\n                    break;\n                case 'f':\n                    *output_pointer++ = '\\f';\n                    break;\n                case 'n':\n                    *output_pointer++ = '\\n';\n                    break;\n                case 'r':\n                    *output_pointer++ = '\\r';\n                    break;\n                case 't':\n                    *output_pointer++ = '\\t';\n                    break;\n                case '\\\"':\n                case '\\\\':\n                case '/':\n                    *output_pointer++ = input_pointer[1];\n                    break;\n\n                /* UTF-16 literal */\n                case 'u':\n                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);\n                    if (sequence_length == 0)\n                    {\n                        /* failed to convert UTF16-literal to UTF-8 */\n                        goto fail;\n                    }\n                    break;\n\n                default:\n                    goto fail;\n            }\n            input_pointer += sequence_length;\n        }\n    }\n\n    /* zero terminate the output */\n    *output_pointer = '\\0';\n\n    item->type = cJSON_String;\n    item->valuestring = (char*)output;\n\n    input_buffer->offset = (size_t) (input_end - input_buffer->content);\n    input_buffer->offset++;\n\n    return true;\n\nfail:\n    if (output != NULL)\n    {\n        input_buffer->hooks.deallocate(output);\n    }\n\n    if (input_pointer != NULL)\n    {\n        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);\n    }\n\n    return false;\n}\n\n/* Render the cstring provided to an escaped version that can be printed. */\nstatic cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)\n{\n    const unsigned char *input_pointer = NULL;\n    unsigned char *output = NULL;\n    unsigned char *output_pointer = NULL;\n    size_t output_length = 0;\n    /* numbers of additional characters needed for escaping */\n    size_t escape_characters = 0;\n\n    if (output_buffer == NULL)\n    {\n        return false;\n    }\n\n    /* empty string */\n    if (input == NULL)\n    {\n        output = ensure(output_buffer, sizeof(\"\\\"\\\"\"));\n        if (output == NULL)\n        {\n            return false;\n        }\n        strcpy((char*)output, \"\\\"\\\"\");\n\n        return true;\n    }\n\n    /* set \"flag\" to 1 if something needs to be escaped */\n    for (input_pointer = input; *input_pointer; input_pointer++)\n    {\n        switch (*input_pointer)\n        {\n            case '\\\"':\n            case '\\\\':\n            case '\\b':\n            case '\\f':\n            case '\\n':\n            case '\\r':\n            case '\\t':\n                /* one character escape sequence */\n                escape_characters++;\n                break;\n            default:\n                if (*input_pointer < 32)\n                {\n                    /* UTF-16 escape sequence uXXXX */\n                    escape_characters += 5;\n                }\n                break;\n        }\n    }\n    output_length = (size_t)(input_pointer - input) + escape_characters;\n\n    output = ensure(output_buffer, output_length + sizeof(\"\\\"\\\"\"));\n    if (output == NULL)\n    {\n        return false;\n    }\n\n    /* no characters have to be escaped */\n    if (escape_characters == 0)\n    {\n        output[0] = '\\\"';\n        memcpy(output + 1, input, output_length);\n        output[output_length + 1] = '\\\"';\n        output[output_length + 2] = '\\0';\n\n        return true;\n    }\n\n    output[0] = '\\\"';\n    output_pointer = output + 1;\n    /* copy the string */\n    for (input_pointer = input; *input_pointer != '\\0'; (void)input_pointer++, output_pointer++)\n    {\n        if ((*input_pointer > 31) && (*input_pointer != '\\\"') && (*input_pointer != '\\\\'))\n        {\n            /* normal character, copy */\n            *output_pointer = *input_pointer;\n        }\n        else\n        {\n            /* character needs to be escaped */\n            *output_pointer++ = '\\\\';\n            switch (*input_pointer)\n            {\n                case '\\\\':\n                    *output_pointer = '\\\\';\n                    break;\n                case '\\\"':\n                    *output_pointer = '\\\"';\n                    break;\n                case '\\b':\n                    *output_pointer = 'b';\n                    break;\n                case '\\f':\n                    *output_pointer = 'f';\n                    break;\n                case '\\n':\n                    *output_pointer = 'n';\n                    break;\n                case '\\r':\n                    *output_pointer = 'r';\n                    break;\n                case '\\t':\n                    *output_pointer = 't';\n                    break;\n                default:\n                    /* escape and print as unicode codepoint */\n                    sprintf((char*)output_pointer, \"u%04x\", *input_pointer);\n                    output_pointer += 4;\n                    break;\n            }\n        }\n    }\n    output[output_length + 1] = '\\\"';\n    output[output_length + 2] = '\\0';\n\n    return true;\n}\n\n/* Invoke print_string_ptr (which is useful) on an item. */\nstatic cJSON_bool print_string(const cJSON * const item, printbuffer * const p)\n{\n    return print_string_ptr((unsigned char*)item->valuestring, p);\n}\n\n/* Predeclare these prototypes. */\nstatic cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);\nstatic cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);\nstatic cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);\nstatic cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);\nstatic cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);\nstatic cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);\n\n/* Utility to jump whitespace and cr/lf */\nstatic parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)\n{\n    if ((buffer == NULL) || (buffer->content == NULL))\n    {\n        return NULL;\n    }\n\n    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))\n    {\n       buffer->offset++;\n    }\n\n    if (buffer->offset == buffer->length)\n    {\n        buffer->offset--;\n    }\n\n    return buffer;\n}\n\n/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */\nstatic parse_buffer *skip_utf8_bom(parse_buffer * const buffer)\n{\n    if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))\n    {\n        return NULL;\n    }\n\n    if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), \"\\xEF\\xBB\\xBF\", 3) == 0))\n    {\n        buffer->offset += 3;\n    }\n\n    return buffer;\n}\n\n/* Parse an object - create a new root, and populate. */\nCJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)\n{\n    parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };\n    cJSON *item = NULL;\n\n    /* reset error position */\n    global_error.json = NULL;\n    global_error.position = 0;\n\n    if (value == NULL)\n    {\n        goto fail;\n    }\n\n    buffer.content = (const unsigned char*)value;\n    buffer.length = strlen((const char*)value) + sizeof(\"\");\n    buffer.offset = 0;\n    buffer.hooks = global_hooks;\n\n    item = cJSON_New_Item(&global_hooks);\n    if (item == NULL) /* memory fail */\n    {\n        goto fail;\n    }\n\n    if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))\n    {\n        /* parse failure. ep is set. */\n        goto fail;\n    }\n\n    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */\n    if (require_null_terminated)\n    {\n        buffer_skip_whitespace(&buffer);\n        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\\0')\n        {\n            goto fail;\n        }\n    }\n    if (return_parse_end)\n    {\n        *return_parse_end = (const char*)buffer_at_offset(&buffer);\n    }\n\n    return item;\n\nfail:\n    if (item != NULL)\n    {\n        cJSON_Delete(item);\n    }\n\n    if (value != NULL)\n    {\n        error local_error;\n        local_error.json = (const unsigned char*)value;\n        local_error.position = 0;\n\n        if (buffer.offset < buffer.length)\n        {\n            local_error.position = buffer.offset;\n        }\n        else if (buffer.length > 0)\n        {\n            local_error.position = buffer.length - 1;\n        }\n\n        if (return_parse_end != NULL)\n        {\n            *return_parse_end = (const char*)local_error.json + local_error.position;\n        }\n\n        global_error = local_error;\n    }\n\n    return NULL;\n}\n\n/* Default options for cJSON_Parse */\nCJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)\n{\n    return cJSON_ParseWithOpts(value, 0, 0);\n}\n\n#define cjson_min(a, b) ((a < b) ? a : b)\n\nstatic unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)\n{\n    static const size_t default_buffer_size = 256;\n    printbuffer buffer[1];\n    unsigned char *printed = NULL;\n\n    memset(buffer, 0, sizeof(buffer));\n\n    /* create buffer */\n    buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);\n    buffer->length = default_buffer_size;\n    buffer->format = format;\n    buffer->hooks = *hooks;\n    if (buffer->buffer == NULL)\n    {\n        goto fail;\n    }\n\n    /* print the value */\n    if (!print_value(item, buffer))\n    {\n        goto fail;\n    }\n    update_offset(buffer);\n\n    /* check if reallocate is available */\n    if (hooks->reallocate != NULL)\n    {\n        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);\n        buffer->buffer = NULL;\n        if (printed == NULL) {\n            goto fail;\n        }\n    }\n    else /* otherwise copy the JSON over to a new buffer */\n    {\n        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);\n        if (printed == NULL)\n        {\n            goto fail;\n        }\n        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));\n        printed[buffer->offset] = '\\0'; /* just to be sure */\n\n        /* free the buffer */\n        hooks->deallocate(buffer->buffer);\n    }\n\n    return printed;\n\nfail:\n    if (buffer->buffer != NULL)\n    {\n        hooks->deallocate(buffer->buffer);\n    }\n\n    if (printed != NULL)\n    {\n        hooks->deallocate(printed);\n    }\n\n    return NULL;\n}\n\n/* Render a cJSON item/entity/structure to text. */\nCJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)\n{\n    return (char*)print(item, true, &global_hooks);\n}\n\nCJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)\n{\n    return (char*)print(item, false, &global_hooks);\n}\n\nCJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)\n{\n    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };\n\n    if (prebuffer < 0)\n    {\n        return NULL;\n    }\n\n    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);\n    if (!p.buffer)\n    {\n        return NULL;\n    }\n\n    p.length = (size_t)prebuffer;\n    p.offset = 0;\n    p.noalloc = false;\n    p.format = fmt;\n    p.hooks = global_hooks;\n\n    if (!print_value(item, &p))\n    {\n        global_hooks.deallocate(p.buffer);\n        return NULL;\n    }\n\n    return (char*)p.buffer;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)\n{\n    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };\n\n    if ((len < 0) || (buf == NULL))\n    {\n        return false;\n    }\n\n    p.buffer = (unsigned char*)buf;\n    p.length = (size_t)len;\n    p.offset = 0;\n    p.noalloc = true;\n    p.format = fmt;\n    p.hooks = global_hooks;\n\n    return print_value(item, &p);\n}\n\n/* Parser core - when encountering text, process appropriately. */\nstatic cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)\n{\n    if ((input_buffer == NULL) || (input_buffer->content == NULL))\n    {\n        return false; /* no input */\n    }\n\n    /* parse the different types of values */\n    /* null */\n    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), \"null\", 4) == 0))\n    {\n        item->type = cJSON_NULL;\n        input_buffer->offset += 4;\n        return true;\n    }\n    /* false */\n    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), \"false\", 5) == 0))\n    {\n        item->type = cJSON_False;\n        input_buffer->offset += 5;\n        return true;\n    }\n    /* true */\n    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), \"true\", 4) == 0))\n    {\n        item->type = cJSON_True;\n        item->valueint = 1;\n        input_buffer->offset += 4;\n        return true;\n    }\n    /* string */\n    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\\\"'))\n    {\n        return parse_string(item, input_buffer);\n    }\n    /* number */\n    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'))))\n    {\n        return parse_number(item, input_buffer);\n    }\n    /* array */\n    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))\n    {\n        return parse_array(item, input_buffer);\n    }\n    /* object */\n    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))\n    {\n        return parse_object(item, input_buffer);\n    }\n\n    return false;\n}\n\n/* Render a value to text. */\nstatic cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)\n{\n    unsigned char *output = NULL;\n\n    if ((item == NULL) || (output_buffer == NULL))\n    {\n        return false;\n    }\n\n    switch ((item->type) & 0xFF)\n    {\n        case cJSON_NULL:\n            output = ensure(output_buffer, 5);\n            if (output == NULL)\n            {\n                return false;\n            }\n            strcpy((char*)output, \"null\");\n            return true;\n\n        case cJSON_False:\n            output = ensure(output_buffer, 6);\n            if (output == NULL)\n            {\n                return false;\n            }\n            strcpy((char*)output, \"false\");\n            return true;\n\n        case cJSON_True:\n            output = ensure(output_buffer, 5);\n            if (output == NULL)\n            {\n                return false;\n            }\n            strcpy((char*)output, \"true\");\n            return true;\n\n        case cJSON_Number:\n            return print_number(item, output_buffer);\n\n        case cJSON_Raw:\n        {\n            size_t raw_length = 0;\n            if (item->valuestring == NULL)\n            {\n                return false;\n            }\n\n            raw_length = strlen(item->valuestring) + sizeof(\"\");\n            output = ensure(output_buffer, raw_length);\n            if (output == NULL)\n            {\n                return false;\n            }\n            memcpy(output, item->valuestring, raw_length);\n            return true;\n        }\n\n        case cJSON_String:\n            return print_string(item, output_buffer);\n\n        case cJSON_Array:\n            return print_array(item, output_buffer);\n\n        case cJSON_Object:\n            return print_object(item, output_buffer);\n\n        default:\n            return false;\n    }\n}\n\n/* Build an array from input text. */\nstatic cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)\n{\n    cJSON *head = NULL; /* head of the linked list */\n    cJSON *current_item = NULL;\n\n    if (input_buffer->depth >= CJSON_NESTING_LIMIT)\n    {\n        return false; /* to deeply nested */\n    }\n    input_buffer->depth++;\n\n    if (buffer_at_offset(input_buffer)[0] != '[')\n    {\n        /* not an array */\n        goto fail;\n    }\n\n    input_buffer->offset++;\n    buffer_skip_whitespace(input_buffer);\n    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))\n    {\n        /* empty array */\n        goto success;\n    }\n\n    /* check if we skipped to the end of the buffer */\n    if (cannot_access_at_index(input_buffer, 0))\n    {\n        input_buffer->offset--;\n        goto fail;\n    }\n\n    /* step back to character in front of the first element */\n    input_buffer->offset--;\n    /* loop through the comma separated array elements */\n    do\n    {\n        /* allocate next item */\n        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));\n        if (new_item == NULL)\n        {\n            goto fail; /* allocation failure */\n        }\n\n        /* attach next item to list */\n        if (head == NULL)\n        {\n            /* start the linked list */\n            current_item = head = new_item;\n        }\n        else\n        {\n            /* add to the end and advance */\n            current_item->next = new_item;\n            new_item->prev = current_item;\n            current_item = new_item;\n        }\n\n        /* parse next value */\n        input_buffer->offset++;\n        buffer_skip_whitespace(input_buffer);\n        if (!parse_value(current_item, input_buffer))\n        {\n            goto fail; /* failed to parse value */\n        }\n        buffer_skip_whitespace(input_buffer);\n    }\n    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));\n\n    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')\n    {\n        goto fail; /* expected end of array */\n    }\n\nsuccess:\n    input_buffer->depth--;\n\n    item->type = cJSON_Array;\n    item->child = head;\n\n    input_buffer->offset++;\n\n    return true;\n\nfail:\n    if (head != NULL)\n    {\n        cJSON_Delete(head);\n    }\n\n    return false;\n}\n\n/* Render an array to text */\nstatic cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)\n{\n    unsigned char *output_pointer = NULL;\n    size_t length = 0;\n    cJSON *current_element = item->child;\n\n    if (output_buffer == NULL)\n    {\n        return false;\n    }\n\n    /* Compose the output array. */\n    /* opening square bracket */\n    output_pointer = ensure(output_buffer, 1);\n    if (output_pointer == NULL)\n    {\n        return false;\n    }\n\n    *output_pointer = '[';\n    output_buffer->offset++;\n    output_buffer->depth++;\n\n    while (current_element != NULL)\n    {\n        if (!print_value(current_element, output_buffer))\n        {\n            return false;\n        }\n        update_offset(output_buffer);\n        if (current_element->next)\n        {\n            length = (size_t) (output_buffer->format ? 2 : 1);\n            output_pointer = ensure(output_buffer, length + 1);\n            if (output_pointer == NULL)\n            {\n                return false;\n            }\n            *output_pointer++ = ',';\n            if(output_buffer->format)\n            {\n                *output_pointer++ = ' ';\n            }\n            *output_pointer = '\\0';\n            output_buffer->offset += length;\n        }\n        current_element = current_element->next;\n    }\n\n    output_pointer = ensure(output_buffer, 2);\n    if (output_pointer == NULL)\n    {\n        return false;\n    }\n    *output_pointer++ = ']';\n    *output_pointer = '\\0';\n    output_buffer->depth--;\n\n    return true;\n}\n\n/* Build an object from the text. */\nstatic cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)\n{\n    cJSON *head = NULL; /* linked list head */\n    cJSON *current_item = NULL;\n\n    if (input_buffer->depth >= CJSON_NESTING_LIMIT)\n    {\n        return false; /* to deeply nested */\n    }\n    input_buffer->depth++;\n\n    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))\n    {\n        goto fail; /* not an object */\n    }\n\n    input_buffer->offset++;\n    buffer_skip_whitespace(input_buffer);\n    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))\n    {\n        goto success; /* empty object */\n    }\n\n    /* check if we skipped to the end of the buffer */\n    if (cannot_access_at_index(input_buffer, 0))\n    {\n        input_buffer->offset--;\n        goto fail;\n    }\n\n    /* step back to character in front of the first element */\n    input_buffer->offset--;\n    /* loop through the comma separated array elements */\n    do\n    {\n        /* allocate next item */\n        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));\n        if (new_item == NULL)\n        {\n            goto fail; /* allocation failure */\n        }\n\n        /* attach next item to list */\n        if (head == NULL)\n        {\n            /* start the linked list */\n            current_item = head = new_item;\n        }\n        else\n        {\n            /* add to the end and advance */\n            current_item->next = new_item;\n            new_item->prev = current_item;\n            current_item = new_item;\n        }\n\n        /* parse the name of the child */\n        input_buffer->offset++;\n        buffer_skip_whitespace(input_buffer);\n        if (!parse_string(current_item, input_buffer))\n        {\n            goto fail; /* faile to parse name */\n        }\n        buffer_skip_whitespace(input_buffer);\n\n        /* swap valuestring and string, because we parsed the name */\n        current_item->string = current_item->valuestring;\n        current_item->valuestring = NULL;\n\n        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))\n        {\n            goto fail; /* invalid object */\n        }\n\n        /* parse the value */\n        input_buffer->offset++;\n        buffer_skip_whitespace(input_buffer);\n        if (!parse_value(current_item, input_buffer))\n        {\n            goto fail; /* failed to parse value */\n        }\n        buffer_skip_whitespace(input_buffer);\n    }\n    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));\n\n    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))\n    {\n        goto fail; /* expected end of object */\n    }\n\nsuccess:\n    input_buffer->depth--;\n\n    item->type = cJSON_Object;\n    item->child = head;\n\n    input_buffer->offset++;\n    return true;\n\nfail:\n    if (head != NULL)\n    {\n        cJSON_Delete(head);\n    }\n\n    return false;\n}\n\n/* Render an object to text. */\nstatic cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)\n{\n    unsigned char *output_pointer = NULL;\n    size_t length = 0;\n    cJSON *current_item = item->child;\n\n    if (output_buffer == NULL)\n    {\n        return false;\n    }\n\n    /* Compose the output: */\n    length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\\n */\n    output_pointer = ensure(output_buffer, length + 1);\n    if (output_pointer == NULL)\n    {\n        return false;\n    }\n\n    *output_pointer++ = '{';\n    output_buffer->depth++;\n    if (output_buffer->format)\n    {\n        *output_pointer++ = '\\n';\n    }\n    output_buffer->offset += length;\n\n    while (current_item)\n    {\n        if (output_buffer->format)\n        {\n            size_t i;\n            output_pointer = ensure(output_buffer, output_buffer->depth);\n            if (output_pointer == NULL)\n            {\n                return false;\n            }\n            for (i = 0; i < output_buffer->depth; i++)\n            {\n                *output_pointer++ = '\\t';\n            }\n            output_buffer->offset += output_buffer->depth;\n        }\n\n        /* print key */\n        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))\n        {\n            return false;\n        }\n        update_offset(output_buffer);\n\n        length = (size_t) (output_buffer->format ? 2 : 1);\n        output_pointer = ensure(output_buffer, length);\n        if (output_pointer == NULL)\n        {\n            return false;\n        }\n        *output_pointer++ = ':';\n        if (output_buffer->format)\n        {\n            *output_pointer++ = '\\t';\n        }\n        output_buffer->offset += length;\n\n        /* print value */\n        if (!print_value(current_item, output_buffer))\n        {\n            return false;\n        }\n        update_offset(output_buffer);\n\n        /* print comma if not last */\n        length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0));\n        output_pointer = ensure(output_buffer, length + 1);\n        if (output_pointer == NULL)\n        {\n            return false;\n        }\n        if (current_item->next)\n        {\n            *output_pointer++ = ',';\n        }\n\n        if (output_buffer->format)\n        {\n            *output_pointer++ = '\\n';\n        }\n        *output_pointer = '\\0';\n        output_buffer->offset += length;\n\n        current_item = current_item->next;\n    }\n\n    output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);\n    if (output_pointer == NULL)\n    {\n        return false;\n    }\n    if (output_buffer->format)\n    {\n        size_t i;\n        for (i = 0; i < (output_buffer->depth - 1); i++)\n        {\n            *output_pointer++ = '\\t';\n        }\n    }\n    *output_pointer++ = '}';\n    *output_pointer = '\\0';\n    output_buffer->depth--;\n\n    return true;\n}\n\n/* Get Array size/item / object item. */\nCJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)\n{\n    cJSON *child = NULL;\n    size_t size = 0;\n\n    if (array == NULL)\n    {\n        return 0;\n    }\n\n    child = array->child;\n\n    while(child != NULL)\n    {\n        size++;\n        child = child->next;\n    }\n\n    /* FIXME: Can overflow here. Cannot be fixed without breaking the API */\n\n    return (int)size;\n}\n\nstatic cJSON* get_array_item(const cJSON *array, size_t index)\n{\n    cJSON *current_child = NULL;\n\n    if (array == NULL)\n    {\n        return NULL;\n    }\n\n    current_child = array->child;\n    while ((current_child != NULL) && (index > 0))\n    {\n        index--;\n        current_child = current_child->next;\n    }\n\n    return current_child;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)\n{\n    if (index < 0)\n    {\n        return NULL;\n    }\n\n    return get_array_item(array, (size_t)index);\n}\n\nstatic cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)\n{\n    cJSON *current_element = NULL;\n\n    if ((object == NULL) || (name == NULL))\n    {\n        return NULL;\n    }\n\n    current_element = object->child;\n    if (case_sensitive)\n    {\n        while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))\n        {\n            current_element = current_element->next;\n        }\n    }\n    else\n    {\n        while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))\n        {\n            current_element = current_element->next;\n        }\n    }\n\n    return current_element;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)\n{\n    return get_object_item(object, string, false);\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)\n{\n    return get_object_item(object, string, true);\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)\n{\n    return cJSON_GetObjectItem(object, string) ? 1 : 0;\n}\n\n/* Utility for array list handling. */\nstatic void suffix_object(cJSON *prev, cJSON *item)\n{\n    prev->next = item;\n    item->prev = prev;\n}\n\n/* Utility for handling references. */\nstatic cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)\n{\n    cJSON *reference = NULL;\n    if (item == NULL)\n    {\n        return NULL;\n    }\n\n    reference = cJSON_New_Item(hooks);\n    if (reference == NULL)\n    {\n        return NULL;\n    }\n\n    memcpy(reference, item, sizeof(cJSON));\n    reference->string = NULL;\n    reference->type |= cJSON_IsReference;\n    reference->next = reference->prev = NULL;\n    return reference;\n}\n\nstatic cJSON_bool add_item_to_array(cJSON *array, cJSON *item)\n{\n    cJSON *child = NULL;\n\n    if ((item == NULL) || (array == NULL))\n    {\n        return false;\n    }\n\n    child = array->child;\n\n    if (child == NULL)\n    {\n        /* list is empty, start new one */\n        array->child = item;\n    }\n    else\n    {\n        /* append to the end */\n        while (child->next)\n        {\n            child = child->next;\n        }\n        suffix_object(child, item);\n    }\n\n    return true;\n}\n\n/* Add item to array/object. */\nCJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)\n{\n    add_item_to_array(array, item);\n}\n\n#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))\n    #pragma GCC diagnostic push\n#endif\n#ifdef __GNUC__\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n#endif\n/* helper function to cast away const */\nstatic void* cast_away_const(const void* string)\n{\n    return (void*)string;\n}\n#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))\n    #pragma GCC diagnostic pop\n#endif\n\n\nstatic 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)\n{\n    char *new_key = NULL;\n    int new_type = cJSON_Invalid;\n\n    if ((object == NULL) || (string == NULL) || (item == NULL))\n    {\n        return false;\n    }\n\n    if (constant_key)\n    {\n        new_key = (char*)cast_away_const(string);\n        new_type = item->type | cJSON_StringIsConst;\n    }\n    else\n    {\n        new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);\n        if (new_key == NULL)\n        {\n            return false;\n        }\n\n        new_type = item->type & ~cJSON_StringIsConst;\n    }\n\n    if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))\n    {\n        hooks->deallocate(item->string);\n    }\n\n    item->string = new_key;\n    item->type = new_type;\n\n    return add_item_to_array(object, item);\n}\n\nCJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)\n{\n    add_item_to_object(object, string, item, &global_hooks, false);\n}\n\n/* Add an item to an object with constant string as key */\nCJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)\n{\n    add_item_to_object(object, string, item, &global_hooks, true);\n}\n\nCJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)\n{\n    if (array == NULL)\n    {\n        return;\n    }\n\n    add_item_to_array(array, create_reference(item, &global_hooks));\n}\n\nCJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)\n{\n    if ((object == NULL) || (string == NULL))\n    {\n        return;\n    }\n\n    add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)\n{\n    cJSON *null = cJSON_CreateNull();\n    if (add_item_to_object(object, name, null, &global_hooks, false))\n    {\n        return null;\n    }\n\n    cJSON_Delete(null);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)\n{\n    cJSON *true_item = cJSON_CreateTrue();\n    if (add_item_to_object(object, name, true_item, &global_hooks, false))\n    {\n        return true_item;\n    }\n\n    cJSON_Delete(true_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)\n{\n    cJSON *false_item = cJSON_CreateFalse();\n    if (add_item_to_object(object, name, false_item, &global_hooks, false))\n    {\n        return false_item;\n    }\n\n    cJSON_Delete(false_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)\n{\n    cJSON *bool_item = cJSON_CreateBool(boolean);\n    if (add_item_to_object(object, name, bool_item, &global_hooks, false))\n    {\n        return bool_item;\n    }\n\n    cJSON_Delete(bool_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)\n{\n    cJSON *number_item = cJSON_CreateNumber(number);\n    if (add_item_to_object(object, name, number_item, &global_hooks, false))\n    {\n        return number_item;\n    }\n\n    cJSON_Delete(number_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)\n{\n    cJSON *string_item = cJSON_CreateString(string);\n    if (add_item_to_object(object, name, string_item, &global_hooks, false))\n    {\n        return string_item;\n    }\n\n    cJSON_Delete(string_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)\n{\n    cJSON *raw_item = cJSON_CreateRaw(raw);\n    if (add_item_to_object(object, name, raw_item, &global_hooks, false))\n    {\n        return raw_item;\n    }\n\n    cJSON_Delete(raw_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)\n{\n    cJSON *object_item = cJSON_CreateObject();\n    if (add_item_to_object(object, name, object_item, &global_hooks, false))\n    {\n        return object_item;\n    }\n\n    cJSON_Delete(object_item);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)\n{\n    cJSON *array = cJSON_CreateArray();\n    if (add_item_to_object(object, name, array, &global_hooks, false))\n    {\n        return array;\n    }\n\n    cJSON_Delete(array);\n    return NULL;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)\n{\n    if ((parent == NULL) || (item == NULL))\n    {\n        return NULL;\n    }\n\n    if (item->prev != NULL)\n    {\n        /* not the first element */\n        item->prev->next = item->next;\n    }\n    if (item->next != NULL)\n    {\n        /* not the last element */\n        item->next->prev = item->prev;\n    }\n\n    if (item == parent->child)\n    {\n        /* first element */\n        parent->child = item->next;\n    }\n    /* make sure the detached item doesn't point anywhere anymore */\n    item->prev = NULL;\n    item->next = NULL;\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)\n{\n    if (which < 0)\n    {\n        return NULL;\n    }\n\n    return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));\n}\n\nCJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)\n{\n    cJSON_Delete(cJSON_DetachItemFromArray(array, which));\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)\n{\n    cJSON *to_detach = cJSON_GetObjectItem(object, string);\n\n    return cJSON_DetachItemViaPointer(object, to_detach);\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)\n{\n    cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);\n\n    return cJSON_DetachItemViaPointer(object, to_detach);\n}\n\nCJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)\n{\n    cJSON_Delete(cJSON_DetachItemFromObject(object, string));\n}\n\nCJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)\n{\n    cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));\n}\n\n/* Replace array/object items with new ones. */\nCJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)\n{\n    cJSON *after_inserted = NULL;\n\n    if (which < 0)\n    {\n        return;\n    }\n\n    after_inserted = get_array_item(array, (size_t)which);\n    if (after_inserted == NULL)\n    {\n        add_item_to_array(array, newitem);\n        return;\n    }\n\n    newitem->next = after_inserted;\n    newitem->prev = after_inserted->prev;\n    after_inserted->prev = newitem;\n    if (after_inserted == array->child)\n    {\n        array->child = newitem;\n    }\n    else\n    {\n        newitem->prev->next = newitem;\n    }\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)\n{\n    if ((parent == NULL) || (replacement == NULL) || (item == NULL))\n    {\n        return false;\n    }\n\n    if (replacement == item)\n    {\n        return true;\n    }\n\n    replacement->next = item->next;\n    replacement->prev = item->prev;\n\n    if (replacement->next != NULL)\n    {\n        replacement->next->prev = replacement;\n    }\n    if (replacement->prev != NULL)\n    {\n        replacement->prev->next = replacement;\n    }\n    if (parent->child == item)\n    {\n        parent->child = replacement;\n    }\n\n    item->next = NULL;\n    item->prev = NULL;\n    cJSON_Delete(item);\n\n    return true;\n}\n\nCJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)\n{\n    if (which < 0)\n    {\n        return;\n    }\n\n    cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);\n}\n\nstatic cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)\n{\n    if ((replacement == NULL) || (string == NULL))\n    {\n        return false;\n    }\n\n    /* replace the name in the replacement */\n    if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))\n    {\n        cJSON_free(replacement->string);\n    }\n    replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);\n    replacement->type &= ~cJSON_StringIsConst;\n\n    cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);\n\n    return true;\n}\n\nCJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)\n{\n    replace_item_in_object(object, string, newitem, false);\n}\n\nCJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)\n{\n    replace_item_in_object(object, string, newitem, true);\n}\n\n/* Create basic types: */\nCJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_NULL;\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_True;\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_False;\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = b ? cJSON_True : cJSON_False;\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_Number;\n        item->valuedouble = num;\n\n        /* use saturation in case of overflow */\n        if (num >= INT_MAX)\n        {\n            item->valueint = INT_MAX;\n        }\n        else if (num <= INT_MIN)\n        {\n            item->valueint = INT_MIN;\n        }\n        else\n        {\n            item->valueint = (int)num;\n        }\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_String;\n        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);\n        if(!item->valuestring)\n        {\n            cJSON_Delete(item);\n            return NULL;\n        }\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if (item != NULL)\n    {\n        item->type = cJSON_String | cJSON_IsReference;\n        item->valuestring = (char*)cast_away_const(string);\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if (item != NULL) {\n        item->type = cJSON_Object | cJSON_IsReference;\n        item->child = (cJSON*)cast_away_const(child);\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if (item != NULL) {\n        item->type = cJSON_Array | cJSON_IsReference;\n        item->child = (cJSON*)cast_away_const(child);\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type = cJSON_Raw;\n        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);\n        if(!item->valuestring)\n        {\n            cJSON_Delete(item);\n            return NULL;\n        }\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if(item)\n    {\n        item->type=cJSON_Array;\n    }\n\n    return item;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)\n{\n    cJSON *item = cJSON_New_Item(&global_hooks);\n    if (item)\n    {\n        item->type = cJSON_Object;\n    }\n\n    return item;\n}\n\n/* Create Arrays: */\nCJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)\n{\n    size_t i = 0;\n    cJSON *n = NULL;\n    cJSON *p = NULL;\n    cJSON *a = NULL;\n\n    if ((count < 0) || (numbers == NULL))\n    {\n        return NULL;\n    }\n\n    a = cJSON_CreateArray();\n    for(i = 0; a && (i < (size_t)count); i++)\n    {\n        n = cJSON_CreateNumber(numbers[i]);\n        if (!n)\n        {\n            cJSON_Delete(a);\n            return NULL;\n        }\n        if(!i)\n        {\n            a->child = n;\n        }\n        else\n        {\n            suffix_object(p, n);\n        }\n        p = n;\n    }\n\n    return a;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)\n{\n    size_t i = 0;\n    cJSON *n = NULL;\n    cJSON *p = NULL;\n    cJSON *a = NULL;\n\n    if ((count < 0) || (numbers == NULL))\n    {\n        return NULL;\n    }\n\n    a = cJSON_CreateArray();\n\n    for(i = 0; a && (i < (size_t)count); i++)\n    {\n        n = cJSON_CreateNumber((double)numbers[i]);\n        if(!n)\n        {\n            cJSON_Delete(a);\n            return NULL;\n        }\n        if(!i)\n        {\n            a->child = n;\n        }\n        else\n        {\n            suffix_object(p, n);\n        }\n        p = n;\n    }\n\n    return a;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)\n{\n    size_t i = 0;\n    cJSON *n = NULL;\n    cJSON *p = NULL;\n    cJSON *a = NULL;\n\n    if ((count < 0) || (numbers == NULL))\n    {\n        return NULL;\n    }\n\n    a = cJSON_CreateArray();\n\n    for(i = 0;a && (i < (size_t)count); i++)\n    {\n        n = cJSON_CreateNumber(numbers[i]);\n        if(!n)\n        {\n            cJSON_Delete(a);\n            return NULL;\n        }\n        if(!i)\n        {\n            a->child = n;\n        }\n        else\n        {\n            suffix_object(p, n);\n        }\n        p = n;\n    }\n\n    return a;\n}\n\nCJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)\n{\n    size_t i = 0;\n    cJSON *n = NULL;\n    cJSON *p = NULL;\n    cJSON *a = NULL;\n\n    if ((count < 0) || (strings == NULL))\n    {\n        return NULL;\n    }\n\n    a = cJSON_CreateArray();\n\n    for (i = 0; a && (i < (size_t)count); i++)\n    {\n        n = cJSON_CreateString(strings[i]);\n        if(!n)\n        {\n            cJSON_Delete(a);\n            return NULL;\n        }\n        if(!i)\n        {\n            a->child = n;\n        }\n        else\n        {\n            suffix_object(p,n);\n        }\n        p = n;\n    }\n\n    return a;\n}\n\n/* Duplication */\nCJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)\n{\n    cJSON *newitem = NULL;\n    cJSON *child = NULL;\n    cJSON *next = NULL;\n    cJSON *newchild = NULL;\n\n    /* Bail on bad ptr */\n    if (!item)\n    {\n        goto fail;\n    }\n    /* Create new item */\n    newitem = cJSON_New_Item(&global_hooks);\n    if (!newitem)\n    {\n        goto fail;\n    }\n    /* Copy over all vars */\n    newitem->type = item->type & (~cJSON_IsReference);\n    newitem->valueint = item->valueint;\n    newitem->valuedouble = item->valuedouble;\n    if (item->valuestring)\n    {\n        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);\n        if (!newitem->valuestring)\n        {\n            goto fail;\n        }\n    }\n    if (item->string)\n    {\n        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);\n        if (!newitem->string)\n        {\n            goto fail;\n        }\n    }\n    /* If non-recursive, then we're done! */\n    if (!recurse)\n    {\n        return newitem;\n    }\n    /* Walk the ->next chain for the child. */\n    child = item->child;\n    while (child != NULL)\n    {\n        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */\n        if (!newchild)\n        {\n            goto fail;\n        }\n        if (next != NULL)\n        {\n            /* If newitem->child already set, then crosswire ->prev and ->next and move on */\n            next->next = newchild;\n            newchild->prev = next;\n            next = newchild;\n        }\n        else\n        {\n            /* Set newitem->child and move to it */\n            newitem->child = newchild;\n            next = newchild;\n        }\n        child = child->next;\n    }\n\n    return newitem;\n\nfail:\n    if (newitem != NULL)\n    {\n        cJSON_Delete(newitem);\n    }\n\n    return NULL;\n}\n\nCJSON_PUBLIC(void) cJSON_Minify(char *json)\n{\n    unsigned char *into = (unsigned char*)json;\n\n    if (json == NULL)\n    {\n        return;\n    }\n\n    while (*json)\n    {\n        if (*json == ' ')\n        {\n            json++;\n        }\n        else if (*json == '\\t')\n        {\n            /* Whitespace characters. */\n            json++;\n        }\n        else if (*json == '\\r')\n        {\n            json++;\n        }\n        else if (*json=='\\n')\n        {\n            json++;\n        }\n        else if ((*json == '/') && (json[1] == '/'))\n        {\n            /* double-slash comments, to end of line. */\n            while (*json && (*json != '\\n'))\n            {\n                json++;\n            }\n        }\n        else if ((*json == '/') && (json[1] == '*'))\n        {\n            /* multiline comments. */\n            while (*json && !((*json == '*') && (json[1] == '/')))\n            {\n                json++;\n            }\n            json += 2;\n        }\n        else if (*json == '\\\"')\n        {\n            /* string literals, which are \\\" sensitive. */\n            *into++ = (unsigned char)*json++;\n            while (*json && (*json != '\\\"'))\n            {\n                if (*json == '\\\\')\n                {\n                    *into++ = (unsigned char)*json++;\n                }\n                *into++ = (unsigned char)*json++;\n            }\n            *into++ = (unsigned char)*json++;\n        }\n        else\n        {\n            /* All other characters. */\n            *into++ = (unsigned char)*json++;\n        }\n    }\n\n    /* and null-terminate. */\n    *into = '\\0';\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_Invalid;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_False;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xff) == cJSON_True;\n}\n\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & (cJSON_True | cJSON_False)) != 0;\n}\nCJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_NULL;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_Number;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_String;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_Array;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_Object;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)\n{\n    if (item == NULL)\n    {\n        return false;\n    }\n\n    return (item->type & 0xFF) == cJSON_Raw;\n}\n\nCJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)\n{\n    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))\n    {\n        return false;\n    }\n\n    /* check if type is valid */\n    switch (a->type & 0xFF)\n    {\n        case cJSON_False:\n        case cJSON_True:\n        case cJSON_NULL:\n        case cJSON_Number:\n        case cJSON_String:\n        case cJSON_Raw:\n        case cJSON_Array:\n        case cJSON_Object:\n            break;\n\n        default:\n            return false;\n    }\n\n    /* identical objects are equal */\n    if (a == b)\n    {\n        return true;\n    }\n\n    switch (a->type & 0xFF)\n    {\n        /* in these cases and equal type is enough */\n        case cJSON_False:\n        case cJSON_True:\n        case cJSON_NULL:\n            return true;\n\n        case cJSON_Number:\n            if (a->valuedouble == b->valuedouble)\n            {\n                return true;\n            }\n            return false;\n\n        case cJSON_String:\n        case cJSON_Raw:\n            if ((a->valuestring == NULL) || (b->valuestring == NULL))\n            {\n                return false;\n            }\n            if (strcmp(a->valuestring, b->valuestring) == 0)\n            {\n                return true;\n            }\n\n            return false;\n\n        case cJSON_Array:\n        {\n            cJSON *a_element = a->child;\n            cJSON *b_element = b->child;\n\n            for (; (a_element != NULL) && (b_element != NULL);)\n            {\n                if (!cJSON_Compare(a_element, b_element, case_sensitive))\n                {\n                    return false;\n                }\n\n                a_element = a_element->next;\n                b_element = b_element->next;\n            }\n\n            /* one of the arrays is longer than the other */\n            if (a_element != b_element) {\n                return false;\n            }\n\n            return true;\n        }\n\n        case cJSON_Object:\n        {\n            cJSON *a_element = NULL;\n            cJSON *b_element = NULL;\n            cJSON_ArrayForEach(a_element, a)\n            {\n                /* TODO This has O(n^2) runtime, which is horrible! */\n                b_element = get_object_item(b, a_element->string, case_sensitive);\n                if (b_element == NULL)\n                {\n                    return false;\n                }\n\n                if (!cJSON_Compare(a_element, b_element, case_sensitive))\n                {\n                    return false;\n                }\n            }\n\n            /* doing this twice, once on a and b to prevent true comparison if a subset of b\n             * TODO: Do this the proper way, this is just a fix for now */\n            cJSON_ArrayForEach(b_element, b)\n            {\n                a_element = get_object_item(a, b_element->string, case_sensitive);\n                if (a_element == NULL)\n                {\n                    return false;\n                }\n\n                if (!cJSON_Compare(b_element, a_element, case_sensitive))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        default:\n            return false;\n    }\n}\n\nCJSON_PUBLIC(void *) cJSON_malloc(size_t size)\n{\n    return global_hooks.allocate(size);\n}\n\nCJSON_PUBLIC(void) cJSON_free(void *object)\n{\n    global_hooks.deallocate(object);\n}\n"
  },
  {
    "path": "src/cJSON.h",
    "content": "/*\n  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to deal\n  in the Software without restriction, including without limitation the rights\n  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n  copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n  THE SOFTWARE.\n*/\n\n#ifndef cJSON__h\n#define cJSON__h\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/* project version */\n#define CJSON_VERSION_MAJOR 1\n#define CJSON_VERSION_MINOR 7\n#define CJSON_VERSION_PATCH 6\n\n#include <stddef.h>\n\n/* cJSON Types: */\n#define cJSON_Invalid (0)\n#define cJSON_False  (1 << 0)\n#define cJSON_True   (1 << 1)\n#define cJSON_NULL   (1 << 2)\n#define cJSON_Number (1 << 3)\n#define cJSON_String (1 << 4)\n#define cJSON_Array  (1 << 5)\n#define cJSON_Object (1 << 6)\n#define cJSON_Raw    (1 << 7) /* raw json */\n\n#define cJSON_IsReference 256\n#define cJSON_StringIsConst 512\n\n/* The cJSON structure: */\ntypedef struct cJSON\n{\n    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */\n    struct cJSON *next;\n    struct cJSON *prev;\n    /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */\n    struct cJSON *child;\n\n    /* The type of the item, as above. */\n    int type;\n\n    /* The item's string, if type==cJSON_String  and type == cJSON_Raw */\n    char *valuestring;\n    /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */\n    int valueint;\n    /* The item's number, if type==cJSON_Number */\n    double valuedouble;\n\n    /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */\n    char *string;\n} cJSON;\n\ntypedef struct cJSON_Hooks\n{\n      void *(*malloc_fn)(size_t sz);\n      void (*free_fn)(void *ptr);\n} cJSON_Hooks;\n\ntypedef int cJSON_bool;\n\n#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))\n#define __WINDOWS__\n#endif\n#ifdef __WINDOWS__\n\n/* 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:\n\nCJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols\nCJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)\nCJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol\n\nFor *nix builds that support visibility attribute, you can define similar behavior by\n\nsetting default visibility to hidden by adding\n-fvisibility=hidden (for gcc)\nor\n-xldscope=hidden (for sun cc)\nto CFLAGS\n\nthen using the CJSON_API_VISIBILITY flag to \"export\" the same symbols the way CJSON_EXPORT_SYMBOLS does\n\n*/\n\n/* export symbols by default, this is necessary for copy pasting the C and header file */\n#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)\n#define CJSON_EXPORT_SYMBOLS\n#endif\n\n#if defined(CJSON_HIDE_SYMBOLS)\n#define CJSON_PUBLIC(type)   type __stdcall\n#elif defined(CJSON_EXPORT_SYMBOLS)\n#define CJSON_PUBLIC(type)   __declspec(dllexport) type __stdcall\n#elif defined(CJSON_IMPORT_SYMBOLS)\n#define CJSON_PUBLIC(type)   __declspec(dllimport) type __stdcall\n#endif\n#else /* !WIN32 */\n#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)\n#define CJSON_PUBLIC(type)   __attribute__((visibility(\"default\"))) type\n#else\n#define CJSON_PUBLIC(type) type\n#endif\n#endif\n\n/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.\n * This is to prevent stack overflows. */\n#ifndef CJSON_NESTING_LIMIT\n#define CJSON_NESTING_LIMIT 1000\n#endif\n\n/* returns the version of cJSON as a string */\nCJSON_PUBLIC(const char*) cJSON_Version(void);\n\n/* Supply malloc, realloc and free functions to cJSON */\nCJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);\n\n/* 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. */\n/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */\nCJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);\n/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */\n/* 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(). */\nCJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);\n\n/* Render a cJSON entity to text for transfer/storage. */\nCJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);\n/* Render a cJSON entity to text for transfer/storage without any formatting. */\nCJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);\n/* 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 */\nCJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);\n/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */\n/* 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 */\nCJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);\n/* Delete a cJSON entity and all subentities. */\nCJSON_PUBLIC(void) cJSON_Delete(cJSON *c);\n\n/* Returns the number of items in an array (or object). */\nCJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);\n/* Retrieve item number \"item\" from array \"array\". Returns NULL if unsuccessful. */\nCJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);\n/* Get item \"string\" from object. Case insensitive. */\nCJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);\nCJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);\nCJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);\n/* 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. */\nCJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);\n\n/* Check if the item is a string and return its valuestring */\nCJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);\n\n/* These functions check the type of an item */\nCJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);\nCJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);\n\n/* These calls create a cJSON item of the appropriate type. */\nCJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);\nCJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);\nCJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);\nCJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);\nCJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);\nCJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);\n/* raw json */\nCJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);\nCJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);\nCJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);\n\n/* Create a string where valuestring references a string so\n * it will not be freed by cJSON_Delete */\nCJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);\n/* Create an object/arrray that only references it's elements so\n * they will not be freed by cJSON_Delete */\nCJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);\nCJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);\n\n/* These utilities create an Array of count items. */\nCJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);\nCJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);\nCJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);\nCJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);\n\n/* Append item to the specified array/object. */\nCJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);\nCJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);\n/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.\n * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before\n * writing to `item->string` */\nCJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);\n/* 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. */\nCJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);\nCJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);\n\n/* Remove/Detatch items from Arrays/Objects. */\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);\nCJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);\nCJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);\nCJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);\nCJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);\n\n/* Update array items. */\nCJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */\nCJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);\nCJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);\nCJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);\nCJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);\n\n/* Duplicate a cJSON item */\nCJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);\n/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will\nneed to be released. With recurse!=0, it will duplicate any children connected to the item.\nThe item->next and ->prev pointers are always zero on return from Duplicate. */\n/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.\n * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */\nCJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);\n\n\nCJSON_PUBLIC(void) cJSON_Minify(char *json);\n\n/* Helper functions for creating and adding items to an object at the same time.\n * They return the added item or NULL on failure. */\nCJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);\nCJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);\nCJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);\nCJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);\nCJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);\nCJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);\nCJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);\nCJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);\nCJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);\n\n/* When assigning an integer value, it needs to be propagated to valuedouble too. */\n#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))\n/* helper for the cJSON_SetNumberValue macro */\nCJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);\n#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))\n\n/* Macro for iterating over an array or object */\n#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)\n\n/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */\nCJSON_PUBLIC(void *) cJSON_malloc(size_t size);\nCJSON_PUBLIC(void) cJSON_free(void *object);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "src/elf2kip.c",
    "content": "// Copyright 2018 SciresM\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <errno.h>\n#include <limits.h>\n#include \"cJSON.h\"\n#include \"blz.h\"\n#include \"elf64.h\"\n\ntypedef struct {\n    u32 DstOff;\n    u32 DecompSz;\n    u32 CompSz;\n    u32 Attribute;\n} KipSegment;\n\ntypedef struct {\n    u8  Magic[4];\n    u8  Name[0xC];\n    u64 ProgramId;\n    u32 Version;\n    u8  MainThreadPriority;\n    u8  DefaultCpuId;\n    u8  Unk;\n    u8  Flags;\n    KipSegment Segments[6];\n    u32 Capabilities[0x20];\n} KipHeader;\n\nuint8_t* ReadEntireFile(const char* fn, size_t* len_out) {\n    FILE* fd = fopen(fn, \"rb\");\n    if (fd == NULL)\n        return NULL;\n\n    fseek(fd, 0, SEEK_END);\n    size_t len = ftell(fd);\n    fseek(fd, 0, SEEK_SET);\n\n    uint8_t* buf = malloc(len);\n    if (buf == NULL) {\n        fclose(fd);\n        return NULL;\n    }\n\n    size_t rc = fread(buf, 1, len, fd);\n    if (rc != len) {\n        fclose(fd);\n        free(buf);\n        return NULL;\n    }\n\n    *len_out = len;\n    return buf;\n}\n\nint cJSON_GetString(const cJSON *obj, const char *field, const char **out) {\n  const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n  if (cJSON_IsString(config)) {\n    *out = config->valuestring;\n    return 1;\n  } else {\n    fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n    return 0;\n  }\n}\n\nint cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsNumber(config)) {\n        *out = (u8)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsNumber(config)) {\n        *out = (u16)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {\n    if (cJSON_IsNumber(config)) {\n        *out = (u16)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", config->string);\n        return 0;\n    }\n}\n\nint cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsBool(config)) {\n        if (cJSON_IsTrue(config)) {\n            *out = 1;\n        } else if (cJSON_IsFalse(config)) {\n            *out = 0;\n        } else {\n            fprintf(stderr, \"Unknown boolean value in %s.\\n\", field);\n            return 0;\n        }\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsBool(config)) {\n        if (cJSON_IsTrue(config)) {\n            *out = 1;\n        } else if (cJSON_IsFalse(config)) {\n            *out = 0;\n        } else {\n            fprintf(stderr, \"Unknown boolean value in %s.\\n\", field);\n            return 0;\n        }\n        return 1;\n    } else {\n        *out = 0;\n        return 0;\n    }\n}\n\nint cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoull(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", field);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", field);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", field);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", field);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoull(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", config->string);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", config->string);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", config->string);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", config->string);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", config->string);\n        return 0;\n    }\n}\n\nint cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoul(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", field);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", field);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", field);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", field);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint ParseKipConfiguration(const char *json, KipHeader *kip_hdr) {\n    const cJSON *capability = NULL;\n    const cJSON *capabilities = NULL;\n    int status = 0;\n    cJSON *npdm_json = cJSON_Parse(json);\n    if (npdm_json == NULL) {\n        const char *error_ptr = cJSON_GetErrorPtr();\n        if (error_ptr != NULL) {\n            fprintf(stderr, \"JSON Parse Error: %s\\n\", error_ptr);\n        }\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n\n    /* Parse name. */\n    const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, \"name\");\n    if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {\n        strncpy(kip_hdr->Name, title_name->valuestring, sizeof(kip_hdr->Name) - 1);\n    } else {\n        fprintf(stderr, \"Failed to get title name (name field not present).\\n\");\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n\n    /* Parse program_id (or deprecated title_id). */\n    if (!cJSON_GetU64(npdm_json, \"program_id\", &kip_hdr->ProgramId) && !cJSON_GetU64(npdm_json, \"title_id\", &kip_hdr->ProgramId)) {\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n\n    /* Parse use secure memory. */\n    /* This field is optional, and defaults to true (set before this function is called). */\n    int use_secure_memory = 1;\n    if (cJSON_GetBooleanOptional(npdm_json, \"use_secure_memory\", &use_secure_memory)) {\n        if (use_secure_memory) {\n            kip_hdr->Flags |= 0x20;\n        } else {\n            kip_hdr->Flags &= ~0x20;\n        }\n    }\n\n    /* Parse immortality. */\n    /* This field is optional, and defaults to true (set before this function is called). */\n    int immortal = 1;\n    if (cJSON_GetBooleanOptional(npdm_json, \"immortal\", &immortal)) {\n        if (immortal) {\n            kip_hdr->Flags |= 0x40;\n        } else {\n            kip_hdr->Flags &= ~0x40;\n        }\n    }\n\n    /* Parse main_thread_stack_size. */\n    u64 stack_size = 0;\n    if (!cJSON_GetU64(npdm_json, \"main_thread_stack_size\", &stack_size)) {\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n    if (stack_size >> 32) {\n        fprintf(stderr, \"Error: Main thread stack size must be a u32!\\n\");\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n    kip_hdr->Segments[1].Attribute = (u32)(stack_size & 0xFFFFFFFF);\n\n    /* Parse various config. */\n    if (!cJSON_GetU8(npdm_json, \"main_thread_priority\", &kip_hdr->MainThreadPriority)) {\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n    if (!cJSON_GetU8(npdm_json, \"default_cpu_id\", &kip_hdr->DefaultCpuId)) {\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n    if (!cJSON_GetU32(npdm_json, \"version\", &kip_hdr->Version) && !cJSON_GetU32(npdm_json, \"process_category\", &kip_hdr->Version)) { // optional\n        kip_hdr->Version = 1;\n    }\n\n    /* Parse capabilities. */\n    capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, \"kernel_capabilities\");\n    if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {\n        fprintf(stderr, \"Kernel Capabilities must be an array!\\n\");\n        status = 0;\n        goto PARSE_CAPS_END;\n    }\n\n    int kac_obj = 0;\n    if (cJSON_IsObject(capabilities)) {\n        kac_obj = 1;\n        fprintf(stderr, \"Using deprecated kernel_capabilities format. Please turn it into an array.\\n\");\n    }\n\n    u32 cur_cap = 0;\n    u32 desc;\n    cJSON_ArrayForEach(capability, capabilities) {\n        desc = 0;\n        const char *type_str;\n        const cJSON *value;\n\n        if (kac_obj) {\n            type_str = capability->string;\n            value = capability;\n        } else {\n            if (!cJSON_GetString(capability, \"type\", &type_str)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            value = cJSON_GetObjectItemCaseSensitive(capability, \"value\");\n        }\n\n\n        if (!strcmp(type_str, \"kernel_flags\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Kernel Flags Capability value must be object!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;\n            if (!cJSON_GetU8(value, \"highest_thread_priority\", &highest_prio) ||\n                !cJSON_GetU8(value, \"lowest_thread_priority\", &lowest_prio) ||\n                !cJSON_GetU8(value, \"highest_cpu_id\", &highest_cpu) ||\n                !cJSON_GetU8(value, \"lowest_cpu_id\", &lowest_cpu)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n\n            u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;\n            u8 real_lowest_prio  = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;\n\n            desc = highest_cpu;\n            desc <<= 8;\n            desc |= lowest_cpu;\n            desc <<= 6;\n            desc |= (real_highest_prio & 0x3F);\n            desc <<= 6;\n            desc |= (real_lowest_prio & 0x3F);\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 4) | (0x0007));\n        } else if (!strcmp(type_str, \"syscalls\")) {\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Syscalls Capability value must be object!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u32 num_descriptors;\n            u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */\n            char field_name[8] = {0};\n            const cJSON *cur_syscall = NULL;\n            u64 syscall_value = 0;\n            cJSON_ArrayForEach(cur_syscall, value) {\n                if (cJSON_IsNumber(cur_syscall)) {\n                    syscall_value = (u64)cur_syscall->valueint;\n                } else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {\n                    fprintf(stderr, \"Error: Syscall entries must be integers or hex strings.\\n\");\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n\n                if (syscall_value >= 0xC0) {\n                    fprintf(stderr, \"Error: All syscall entries must be numbers in [0, 0xBF]\\n\");\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n                descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));\n            }\n            for (unsigned int i = 0; i < 8; i++) {\n                if (descriptors[i]) {\n                    if (cur_cap + 1 > 0x20) {\n                        fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                        status = 0;\n                        goto PARSE_CAPS_END;\n                    }\n                    desc = descriptors[i] | (i << 24);\n                    kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 5) | (0x000F));\n                }\n            }\n        } else if (!strcmp(type_str, \"map\")) {\n            if (cur_cap + 2 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Map Capability value must be object!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u64 map_address = 0;\n            u64 map_size = 0;\n            int is_ro;\n            int is_io;\n            if (!cJSON_GetU64(value, \"address\", &map_address) ||\n                !cJSON_GetU64(value, \"size\", &map_size) ||\n                !cJSON_GetBoolean(value, \"is_ro\", &is_ro) ||\n                !cJSON_GetBoolean(value, \"is_io\", &is_io)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);\n            desc |= is_ro << 24;\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));\n\n            desc = (u32)((map_size >> 12) & 0x000FFFFFULL);\n            desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);\n            is_io ^= 1;\n            desc |= is_io << 24;\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));\n        } else if (!strcmp(type_str, \"map_page\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u64 page_address = 0;\n            if (!cJSON_GetU64FromObjectValue(value, &page_address)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 8) | (0x007F));\n        } else if (!strcmp(type_str, \"map_region\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_IsArray(value)) {\n                fprintf(stderr, \"Map Region capability value must be array!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u8 regions[3] = {0};\n            int is_ro[3] = {0};\n            const cJSON *cur_region = NULL;\n            int index = 0;\n            cJSON_ArrayForEach(cur_region, value) {\n                if (index >= 3) {\n                    fprintf(stderr, \"Too many region descriptors!\\n\");\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n                if (!cJSON_IsObject(cur_region)) {\n                    fprintf(stderr, \"Region descriptor value must be object!\\n\");\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n\n                if (!cJSON_GetU8(cur_region, \"region_type\", &regions[index]) ||\n                    !cJSON_GetBoolean(cur_region, \"is_ro\", &is_ro[index])) {\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n\n                index++;\n            }\n\n            u32 capability = 0x3FF;\n            for (int i = 0; i < 3; ++i) {\n                capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);\n            }\n            kip_hdr->Capabilities[cur_cap++] = capability;\n        } else if (!strcmp(type_str, \"irq_pair\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {\n                fprintf(stderr, \"Error: IRQ Pairs must have size 2 array value.\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            const cJSON *irq = NULL;\n            int desc_idx = 0;\n            cJSON_ArrayForEach(irq, value) {\n                if (cJSON_IsNull(irq)) {\n                    desc |= 0x3FF << desc_idx;\n                } else if (cJSON_IsNumber(irq)) {\n                    desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;\n                } else {\n                    fprintf(stderr, \"Failed to parse IRQ value.\\n\");\n                    status = 0;\n                    goto PARSE_CAPS_END;\n                }\n                desc_idx += 10;\n            }\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 12) | (0x07FF));\n        } else if (!strcmp(type_str, \"application_type\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            desc &= 7;\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 14) | (0x1FFF));\n        } else if (!strcmp(type_str, \"min_kernel_version\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            u64 kern_ver = 0;\n            if (cJSON_IsNumber(value)) {\n                kern_ver = (u64)value->valueint;\n            } else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {\n                fprintf(stderr, \"Error: Kernel version must be integer or hex strings.\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            desc = (kern_ver) & 0xFFFF;\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 15) | (0x3FFF));\n        } else if (!strcmp(type_str, \"handle_table_size\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 16) | (0x7FFF));\n        } else if (!strcmp(type_str, \"debug_flags\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Debug Flag Capability value must be object!\\n\");\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            int allow_debug = 0;\n            int force_debug = 0;\n            int force_debug_prod = 0;\n            if (!cJSON_GetBoolean(value, \"allow_debug\", &allow_debug)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_GetBoolean(value, \"force_debug\", &force_debug)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            if (!cJSON_GetBoolean(value, \"force_debug_prod\", &force_debug_prod)) {\n                status = 0;\n                goto PARSE_CAPS_END;\n            }\n            desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);\n            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 17) | (0xFFFF));\n        } else {\n            fprintf(stderr, \"Error: unknown capability %s\\n\", type_str);\n            status = 0;\n            goto PARSE_CAPS_END;\n        }\n    }\n\n    for (u32 i = cur_cap; i < 0x20; i++) {\n        kip_hdr->Capabilities[i] = 0xFFFFFFFF;\n    }\n\n    status = 1;\n    PARSE_CAPS_END:\n    cJSON_Delete(npdm_json);\n    return status;\n}\n\nint main(int argc, char* argv[]) {\n    if (argc != 4) {\n        fprintf(stderr, \"%s <elf-file> <json-file> <kip-file>\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n\n    KipHeader kip_hdr = {0};\n    memcpy(kip_hdr.Magic, \"KIP1\", 4);\n    kip_hdr.Flags = 0x7F;\n\n    if (sizeof(KipHeader) != 0x100) {\n        fprintf(stderr, \"Bad compile environment!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    size_t json_len;\n    uint8_t* json = ReadEntireFile(argv[2], &json_len);\n    if (json == NULL) {\n        fprintf(stderr, \"Failed to read descriptor json!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    if (!ParseKipConfiguration(json, &kip_hdr)) {\n        fprintf(stderr, \"Failed to parse kip configuration!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    size_t elf_len;\n    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);\n    if (elf == NULL) {\n        fprintf(stderr, \"Failed to open input!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    if (elf_len < sizeof(Elf64_Ehdr)) {\n        fprintf(stderr, \"Input file doesn't fit ELF header!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;\n    if (hdr->e_machine != EM_AARCH64) {\n        fprintf(stderr, \"Invalid ELF: expected AArch64!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);\n\n    if (ph_end < hdr->e_phoff || ph_end > elf_len) {\n        fprintf(stderr, \"Invalid ELF: phdrs outside file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];\n    size_t i, j = 0;\n    size_t file_off = 0;\n    size_t dst_off = 0;\n    size_t tmpsize;\n\n    uint8_t* buf[3];\n    uint8_t* cmp[3];\n    size_t FileOffsets[3];\n\n    for (i=0; i<4; i++) {\n        Elf64_Phdr* phdr = NULL;\n        while (j < hdr->e_phnum) {\n            Elf64_Phdr* cur = &phdrs[j];\n            if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;\n            if (cur->p_type == PT_LOAD || i == 3) {\n                phdr = cur;\n                break;\n            }\n        }\n\n        if (phdr == NULL) {\n            fprintf(stderr, \"Invalid ELF: expected 3 loadable phdrs and a bss!\\n\");\n            return EXIT_FAILURE;\n        }\n\n\n        kip_hdr.Segments[i].DstOff = dst_off;\n\n        // .bss is special\n        if (i == 3) {\n            tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;\n            if ( phdr->p_memsz > tmpsize) {\n                kip_hdr.Segments[i].DecompSz = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;\n            } else {\n                kip_hdr.Segments[i].DecompSz = 0;\n            }\n            kip_hdr.Segments[i].CompSz = 0;\n            break;\n        }\n\n        FileOffsets[i] = file_off;\n        kip_hdr.Segments[i].DecompSz = phdr->p_filesz;\n        buf[i] = malloc(kip_hdr.Segments[i].DecompSz);\n\n        if (buf[i] == NULL) {\n            fprintf(stderr, \"Out of memory!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        memset(buf[i], 0, kip_hdr.Segments[i].DecompSz);\n\n        memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);\n        cmp[i] = BLZ_Code(buf[i], phdr->p_filesz, &kip_hdr.Segments[i].CompSz, BLZ_BEST);\n\n        file_off += kip_hdr.Segments[i].CompSz;\n        dst_off += kip_hdr.Segments[i].DecompSz;\n        dst_off = (dst_off + 0xFFF) & ~0xFFF;\n    }\n\n    FILE* out = fopen(argv[3], \"wb\");\n\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to open output file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    // TODO check retvals\n\n    for (i=0; i<3; i++)\n    {\n        fseek(out, sizeof(kip_hdr) + FileOffsets[i], SEEK_SET);\n        fwrite(cmp[i], kip_hdr.Segments[i].CompSz, 1, out);\n    }\n\n    fseek(out, 0, SEEK_SET);\n    fwrite(&kip_hdr, sizeof(kip_hdr), 1, out);\n\n    fclose(out);\n    return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/elf2nro.c",
    "content": "// Copyright 2017 plutoo\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <lz4.h>\n#include \"sha256.h\"\n#include \"elf64.h\"\n#include \"romfs.h\"\n\ntypedef struct {\n    u32 FileOff;\n    u32 Size;\n} NsoSegment;\n\ntypedef struct {\n    u32 unused;\n    u32 modOffset;\n    u8 Padding[8];\n} NroStart;\n\ntypedef struct {\n    u8  Magic[4];\n    u32 version;\n    u32 size;\n    u32 flags;\n    NsoSegment Segments[3];\n    u32 bssSize;\n    u32 Unk3;\n    u8  BuildId[0x20];\n    u8  Padding[0x20];\n} NroHeader;\n\ntypedef struct {\n    u64 offset;\n    u64 size;\n} AssetSection;\n\ntypedef struct {\n    u8  magic[4];\n    u32 version;\n    AssetSection icon;\n    AssetSection nacp;\n    AssetSection romfs;\n} AssetHeader;\n\nuint8_t* ReadEntireFile(const char* fn, size_t* len_out) {\n    FILE* fd = fopen(fn, \"rb\");\n    if (fd == NULL)\n        return NULL;\n\n    fseek(fd, 0, SEEK_END);\n    size_t len = ftell(fd);\n    fseek(fd, 0, SEEK_SET);\n\n    uint8_t* buf = malloc(len);\n    if (buf == NULL) {\n        fclose(fd);\n        return NULL;\n    }\n\n    size_t rc = fread(buf, 1, len, fd);\n    if (rc != len) {\n        fclose(fd);\n        free(buf);\n        return NULL;\n    }\n\n    *len_out = len;\n    return buf;\n}\n\nint main(int argc, char* argv[]) {\n    if (argc < 3) {\n        fprintf(stderr, \"%s <elf-file> <nro-file> [options]\\n\\n\", argv[0]);\n        fprintf(stderr, \"Options:\\n\");\n        fprintf(stderr, \"--icon=<iconpath> Embeds icon into the output file.\\n\");\n        fprintf(stderr, \"--nacp=<control.nacp> Embeds control.nacp into the output file.\\n\");\n        fprintf(stderr, \"--romfs=<image> Embeds RomFS into the output file.\\n\");\n        fprintf(stderr, \"--romfsdir=<directory> Builds and embeds RomFS into the output file.\\n\");\n        fprintf(stderr, \"--alignedheader Sets the \\\"AlignedHeader\\\" flag in the output file.\\n\");\n        return EXIT_FAILURE;\n    }\n\n    NroStart nro_start;\n    memset(&nro_start, 0, sizeof(nro_start));\n\n    NroHeader nro_hdr;\n    memset(&nro_hdr, 0, sizeof(nro_hdr));\n    memcpy(nro_hdr.Magic, \"NRO0\", 4);\n\n    if (sizeof(NroHeader) != 0x70) {\n        fprintf(stderr, \"Bad compile environment!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    size_t elf_len;\n    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);\n    if (elf == NULL) {\n        fprintf(stderr, \"Failed to open input!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    int argi;\n    char* icon_path = NULL, *nacp_path = NULL, *romfs_path = NULL, *romfs_dir_path = NULL;\n    u32 aligned_header = 0;\n    for (argi=3; argi<argc; argi++) {\n        if (strncmp(argv[argi], \"--icon=\", 7)==0) icon_path = &argv[argi][7];\n        if (strncmp(argv[argi], \"--nacp=\", 7)==0) nacp_path = &argv[argi][7];\n        if (strncmp(argv[argi], \"--romfs=\", 8)==0) romfs_path = &argv[argi][8];\n        if (strncmp(argv[argi], \"--romfsdir=\", 11)==0) romfs_dir_path = &argv[argi][11];\n        if (strncmp(argv[argi], \"--alignedheader\", 15)==0) aligned_header = 1;\n    }\n\n    if (romfs_dir_path != NULL && romfs_path != NULL) {\n        fprintf(stderr, \"Cannot have a RomFS and a RomFS Directory at the same time!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    if (elf_len < sizeof(Elf64_Ehdr)) {\n        fprintf(stderr, \"Input file doesn't fit ELF header!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;\n    if (hdr->e_machine != EM_AARCH64) {\n        fprintf(stderr, \"Invalid ELF: expected AArch64!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);\n\n    if (ph_end < hdr->e_phoff || ph_end > elf_len) {\n        fprintf(stderr, \"Invalid ELF: phdrs outside file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];\n    size_t i, j = 0;\n    size_t file_off = 0;\n    size_t tmpsize;\n\n    uint8_t* buf[3];\n\n    for (i=0; i<4; i++) {\n        Elf64_Phdr* phdr = NULL;\n        while (j < hdr->e_phnum) {\n            Elf64_Phdr* cur = &phdrs[j];\n            if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;\n            if (cur->p_type == PT_LOAD || i == 3) {\n                phdr = cur;\n                break;\n            }\n        }\n\n        if (phdr == NULL) {\n            fprintf(stderr, \"Invalid ELF: expected 3 loadable phdrs and a bss!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        // .bss is special\n        if (i == 3) {\n            tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;\n            if ( phdr->p_memsz > tmpsize)\n                nro_hdr.bssSize = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;\n            else\n                nro_hdr.bssSize = 0;\n            break;\n        }\n\n        nro_hdr.Segments[i].FileOff = phdr->p_vaddr;\n        nro_hdr.Segments[i].Size = (phdr->p_filesz + 0xFFF) & ~0xFFF;\n        buf[i] = malloc(nro_hdr.Segments[i].Size);\n        memset(buf[i], 0, nro_hdr.Segments[i].Size);\n\n        if (buf[i] == NULL) {\n            fprintf(stderr, \"Out of memory!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);\n\n        file_off += nro_hdr.Segments[i].Size;\n        file_off = (file_off + 0xFFF) & ~0xFFF;\n    }\n\n    /* Iterate over sections to find build id. */\n    size_t cur_sect_hdr_ofs = hdr->e_shoff;\n    for (unsigned int i = 0; i < hdr->e_shnum; i++) {\n        Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);\n        if (cur_shdr->sh_type == SHT_NOTE) {\n            Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);\n            u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));\n            u8 *note_desc = note_name + note_hdr->n_namesz;\n            if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, \"GNU\\x00\", 4) == 0) {\n                size_t build_id_size = note_hdr->n_descsz;\n                if (build_id_size > 0x20) {\n                    build_id_size = 0x20;\n                }\n                memcpy(nro_hdr.BuildId, note_desc, build_id_size);\n            }\n        }\n        cur_sect_hdr_ofs += hdr->e_shentsize;\n    }\n\n    FILE* out = fopen(argv[2], \"wb\");\n\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to open output file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    nro_hdr.size = file_off;\n\n    nro_hdr.version = 0;\n    nro_hdr.flags   = (aligned_header << 0);\n\n    // TODO check retvals\n\n    for (i=0; i<3; i++)\n    {\n        fseek(out, nro_hdr.Segments[i].FileOff, SEEK_SET);\n        fwrite(buf[i], nro_hdr.Segments[i].Size, 1, out);\n    }\n\n    fseek(out, sizeof(nro_start), SEEK_SET);\n    fwrite(&nro_hdr, sizeof(nro_hdr), 1, out);\n\n    if (icon_path==NULL && nacp_path==NULL && romfs_path==NULL) {\n        fclose(out);\n        return EXIT_SUCCESS;\n    }\n\n    AssetHeader asset_hdr;\n    memset(&asset_hdr, 0, sizeof(asset_hdr));\n    memcpy(asset_hdr.magic, \"ASET\", 4);\n    asset_hdr.version = 0;\n\n    fseek(out, file_off, SEEK_SET);\n\n    uint8_t* icon = NULL, *nacp = NULL, *romfs = NULL;\n    size_t icon_len = 0, nacp_len = 0, romfs_len = 0;\n    size_t tmp_off = sizeof(asset_hdr);\n\n    if (icon_path) {\n        icon = ReadEntireFile(icon_path, &icon_len);\n        if (icon == NULL) {\n            fprintf(stderr, \"Failed to open input icon!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        asset_hdr.icon.offset = tmp_off;\n        asset_hdr.icon.size = icon_len;\n        tmp_off+= icon_len;\n    }\n\n    if (nacp_path) {\n        nacp = ReadEntireFile(nacp_path, &nacp_len);\n        if (nacp == NULL) {\n            fprintf(stderr, \"Failed to open input nacp!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        asset_hdr.nacp.offset = tmp_off;\n        asset_hdr.nacp.size = nacp_len;\n        tmp_off+= nacp_len;\n    }\n\n    if (romfs_path) {\n        romfs = ReadEntireFile(romfs_path, &romfs_len);\n        if (romfs == NULL) {\n            fprintf(stderr, \"Failed to open input romfs!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        asset_hdr.romfs.offset = tmp_off;\n        asset_hdr.romfs.size = romfs_len;\n        tmp_off+= romfs_len;\n\n    } else if (romfs_dir_path) {\n        asset_hdr.romfs.offset = tmp_off;\n        asset_hdr.romfs.size = build_romfs_by_path_into_file(romfs_dir_path, out, file_off + tmp_off);\n        tmp_off+= asset_hdr.romfs.size;\n        fseek(out, file_off, SEEK_SET);\n    }\n\n    fwrite(&asset_hdr, sizeof(asset_hdr), 1, out);\n\n    if (icon_path) {\n        fseek(out, file_off + asset_hdr.icon.offset, SEEK_SET);\n        fwrite(icon, icon_len, 1, out);\n    }\n\n    if (nacp_path) {\n        fseek(out, file_off + asset_hdr.nacp.offset, SEEK_SET);\n        fwrite(nacp, nacp_len, 1, out);\n    }\n\n    if (romfs_path) {\n        fseek(out, file_off + asset_hdr.romfs.offset, SEEK_SET);\n        fwrite(romfs, romfs_len, 1, out);\n    }\n\n    fclose(out);\n\n    return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/elf2nso.c",
    "content": "// Copyright 2017 plutoo\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <lz4.h>\n#include \"sha256.h\"\n#include \"elf64.h\"\n\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint8_t u8;\n\ntypedef struct {\n    u32 FileOff;\n    u32 DstOff;\n    u32 DecompSz;\n    u32 AlignOrTotalSz;\n} NsoSegment;\n\ntypedef u8 Sha2Hash[0x20];\n\ntypedef struct {\n    u8  Magic[4];\n    u32 Unk1;\n    u32 Unk2;\n    u32 Unk3;\n    NsoSegment Segments[3];\n    u8  BuildId[0x20];\n    u32 CompSz[3];\n    u8  Padding[0x24];\n    u64 Unk4;\n    u64 Unk5;\n    Sha2Hash Hashes[3];    \n} NsoHeader;\n\nuint8_t* ReadEntireFile(const char* fn, size_t* len_out) {\n    FILE* fd = fopen(fn, \"rb\");\n    if (fd == NULL)\n        return NULL;\n\n    fseek(fd, 0, SEEK_END);\n    size_t len = ftell(fd);\n    fseek(fd, 0, SEEK_SET);\n\n    uint8_t* buf = malloc(len);\n    if (buf == NULL) {\n        fclose(fd);\n        return NULL;\n    }\n\n    size_t rc = fread(buf, 1, len, fd);\n    if (rc != len) {\n        fclose(fd);\n        free(buf);\n        return NULL;\n    }\n\n    *len_out = len;\n    return buf;\n}\n\nint main(int argc, char* argv[]) {\n    if (argc != 3) {\n        fprintf(stderr, \"%s <elf-file> <nso-file>\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n\n    NsoHeader nso_hdr;\n    memset(&nso_hdr, 0, sizeof(nso_hdr));\n    memcpy(nso_hdr.Magic, \"NSO0\", 4);\n    nso_hdr.Unk3 = 0x3f;\n\n    if (sizeof(NsoHeader) != 0x100) {\n        fprintf(stderr, \"Bad compile environment!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    size_t elf_len;\n    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);\n    if (elf == NULL) {\n        fprintf(stderr, \"Failed to open input!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    if (elf_len < sizeof(Elf64_Ehdr)) {\n        fprintf(stderr, \"Input file doesn't fit ELF header!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;\n    if (hdr->e_machine != EM_AARCH64) {\n        fprintf(stderr, \"Invalid ELF: expected AArch64!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);\n\n    if (ph_end < hdr->e_phoff || ph_end > elf_len) {\n        fprintf(stderr, \"Invalid ELF: phdrs outside file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];\n    size_t i, j = 0;\n    size_t file_off = sizeof(NsoHeader);\n\n    uint8_t* comp_buf[3];\n    int comp_sz[3];\n\n    for (i=0; i<3; i++) {\n        Elf64_Phdr* phdr = NULL;\n        while (j < hdr->e_phnum) {\n            Elf64_Phdr* cur = &phdrs[j++];\n            if (cur->p_type == PT_LOAD) {\n                phdr = cur;\n                break;\n            }\n        }\n\n        if (phdr == NULL) {\n            fprintf(stderr, \"Invalid ELF: expected 3 loadable phdrs!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        nso_hdr.Segments[i].FileOff = file_off;\n        nso_hdr.Segments[i].DstOff = phdr->p_vaddr;\n        nso_hdr.Segments[i].DecompSz = phdr->p_filesz;\n\n        // for .data segment this field contains bss size\n        if (i == 2)\n            nso_hdr.Segments[i].AlignOrTotalSz = phdr->p_memsz - phdr->p_filesz;\n        else\n            nso_hdr.Segments[i].AlignOrTotalSz = 1;\n\n        SHA256_CTX ctx;\n        sha256_init(&ctx);\n        sha256_update(&ctx, &elf[phdr->p_offset], phdr->p_filesz);\n        sha256_final(&ctx, (u8*) &nso_hdr.Hashes[i]);\n\n        size_t comp_max = LZ4_compressBound(phdr->p_filesz);\n        comp_buf[i] = malloc(comp_max);\n\n        if (comp_buf[i] == NULL) {\n            fprintf(stderr, \"Compressing: Out of memory!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        // TODO check p_offset\n        comp_sz[i] = LZ4_compress_default(&elf[phdr->p_offset], comp_buf[i], phdr->p_filesz, comp_max);\n\n        if (comp_sz[i] < 0) {\n            fprintf(stderr, \"Failed to compress!\\n\");\n            return EXIT_FAILURE;\n        }\n\n        nso_hdr.CompSz[i] = comp_sz[i];\n        file_off += comp_sz[i];\n    }\n    \n    /* Iterate over sections to find build id. */\n    size_t cur_sect_hdr_ofs = hdr->e_shoff;\n    for (unsigned int i = 0; i < hdr->e_shnum; i++) {\n        Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);\n        if (cur_shdr->sh_type == SHT_NOTE) {\n            Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);\n            u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));\n            u8 *note_desc = note_name + note_hdr->n_namesz;\n            if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, \"GNU\\x00\", 4) == 0) {\n                size_t build_id_size = note_hdr->n_descsz;\n                if (build_id_size > 0x20) {\n                    build_id_size = 0x20;\n                }\n                memcpy(nso_hdr.BuildId, note_desc, build_id_size);\n            }\n        }\n        cur_sect_hdr_ofs += hdr->e_shentsize;\n    }\n\n    FILE* out = fopen(argv[2], \"wb\");\n\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to open output file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    // TODO check retvals\n    fwrite(&nso_hdr, sizeof(nso_hdr), 1, out);\n\n    for (i=0; i<3; i++)\n        fwrite(comp_buf[i], comp_sz[i], 1, out);\n\n    return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/elf64.h",
    "content": "/*-\n * Copyright (c) 1996-1998 John D. Polstra.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * $FreeBSD: head/sys/sys/elf64.h 186667 2009-01-01 02:08:56Z obrien $\n */\n\n#ifndef _SYS_ELF64_H_\n#define _SYS_ELF64_H_ 1\n\n#include \"elf_common.h\"\n\n/*\n * ELF definitions common to all 64-bit architectures.\n */\n\ntypedef uint64_t\tElf64_Addr;\ntypedef uint16_t\tElf64_Half;\ntypedef uint64_t\tElf64_Off;\ntypedef int32_t\t\tElf64_Sword;\ntypedef int64_t\t\tElf64_Sxword;\ntypedef uint32_t\tElf64_Word;\ntypedef uint64_t\tElf64_Lword;\ntypedef uint64_t\tElf64_Xword;\n\n/*\n * Types of dynamic symbol hash table bucket and chain elements.\n *\n * This is inconsistent among 64 bit architectures, so a machine dependent\n * typedef is required.\n */\n\ntypedef Elf64_Word\tElf64_Hashelt;\n\n/* Non-standard class-dependent datatype used for abstraction. */\ntypedef Elf64_Xword\tElf64_Size;\ntypedef Elf64_Sxword\tElf64_Ssize;\n\n/*\n * ELF header.\n */\n\ntypedef struct {\n\tunsigned char\te_ident[EI_NIDENT];\t/* File identification. */\n\tElf64_Half\te_type;\t\t/* File type. */\n\tElf64_Half\te_machine;\t/* Machine architecture. */\n\tElf64_Word\te_version;\t/* ELF format version. */\n\tElf64_Addr\te_entry;\t/* Entry point. */\n\tElf64_Off\te_phoff;\t/* Program header file offset. */\n\tElf64_Off\te_shoff;\t/* Section header file offset. */\n\tElf64_Word\te_flags;\t/* Architecture-specific flags. */\n\tElf64_Half\te_ehsize;\t/* Size of ELF header in bytes. */\n\tElf64_Half\te_phentsize;\t/* Size of program header entry. */\n\tElf64_Half\te_phnum;\t/* Number of program header entries. */\n\tElf64_Half\te_shentsize;\t/* Size of section header entry. */\n\tElf64_Half\te_shnum;\t/* Number of section header entries. */\n\tElf64_Half\te_shstrndx;\t/* Section name strings section. */\n} Elf64_Ehdr;\n\n/*\n * Section header.\n */\n\ntypedef struct {\n\tElf64_Word\tsh_name;\t/* Section name (index into the\n\t\t\t\t\t   section header string table). */\n\tElf64_Word\tsh_type;\t/* Section type. */\n\tElf64_Xword\tsh_flags;\t/* Section flags. */\n\tElf64_Addr\tsh_addr;\t/* Address in memory image. */\n\tElf64_Off\tsh_offset;\t/* Offset in file. */\n\tElf64_Xword\tsh_size;\t/* Size in bytes. */\n\tElf64_Word\tsh_link;\t/* Index of a related section. */\n\tElf64_Word\tsh_info;\t/* Depends on section type. */\n\tElf64_Xword\tsh_addralign;\t/* Alignment in bytes. */\n\tElf64_Xword\tsh_entsize;\t/* Size of each entry in section. */\n} Elf64_Shdr;\n\n/*\n * Program header.\n */\n\ntypedef struct {\n\tElf64_Word\tp_type;\t\t/* Entry type. */\n\tElf64_Word\tp_flags;\t/* Access permission flags. */\n\tElf64_Off\tp_offset;\t/* File offset of contents. */\n\tElf64_Addr\tp_vaddr;\t/* Virtual address in memory image. */\n\tElf64_Addr\tp_paddr;\t/* Physical address (not used). */\n\tElf64_Xword\tp_filesz;\t/* Size of contents in file. */\n\tElf64_Xword\tp_memsz;\t/* Size of contents in memory. */\n\tElf64_Xword\tp_align;\t/* Alignment in memory and file. */\n} Elf64_Phdr;\n\n/*\n * Dynamic structure.  The \".dynamic\" section contains an array of them.\n */\n\ntypedef struct {\n\tElf64_Sxword\td_tag;\t\t/* Entry type. */\n\tunion {\n\t\tElf64_Xword\td_val;\t/* Integer value. */\n\t\tElf64_Addr\td_ptr;\t/* Address value. */\n\t} d_un;\n} Elf64_Dyn;\n\n/*\n * Relocation entries.\n */\n\n/* Relocations that don't need an addend field. */\ntypedef struct {\n\tElf64_Addr\tr_offset;\t/* Location to be relocated. */\n\tElf64_Xword\tr_info;\t\t/* Relocation type and symbol index. */\n} Elf64_Rel;\n\n/* Relocations that need an addend field. */\ntypedef struct {\n\tElf64_Addr\tr_offset;\t/* Location to be relocated. */\n\tElf64_Xword\tr_info;\t\t/* Relocation type and symbol index. */\n\tElf64_Sxword\tr_addend;\t/* Addend. */\n} Elf64_Rela;\n\n/* Macros for accessing the fields of r_info. */\n#define\tELF64_R_SYM(info)\t((info) >> 32)\n#define\tELF64_R_TYPE(info)\t((info) & 0xffffffffL)\n\n/* Macro for constructing r_info from field values. */\n#define\tELF64_R_INFO(sym, type)\t(((sym) << 32) + ((type) & 0xffffffffL))\n\n#define\tELF64_R_TYPE_DATA(info)\t(((Elf64_Xword)(info)<<32)>>40)\n#define\tELF64_R_TYPE_ID(info)\t(((Elf64_Xword)(info)<<56)>>56)\n#define\tELF64_R_TYPE_INFO(data, type)\t\\\n\t\t\t\t(((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))\n\n/*\n *\tNote entry header\n */\ntypedef Elf_Note Elf64_Nhdr;\n\n/*\n *\tMove entry\n */\ntypedef struct {\n\tElf64_Lword\tm_value;\t/* symbol value */\n\tElf64_Xword \tm_info;\t\t/* size + index */\n\tElf64_Xword\tm_poffset;\t/* symbol offset */\n\tElf64_Half\tm_repeat;\t/* repeat count */\n\tElf64_Half\tm_stride;\t/* stride info */\n} Elf64_Move;\n\n#define\tELF64_M_SYM(info)\t((info)>>8)\n#define\tELF64_M_SIZE(info)\t((unsigned char)(info))\n#define\tELF64_M_INFO(sym, size)\t(((sym)<<8)+(unsigned char)(size))\n\n/*\n *\tHardware/Software capabilities entry\n */\ntypedef struct {\n\tElf64_Xword\tc_tag;\t\t/* how to interpret value */\n\tunion {\n\t\tElf64_Xword\tc_val;\n\t\tElf64_Addr\tc_ptr;\n\t} c_un;\n} Elf64_Cap;\n\n/*\n * Symbol table entries.\n */\n\ntypedef struct {\n\tElf64_Word\tst_name;\t/* String table index of name. */\n\tunsigned char\tst_info;\t/* Type and binding information. */\n\tunsigned char\tst_other;\t/* Reserved (not used). */\n\tElf64_Half\tst_shndx;\t/* Section index of symbol. */\n\tElf64_Addr\tst_value;\t/* Symbol value. */\n\tElf64_Xword\tst_size;\t/* Size of associated object. */\n} Elf64_Sym;\n\n/* Macros for accessing the fields of st_info. */\n#define\tELF64_ST_BIND(info)\t\t((info) >> 4)\n#define\tELF64_ST_TYPE(info)\t\t((info) & 0xf)\n\n/* Macro for constructing st_info from field values. */\n#define\tELF64_ST_INFO(bind, type)\t(((bind) << 4) + ((type) & 0xf))\n\n/* Macro for accessing the fields of st_other. */\n#define\tELF64_ST_VISIBILITY(oth)\t((oth) & 0x3)\n\n/* Structures used by Sun & GNU-style symbol versioning. */\ntypedef struct {\n\tElf64_Half\tvd_version;\n\tElf64_Half\tvd_flags;\n\tElf64_Half\tvd_ndx;\n\tElf64_Half\tvd_cnt;\n\tElf64_Word\tvd_hash;\n\tElf64_Word\tvd_aux;\n\tElf64_Word\tvd_next;\n} Elf64_Verdef;\n\ntypedef struct {\n\tElf64_Word\tvda_name;\n\tElf64_Word\tvda_next;\n} Elf64_Verdaux;\n\ntypedef struct {\n\tElf64_Half\tvn_version;\n\tElf64_Half\tvn_cnt;\n\tElf64_Word\tvn_file;\n\tElf64_Word\tvn_aux;\n\tElf64_Word\tvn_next;\n} Elf64_Verneed;\n\ntypedef struct {\n\tElf64_Word\tvna_hash;\n\tElf64_Half\tvna_flags;\n\tElf64_Half\tvna_other;\n\tElf64_Word\tvna_name;\n\tElf64_Word\tvna_next;\n} Elf64_Vernaux;\n\ntypedef Elf64_Half Elf64_Versym;\n\ntypedef struct {\n\tElf64_Half\tsi_boundto;\t/* direct bindings - symbol bound to */\n\tElf64_Half\tsi_flags;\t/* per symbol flags */\n} Elf64_Syminfo;\n\n#endif /* !_SYS_ELF64_H_ */\n"
  },
  {
    "path": "src/elf_common.h",
    "content": "/*-\n * Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien\n * Copyright (c) 1998 John D. Polstra.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * $FreeBSD: head/sys/sys/elf_common.h 273284 2014-10-19 20:23:31Z andrew $\n */\n\n#ifndef _SYS_ELF_COMMON_H_\n#define\t_SYS_ELF_COMMON_H_ 1\n\n/*\n * ELF definitions that are independent of architecture or word size.\n */\n\n/*\n * Note header.  The \".note\" section contains an array of notes.  Each\n * begins with this header, aligned to a word boundary.  Immediately\n * following the note header is n_namesz bytes of name, padded to the\n * next word boundary.  Then comes n_descsz bytes of descriptor, again\n * padded to a word boundary.  The values of n_namesz and n_descsz do\n * not include the padding.\n */\n\ntypedef struct {\n\tuint32_t\tn_namesz;\t/* Length of name. */\n\tuint32_t\tn_descsz;\t/* Length of descriptor. */\n\tuint32_t\tn_type;\t\t/* Type of this note. */\n} Elf_Note;\n\n/*\n * The header for GNU-style hash sections.\n */\n\ntypedef struct {\n\tuint32_t\tgh_nbuckets;\t/* Number of hash buckets. */\n\tuint32_t\tgh_symndx;\t/* First visible symbol in .dynsym. */\n\tuint32_t\tgh_maskwords;\t/* #maskwords used in bloom filter. */\n\tuint32_t\tgh_shift2;\t/* Bloom filter shift count. */\n} Elf_GNU_Hash_Header;\n\n/* Indexes into the e_ident array.  Keep synced with\n   http://www.sco.com/developers/gabi/latest/ch4.eheader.html */\n#define\tEI_MAG0\t\t0\t/* Magic number, byte 0. */\n#define\tEI_MAG1\t\t1\t/* Magic number, byte 1. */\n#define\tEI_MAG2\t\t2\t/* Magic number, byte 2. */\n#define\tEI_MAG3\t\t3\t/* Magic number, byte 3. */\n#define\tEI_CLASS\t4\t/* Class of machine. */\n#define\tEI_DATA\t\t5\t/* Data format. */\n#define\tEI_VERSION\t6\t/* ELF format version. */\n#define\tEI_OSABI\t7\t/* Operating system / ABI identification */\n#define\tEI_ABIVERSION\t8\t/* ABI version */\n#define\tOLD_EI_BRAND\t8\t/* Start of architecture identification. */\n#define\tEI_PAD\t\t9\t/* Start of padding (per SVR4 ABI). */\n#define\tEI_NIDENT\t16\t/* Size of e_ident array. */\n\n/* Values for the magic number bytes. */\n#define\tELFMAG0\t\t0x7f\n#define\tELFMAG1\t\t'E'\n#define\tELFMAG2\t\t'L'\n#define\tELFMAG3\t\t'F'\n#define\tELFMAG\t\t\"\\177ELF\"\t/* magic string */\n#define\tSELFMAG\t\t4\t\t/* magic string size */\n\n/* Values for e_ident[EI_VERSION] and e_version. */\n#define\tEV_NONE\t\t0\n#define\tEV_CURRENT\t1\n\n/* Values for e_ident[EI_CLASS]. */\n#define\tELFCLASSNONE\t0\t/* Unknown class. */\n#define\tELFCLASS32\t1\t/* 32-bit architecture. */\n#define\tELFCLASS64\t2\t/* 64-bit architecture. */\n\n/* Values for e_ident[EI_DATA]. */\n#define\tELFDATANONE\t0\t/* Unknown data format. */\n#define\tELFDATA2LSB\t1\t/* 2's complement little-endian. */\n#define\tELFDATA2MSB\t2\t/* 2's complement big-endian. */\n\n/* Values for e_ident[EI_OSABI]. */\n#define\tELFOSABI_NONE\t\t0\t/* UNIX System V ABI */\n#define\tELFOSABI_HPUX\t\t1\t/* HP-UX operating system */\n#define\tELFOSABI_NETBSD\t\t2\t/* NetBSD */\n#define\tELFOSABI_LINUX\t\t3\t/* GNU/Linux */\n#define\tELFOSABI_HURD\t\t4\t/* GNU/Hurd */\n#define\tELFOSABI_86OPEN\t\t5\t/* 86Open common IA32 ABI */\n#define\tELFOSABI_SOLARIS\t6\t/* Solaris */\n#define\tELFOSABI_AIX\t\t7\t/* AIX */\n#define\tELFOSABI_IRIX\t\t8\t/* IRIX */\n#define\tELFOSABI_FREEBSD\t9\t/* FreeBSD */\n#define\tELFOSABI_TRU64\t\t10\t/* TRU64 UNIX */\n#define\tELFOSABI_MODESTO\t11\t/* Novell Modesto */\n#define\tELFOSABI_OPENBSD\t12\t/* OpenBSD */\n#define\tELFOSABI_OPENVMS\t13\t/* Open VMS */\n#define\tELFOSABI_NSK\t\t14\t/* HP Non-Stop Kernel */\n#define\tELFOSABI_AROS\t\t15\t/* Amiga Research OS */\n#define\tELFOSABI_ARM\t\t97\t/* ARM */\n#define\tELFOSABI_STANDALONE\t255\t/* Standalone (embedded) application */\n\n#define\tELFOSABI_SYSV\t\tELFOSABI_NONE\t/* symbol used in old spec */\n#define\tELFOSABI_MONTEREY\tELFOSABI_AIX\t/* Monterey */\n\n/* e_ident */\n#define\tIS_ELF(ehdr)\t((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \\\n\t\t\t (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \\\n\t\t\t (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \\\n\t\t\t (ehdr).e_ident[EI_MAG3] == ELFMAG3)\n\n/* Values for e_type. */\n#define\tET_NONE\t\t0\t/* Unknown type. */\n#define\tET_REL\t\t1\t/* Relocatable. */\n#define\tET_EXEC\t\t2\t/* Executable. */\n#define\tET_DYN\t\t3\t/* Shared object. */\n#define\tET_CORE\t\t4\t/* Core file. */\n#define\tET_LOOS\t\t0xfe00\t/* First operating system specific. */\n#define\tET_HIOS\t\t0xfeff\t/* Last operating system-specific. */\n#define\tET_LOPROC\t0xff00\t/* First processor-specific. */\n#define\tET_HIPROC\t0xffff\t/* Last processor-specific. */\n\n/* Values for e_machine. */\n#define\tEM_NONE\t\t0\t/* Unknown machine. */\n#define\tEM_M32\t\t1\t/* AT&T WE32100. */\n#define\tEM_SPARC\t2\t/* Sun SPARC. */\n#define\tEM_386\t\t3\t/* Intel i386. */\n#define\tEM_68K\t\t4\t/* Motorola 68000. */\n#define\tEM_88K\t\t5\t/* Motorola 88000. */\n#define\tEM_860\t\t7\t/* Intel i860. */\n#define\tEM_MIPS\t\t8\t/* MIPS R3000 Big-Endian only. */\n#define\tEM_S370\t\t9\t/* IBM System/370. */\n#define\tEM_MIPS_RS3_LE\t10\t/* MIPS R3000 Little-Endian. */\n#define\tEM_PARISC\t15\t/* HP PA-RISC. */\n#define\tEM_VPP500\t17\t/* Fujitsu VPP500. */\n#define\tEM_SPARC32PLUS\t18\t/* SPARC v8plus. */\n#define\tEM_960\t\t19\t/* Intel 80960. */\n#define\tEM_PPC\t\t20\t/* PowerPC 32-bit. */\n#define\tEM_PPC64\t21\t/* PowerPC 64-bit. */\n#define\tEM_S390\t\t22\t/* IBM System/390. */\n#define\tEM_V800\t\t36\t/* NEC V800. */\n#define\tEM_FR20\t\t37\t/* Fujitsu FR20. */\n#define\tEM_RH32\t\t38\t/* TRW RH-32. */\n#define\tEM_RCE\t\t39\t/* Motorola RCE. */\n#define\tEM_ARM\t\t40\t/* ARM. */\n#define\tEM_SH\t\t42\t/* Hitachi SH. */\n#define\tEM_SPARCV9\t43\t/* SPARC v9 64-bit. */\n#define\tEM_TRICORE\t44\t/* Siemens TriCore embedded processor. */\n#define\tEM_ARC\t\t45\t/* Argonaut RISC Core. */\n#define\tEM_H8_300\t46\t/* Hitachi H8/300. */\n#define\tEM_H8_300H\t47\t/* Hitachi H8/300H. */\n#define\tEM_H8S\t\t48\t/* Hitachi H8S. */\n#define\tEM_H8_500\t49\t/* Hitachi H8/500. */\n#define\tEM_IA_64\t50\t/* Intel IA-64 Processor. */\n#define\tEM_MIPS_X\t51\t/* Stanford MIPS-X. */\n#define\tEM_COLDFIRE\t52\t/* Motorola ColdFire. */\n#define\tEM_68HC12\t53\t/* Motorola M68HC12. */\n#define\tEM_MMA\t\t54\t/* Fujitsu MMA. */\n#define\tEM_PCP\t\t55\t/* Siemens PCP. */\n#define\tEM_NCPU\t\t56\t/* Sony nCPU. */\n#define\tEM_NDR1\t\t57\t/* Denso NDR1 microprocessor. */\n#define\tEM_STARCORE\t58\t/* Motorola Star*Core processor. */\n#define\tEM_ME16\t\t59\t/* Toyota ME16 processor. */\n#define\tEM_ST100\t60\t/* STMicroelectronics ST100 processor. */\n#define\tEM_TINYJ\t61\t/* Advanced Logic Corp. TinyJ processor. */\n#define\tEM_X86_64\t62\t/* Advanced Micro Devices x86-64 */\n#define\tEM_AMD64\tEM_X86_64\t/* Advanced Micro Devices x86-64 (compat) */\n#define\tEM_PDSP\t\t63\t/* Sony DSP Processor. */\n#define\tEM_FX66\t\t66\t/* Siemens FX66 microcontroller. */\n#define\tEM_ST9PLUS\t67\t/* STMicroelectronics ST9+ 8/16\n\t\t\t\t   microcontroller. */\n#define\tEM_ST7\t\t68\t/* STmicroelectronics ST7 8-bit\n\t\t\t\t   microcontroller. */\n#define\tEM_68HC16\t69\t/* Motorola MC68HC16 microcontroller. */\n#define\tEM_68HC11\t70\t/* Motorola MC68HC11 microcontroller. */\n#define\tEM_68HC08\t71\t/* Motorola MC68HC08 microcontroller. */\n#define\tEM_68HC05\t72\t/* Motorola MC68HC05 microcontroller. */\n#define\tEM_SVX\t\t73\t/* Silicon Graphics SVx. */\n#define\tEM_ST19\t\t74\t/* STMicroelectronics ST19 8-bit mc. */\n#define\tEM_VAX\t\t75\t/* Digital VAX. */\n#define\tEM_CRIS\t\t76\t/* Axis Communications 32-bit embedded\n\t\t\t\t   processor. */\n#define\tEM_JAVELIN\t77\t/* Infineon Technologies 32-bit embedded\n\t\t\t\t   processor. */\n#define\tEM_FIREPATH\t78\t/* Element 14 64-bit DSP Processor. */\n#define\tEM_ZSP\t\t79\t/* LSI Logic 16-bit DSP Processor. */\n#define\tEM_MMIX\t\t80\t/* Donald Knuth's educational 64-bit proc. */\n#define\tEM_HUANY\t81\t/* Harvard University machine-independent\n\t\t\t\t   object files. */\n#define\tEM_PRISM\t82\t/* SiTera Prism. */\n#define\tEM_AVR\t\t83\t/* Atmel AVR 8-bit microcontroller. */\n#define\tEM_FR30\t\t84\t/* Fujitsu FR30. */\n#define\tEM_D10V\t\t85\t/* Mitsubishi D10V. */\n#define\tEM_D30V\t\t86\t/* Mitsubishi D30V. */\n#define\tEM_V850\t\t87\t/* NEC v850. */\n#define\tEM_M32R\t\t88\t/* Mitsubishi M32R. */\n#define\tEM_MN10300\t89\t/* Matsushita MN10300. */\n#define\tEM_MN10200\t90\t/* Matsushita MN10200. */\n#define\tEM_PJ\t\t91\t/* picoJava. */\n#define\tEM_OPENRISC\t92\t/* OpenRISC 32-bit embedded processor. */\n#define\tEM_ARC_A5\t93\t/* ARC Cores Tangent-A5. */\n#define\tEM_XTENSA\t94\t/* Tensilica Xtensa Architecture. */\n#define\tEM_VIDEOCORE\t95\t/* Alphamosaic VideoCore processor. */\n#define\tEM_TMM_GPP\t96\t/* Thompson Multimedia General Purpose\n\t\t\t\t   Processor. */\n#define\tEM_NS32K\t97\t/* National Semiconductor 32000 series. */\n#define\tEM_TPC\t\t98\t/* Tenor Network TPC processor. */\n#define\tEM_SNP1K\t99\t/* Trebia SNP 1000 processor. */\n#define\tEM_ST200\t100\t/* STMicroelectronics ST200 microcontroller. */\n#define\tEM_IP2K\t\t101\t/* Ubicom IP2xxx microcontroller family. */\n#define\tEM_MAX\t\t102\t/* MAX Processor. */\n#define\tEM_CR\t\t103\t/* National Semiconductor CompactRISC\n\t\t\t\t   microprocessor. */\n#define\tEM_F2MC16\t104\t/* Fujitsu F2MC16. */\n#define\tEM_MSP430\t105\t/* Texas Instruments embedded microcontroller\n\t\t\t\t   msp430. */\n#define\tEM_BLACKFIN\t106\t/* Analog Devices Blackfin (DSP) processor. */\n#define\tEM_SE_C33\t107\t/* S1C33 Family of Seiko Epson processors. */\n#define\tEM_SEP\t\t108\t/* Sharp embedded microprocessor. */\n#define\tEM_ARCA\t\t109\t/* Arca RISC Microprocessor. */\n#define\tEM_UNICORE\t110\t/* Microprocessor series from PKU-Unity Ltd.\n\t\t\t\t   and MPRC of Peking University */\n#define\tEM_AARCH64\t183\t/* AArch64 (64-bit ARM) */\n\n/* Non-standard or deprecated. */\n#define\tEM_486\t\t6\t/* Intel i486. */\n#define\tEM_MIPS_RS4_BE\t10\t/* MIPS R4000 Big-Endian */\n#define\tEM_ALPHA_STD\t41\t/* Digital Alpha (standard value). */\n#define\tEM_ALPHA\t0x9026\t/* Alpha (written in the absence of an ABI) */\n\n/* Special section indexes. */\n#define\tSHN_UNDEF\t     0\t\t/* Undefined, missing, irrelevant. */\n#define\tSHN_LORESERVE\t0xff00\t\t/* First of reserved range. */\n#define\tSHN_LOPROC\t0xff00\t\t/* First processor-specific. */\n#define\tSHN_HIPROC\t0xff1f\t\t/* Last processor-specific. */\n#define\tSHN_LOOS\t0xff20\t\t/* First operating system-specific. */\n#define\tSHN_HIOS\t0xff3f\t\t/* Last operating system-specific. */\n#define\tSHN_ABS\t\t0xfff1\t\t/* Absolute values. */\n#define\tSHN_COMMON\t0xfff2\t\t/* Common data. */\n#define\tSHN_XINDEX\t0xffff\t\t/* Escape -- index stored elsewhere. */\n#define\tSHN_HIRESERVE\t0xffff\t\t/* Last of reserved range. */\n\n/* sh_type */\n#define\tSHT_NULL\t\t0\t/* inactive */\n#define\tSHT_PROGBITS\t\t1\t/* program defined information */\n#define\tSHT_SYMTAB\t\t2\t/* symbol table section */\n#define\tSHT_STRTAB\t\t3\t/* string table section */\n#define\tSHT_RELA\t\t4\t/* relocation section with addends */\n#define\tSHT_HASH\t\t5\t/* symbol hash table section */\n#define\tSHT_DYNAMIC\t\t6\t/* dynamic section */\n#define\tSHT_NOTE\t\t7\t/* note section */\n#define\tSHT_NOBITS\t\t8\t/* no space section */\n#define\tSHT_REL\t\t\t9\t/* relocation section - no addends */\n#define\tSHT_SHLIB\t\t10\t/* reserved - purpose unknown */\n#define\tSHT_DYNSYM\t\t11\t/* dynamic symbol table section */\n#define\tSHT_INIT_ARRAY\t\t14\t/* Initialization function pointers. */\n#define\tSHT_FINI_ARRAY\t\t15\t/* Termination function pointers. */\n#define\tSHT_PREINIT_ARRAY\t16\t/* Pre-initialization function ptrs. */\n#define\tSHT_GROUP\t\t17\t/* Section group. */\n#define\tSHT_SYMTAB_SHNDX\t18\t/* Section indexes (see SHN_XINDEX). */\n#define\tSHT_LOOS\t\t0x60000000\t/* First of OS specific semantics */\n#define\tSHT_LOSUNW\t\t0x6ffffff4\n#define\tSHT_SUNW_dof\t\t0x6ffffff4\n#define\tSHT_SUNW_cap\t\t0x6ffffff5\n#define\tSHT_SUNW_SIGNATURE\t0x6ffffff6\n#define\tSHT_GNU_HASH\t\t0x6ffffff6\n#define\tSHT_GNU_LIBLIST\t\t0x6ffffff7\n#define\tSHT_SUNW_ANNOTATE\t0x6ffffff7\n#define\tSHT_SUNW_DEBUGSTR\t0x6ffffff8\n#define\tSHT_SUNW_DEBUG\t\t0x6ffffff9\n#define\tSHT_SUNW_move\t\t0x6ffffffa\n#define\tSHT_SUNW_COMDAT\t\t0x6ffffffb\n#define\tSHT_SUNW_syminfo\t0x6ffffffc\n#define\tSHT_SUNW_verdef\t\t0x6ffffffd\n#define\tSHT_GNU_verdef\t\t0x6ffffffd\t/* Symbol versions provided */\n#define\tSHT_SUNW_verneed\t0x6ffffffe\n#define\tSHT_GNU_verneed\t\t0x6ffffffe\t/* Symbol versions required */\n#define\tSHT_SUNW_versym\t\t0x6fffffff\n#define\tSHT_GNU_versym\t\t0x6fffffff\t/* Symbol version table */\n#define\tSHT_HISUNW\t\t0x6fffffff\n#define\tSHT_HIOS\t\t0x6fffffff\t/* Last of OS specific semantics */\n#define\tSHT_LOPROC\t\t0x70000000\t/* reserved range for processor */\n#define\tSHT_AMD64_UNWIND\t0x70000001\t/* unwind information */\n#define\tSHT_ARM_EXIDX\t\t0x70000001\t/* Exception index table. */\n#define\tSHT_ARM_PREEMPTMAP\t0x70000002\t/* BPABI DLL dynamic linking \n\t\t\t\t\t\t   pre-emption map. */\n#define\tSHT_ARM_ATTRIBUTES\t0x70000003\t/* Object file compatibility \n\t\t\t\t\t\t   attributes. */\n#define\tSHT_ARM_DEBUGOVERLAY\t0x70000004\t/* See DBGOVL for details. */\n#define\tSHT_ARM_OVERLAYSECTION\t0x70000005\t/* See DBGOVL for details. */\n#define\tSHT_MIPS_REGINFO\t0x70000006\n#define\tSHT_MIPS_OPTIONS\t0x7000000d\n#define\tSHT_MIPS_DWARF\t\t0x7000001e\t/* MIPS gcc uses MIPS_DWARF */\n#define\tSHT_HIPROC\t\t0x7fffffff\t/* specific section header types */\n#define\tSHT_LOUSER\t\t0x80000000\t/* reserved range for application */\n#define\tSHT_HIUSER\t\t0xffffffff\t/* specific indexes */\n\n/* Flags for sh_flags. */\n#define\tSHF_WRITE\t\t0x1\t/* Section contains writable data. */\n#define\tSHF_ALLOC\t\t0x2\t/* Section occupies memory. */\n#define\tSHF_EXECINSTR\t\t0x4\t/* Section contains instructions. */\n#define\tSHF_MERGE\t\t0x10\t/* Section may be merged. */\n#define\tSHF_STRINGS\t\t0x20\t/* Section contains strings. */\n#define\tSHF_INFO_LINK\t\t0x40\t/* sh_info holds section index. */\n#define\tSHF_LINK_ORDER\t\t0x80\t/* Special ordering requirements. */\n#define\tSHF_OS_NONCONFORMING\t0x100\t/* OS-specific processing required. */\n#define\tSHF_GROUP\t\t0x200\t/* Member of section group. */\n#define\tSHF_TLS\t\t\t0x400\t/* Section contains TLS data. */\n#define\tSHF_MASKOS\t0x0ff00000\t/* OS-specific semantics. */\n#define\tSHF_MASKPROC\t0xf0000000\t/* Processor-specific semantics. */\n\n/* Values for p_type. */\n#define\tPT_NULL\t\t0\t/* Unused entry. */\n#define\tPT_LOAD\t\t1\t/* Loadable segment. */\n#define\tPT_DYNAMIC\t2\t/* Dynamic linking information segment. */\n#define\tPT_INTERP\t3\t/* Pathname of interpreter. */\n#define\tPT_NOTE\t\t4\t/* Auxiliary information. */\n#define\tPT_SHLIB\t5\t/* Reserved (not used). */\n#define\tPT_PHDR\t\t6\t/* Location of program header itself. */\n#define\tPT_TLS\t\t7\t/* Thread local storage segment */\n#define\tPT_LOOS\t\t0x60000000\t/* First OS-specific. */\n#define\tPT_SUNW_UNWIND\t0x6464e550\t/* amd64 UNWIND program header */\n#define\tPT_GNU_EH_FRAME\t0x6474e550\n#define\tPT_GNU_STACK\t0x6474e551\n#define\tPT_GNU_RELRO\t0x6474e552\n#define\tPT_DUMP_DELTA\t0x6fb5d000\t/* va->pa map for kernel dumps\n\t\t\t\t\t   (currently arm). */\n#define\tPT_LOSUNW\t0x6ffffffa\n#define\tPT_SUNWBSS\t0x6ffffffa\t/* Sun Specific segment */\n#define\tPT_SUNWSTACK\t0x6ffffffb\t/* describes the stack segment */\n#define\tPT_SUNWDTRACE\t0x6ffffffc\t/* private */\n#define\tPT_SUNWCAP\t0x6ffffffd\t/* hard/soft capabilities segment */\n#define\tPT_HISUNW\t0x6fffffff\n#define\tPT_HIOS\t\t0x6fffffff\t/* Last OS-specific. */\n#define\tPT_LOPROC\t0x70000000\t/* First processor-specific type. */\n#define\tPT_HIPROC\t0x7fffffff\t/* Last processor-specific type. */\n\n/* Values for p_flags. */\n#define\tPF_X\t\t0x1\t\t/* Executable. */\n#define\tPF_W\t\t0x2\t\t/* Writable. */\n#define\tPF_R\t\t0x4\t\t/* Readable. */\n#define\tPF_MASKOS\t0x0ff00000\t/* Operating system-specific. */\n#define\tPF_MASKPROC\t0xf0000000\t/* Processor-specific. */\n\n/* Extended program header index. */\n#define\tPN_XNUM\t\t0xffff\n\n/* Values for d_tag. */\n#define\tDT_NULL\t\t0\t/* Terminating entry. */\n#define\tDT_NEEDED\t1\t/* String table offset of a needed shared\n\t\t\t\t   library. */\n#define\tDT_PLTRELSZ\t2\t/* Total size in bytes of PLT relocations. */\n#define\tDT_PLTGOT\t3\t/* Processor-dependent address. */\n#define\tDT_HASH\t\t4\t/* Address of symbol hash table. */\n#define\tDT_STRTAB\t5\t/* Address of string table. */\n#define\tDT_SYMTAB\t6\t/* Address of symbol table. */\n#define\tDT_RELA\t\t7\t/* Address of ElfNN_Rela relocations. */\n#define\tDT_RELASZ\t8\t/* Total size of ElfNN_Rela relocations. */\n#define\tDT_RELAENT\t9\t/* Size of each ElfNN_Rela relocation entry. */\n#define\tDT_STRSZ\t10\t/* Size of string table. */\n#define\tDT_SYMENT\t11\t/* Size of each symbol table entry. */\n#define\tDT_INIT\t\t12\t/* Address of initialization function. */\n#define\tDT_FINI\t\t13\t/* Address of finalization function. */\n#define\tDT_SONAME\t14\t/* String table offset of shared object\n\t\t\t\t   name. */\n#define\tDT_RPATH\t15\t/* String table offset of library path. [sup] */\n#define\tDT_SYMBOLIC\t16\t/* Indicates \"symbolic\" linking. [sup] */\n#define\tDT_REL\t\t17\t/* Address of ElfNN_Rel relocations. */\n#define\tDT_RELSZ\t18\t/* Total size of ElfNN_Rel relocations. */\n#define\tDT_RELENT\t19\t/* Size of each ElfNN_Rel relocation. */\n#define\tDT_PLTREL\t20\t/* Type of relocation used for PLT. */\n#define\tDT_DEBUG\t21\t/* Reserved (not used). */\n#define\tDT_TEXTREL\t22\t/* Indicates there may be relocations in\n\t\t\t\t   non-writable segments. [sup] */\n#define\tDT_JMPREL\t23\t/* Address of PLT relocations. */\n#define\tDT_BIND_NOW\t24\t/* [sup] */\n#define\tDT_INIT_ARRAY\t25\t/* Address of the array of pointers to\n\t\t\t\t   initialization functions */\n#define\tDT_FINI_ARRAY\t26\t/* Address of the array of pointers to\n\t\t\t\t   termination functions */\n#define\tDT_INIT_ARRAYSZ\t27\t/* Size in bytes of the array of\n\t\t\t\t   initialization functions. */\n#define\tDT_FINI_ARRAYSZ\t28\t/* Size in bytes of the array of\n\t\t\t\t   termination functions. */\n#define\tDT_RUNPATH\t29\t/* String table offset of a null-terminated\n\t\t\t\t   library search path string. */\n#define\tDT_FLAGS\t30\t/* Object specific flag values. */\n#define\tDT_ENCODING\t32\t/* Values greater than or equal to DT_ENCODING\n\t\t\t\t   and less than DT_LOOS follow the rules for\n\t\t\t\t   the interpretation of the d_un union\n\t\t\t\t   as follows: even == 'd_ptr', odd == 'd_val'\n\t\t\t\t   or none */\n#define\tDT_PREINIT_ARRAY 32\t/* Address of the array of pointers to\n\t\t\t\t   pre-initialization functions. */\n#define\tDT_PREINIT_ARRAYSZ 33\t/* Size in bytes of the array of\n\t\t\t\t   pre-initialization functions. */\n#define\tDT_MAXPOSTAGS\t34\t/* number of positive tags */\n#define\tDT_LOOS\t\t0x6000000d\t/* First OS-specific */\n#define\tDT_SUNW_AUXILIARY\t0x6000000d\t/* symbol auxiliary name */\n#define\tDT_SUNW_RTLDINF\t\t0x6000000e\t/* ld.so.1 info (private) */\n#define\tDT_SUNW_FILTER\t\t0x6000000f\t/* symbol filter name */\n#define\tDT_SUNW_CAP\t\t0x60000010\t/* hardware/software */\n#define\tDT_HIOS\t\t0x6ffff000\t/* Last OS-specific */\n\n/*\n * DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the\n * Dyn.d_un.d_val field of the Elf*_Dyn structure.\n */\n#define\tDT_VALRNGLO\t0x6ffffd00\n#define\tDT_CHECKSUM\t0x6ffffdf8\t/* elf checksum */\n#define\tDT_PLTPADSZ\t0x6ffffdf9\t/* pltpadding size */\n#define\tDT_MOVEENT\t0x6ffffdfa\t/* move table entry size */\n#define\tDT_MOVESZ\t0x6ffffdfb\t/* move table size */\n#define\tDT_FEATURE\t0x6ffffdfc\t/* feature holder */\n#define\tDT_POSFLAG_1\t0x6ffffdfd\t/* flags for DT_* entries, effecting */\n\t\t\t\t\t/*\tthe following DT_* entry. */\n\t\t\t\t\t/*\tSee DF_P1_* definitions */\n#define\tDT_SYMINSZ\t0x6ffffdfe\t/* syminfo table size (in bytes) */\n#define\tDT_SYMINENT\t0x6ffffdff\t/* syminfo entry size (in bytes) */\n#define\tDT_VALRNGHI\t0x6ffffdff\n\n/*\n * DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the\n * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.\n *\n * If any adjustment is made to the ELF object after it has been\n * built, these entries will need to be adjusted.\n */\n#define\tDT_ADDRRNGLO\t0x6ffffe00\n#define\tDT_GNU_HASH\t0x6ffffef5\t/* GNU-style hash table */\n#define\tDT_CONFIG\t0x6ffffefa\t/* configuration information */\n#define\tDT_DEPAUDIT\t0x6ffffefb\t/* dependency auditing */\n#define\tDT_AUDIT\t0x6ffffefc\t/* object auditing */\n#define\tDT_PLTPAD\t0x6ffffefd\t/* pltpadding (sparcv9) */\n#define\tDT_MOVETAB\t0x6ffffefe\t/* move table */\n#define\tDT_SYMINFO\t0x6ffffeff\t/* syminfo table */\n#define\tDT_ADDRRNGHI\t0x6ffffeff\n\n#define\tDT_VERSYM\t0x6ffffff0\t/* Address of versym section. */\n#define\tDT_RELACOUNT\t0x6ffffff9\t/* number of RELATIVE relocations */\n#define\tDT_RELCOUNT\t0x6ffffffa\t/* number of RELATIVE relocations */\n#define\tDT_FLAGS_1\t0x6ffffffb\t/* state flags - see DF_1_* defs */\n#define\tDT_VERDEF\t0x6ffffffc\t/* Address of verdef section. */\n#define\tDT_VERDEFNUM\t0x6ffffffd\t/* Number of elems in verdef section */\n#define\tDT_VERNEED\t0x6ffffffe\t/* Address of verneed section. */\n#define\tDT_VERNEEDNUM\t0x6fffffff\t/* Number of elems in verneed section */\n\n#define\tDT_LOPROC\t0x70000000\t/* First processor-specific type. */\n#define\tDT_DEPRECATED_SPARC_REGISTER\t0x7000001\n#define\tDT_AUXILIARY\t0x7ffffffd\t/* shared library auxiliary name */\n#define\tDT_USED\t\t0x7ffffffe\t/* ignored - same as needed */\n#define\tDT_FILTER\t0x7fffffff\t/* shared library filter name */\n#define\tDT_HIPROC\t0x7fffffff\t/* Last processor-specific type. */\n\n/* Values for DT_FLAGS */\n#define\tDF_ORIGIN\t0x0001\t/* Indicates that the object being loaded may\n\t\t\t\t   make reference to the $ORIGIN substitution\n\t\t\t\t   string */\n#define\tDF_SYMBOLIC\t0x0002\t/* Indicates \"symbolic\" linking. */\n#define\tDF_TEXTREL\t0x0004\t/* Indicates there may be relocations in\n\t\t\t\t   non-writable segments. */\n#define\tDF_BIND_NOW\t0x0008\t/* Indicates that the dynamic linker should\n\t\t\t\t   process all relocations for the object\n\t\t\t\t   containing this entry before transferring\n\t\t\t\t   control to the program. */\n#define\tDF_STATIC_TLS\t0x0010\t/* Indicates that the shared object or\n\t\t\t\t   executable contains code using a static\n\t\t\t\t   thread-local storage scheme. */\n\n/* Values for DT_FLAGS_1 */\n#define\tDF_1_BIND_NOW\t0x00000001\t/* Same as DF_BIND_NOW */\n#define\tDF_1_GLOBAL\t0x00000002\t/* Set the RTLD_GLOBAL for object */\n#define\tDF_1_NODELETE\t0x00000008\t/* Set the RTLD_NODELETE for object */\n#define\tDF_1_LOADFLTR\t0x00000010\t/* Immediate loading of filtees */\n#define\tDF_1_NOOPEN     0x00000040\t/* Do not allow loading on dlopen() */\n#define\tDF_1_ORIGIN\t0x00000080\t/* Process $ORIGIN */\n#define\tDF_1_INTERPOSE\t0x00000400\t/* Interpose all objects but main */\n#define\tDF_1_NODEFLIB\t0x00000800\t/* Do not search default paths */\n\n/* Values for n_type.  Used in core files. */\n#define\tNT_PRSTATUS\t1\t/* Process status. */\n#define\tNT_FPREGSET\t2\t/* Floating point registers. */\n#define\tNT_PRPSINFO\t3\t/* Process state info. */\n#define\tNT_THRMISC\t7\t/* Thread miscellaneous info. */\n#define\tNT_PROCSTAT_PROC\t8\t/* Procstat proc data. */\n#define\tNT_PROCSTAT_FILES\t9\t/* Procstat files data. */\n#define\tNT_PROCSTAT_VMMAP\t10\t/* Procstat vmmap data. */\n#define\tNT_PROCSTAT_GROUPS\t11\t/* Procstat groups data. */\n#define\tNT_PROCSTAT_UMASK\t12\t/* Procstat umask data. */\n#define\tNT_PROCSTAT_RLIMIT\t13\t/* Procstat rlimit data. */\n#define\tNT_PROCSTAT_OSREL\t14\t/* Procstat osreldate data. */\n#define\tNT_PROCSTAT_PSSTRINGS\t15\t/* Procstat ps_strings data. */\n#define\tNT_PROCSTAT_AUXV\t16\t/* Procstat auxv data. */\n\n/* Symbol Binding - ELFNN_ST_BIND - st_info */\n#define\tSTB_LOCAL\t0\t/* Local symbol */\n#define\tSTB_GLOBAL\t1\t/* Global symbol */\n#define\tSTB_WEAK\t2\t/* like global - lower precedence */\n#define\tSTB_LOOS\t10\t/* Reserved range for operating system */\n#define\tSTB_HIOS\t12\t/*   specific semantics. */\n#define\tSTB_LOPROC\t13\t/* reserved range for processor */\n#define\tSTB_HIPROC\t15\t/*   specific semantics. */\n\n/* Symbol type - ELFNN_ST_TYPE - st_info */\n#define\tSTT_NOTYPE\t0\t/* Unspecified type. */\n#define\tSTT_OBJECT\t1\t/* Data object. */\n#define\tSTT_FUNC\t2\t/* Function. */\n#define\tSTT_SECTION\t3\t/* Section. */\n#define\tSTT_FILE\t4\t/* Source file. */\n#define\tSTT_COMMON\t5\t/* Uninitialized common block. */\n#define\tSTT_TLS\t\t6\t/* TLS object. */\n#define\tSTT_NUM\t\t7\n#define\tSTT_LOOS\t10\t/* Reserved range for operating system */\n#define\tSTT_GNU_IFUNC\t10\n#define\tSTT_HIOS\t12\t/*   specific semantics. */\n#define\tSTT_LOPROC\t13\t/* reserved range for processor */\n#define\tSTT_HIPROC\t15\t/*   specific semantics. */\n\n/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */\n#define\tSTV_DEFAULT\t0x0\t/* Default visibility (see binding). */\n#define\tSTV_INTERNAL\t0x1\t/* Special meaning in relocatable objects. */\n#define\tSTV_HIDDEN\t0x2\t/* Not visible. */\n#define\tSTV_PROTECTED\t0x3\t/* Visible but not preemptible. */\n#define\tSTV_EXPORTED\t0x4\n#define\tSTV_SINGLETON\t0x5\n#define\tSTV_ELIMINATE\t0x6\n\n/* Special symbol table indexes. */\n#define\tSTN_UNDEF\t0\t/* Undefined symbol index. */\n\n/* Symbol versioning flags. */\n#define\tVER_DEF_CURRENT\t1\n#define\tVER_DEF_IDX(x)\tVER_NDX(x)\n\n#define\tVER_FLG_BASE\t0x01\n#define\tVER_FLG_WEAK\t0x02\n\n#define\tVER_NEED_CURRENT\t1\n#define\tVER_NEED_WEAK\t(1u << 15)\n#define\tVER_NEED_HIDDEN\tVER_NDX_HIDDEN\n#define\tVER_NEED_IDX(x)\tVER_NDX(x)\n\n#define\tVER_NDX_LOCAL\t0\n#define\tVER_NDX_GLOBAL\t1\n#define\tVER_NDX_GIVEN\t2\n\n#define\tVER_NDX_HIDDEN\t(1u << 15)\n#define\tVER_NDX(x)\t((x) & ~(1u << 15))\n\n#define\tCA_SUNW_NULL\t0\n#define\tCA_SUNW_HW_1\t1\t\t/* first hardware capabilities entry */\n#define\tCA_SUNW_SF_1\t2\t\t/* first software capabilities entry */\n\n/*\n * Syminfo flag values\n */\n#define\tSYMINFO_FLG_DIRECT\t0x0001\t/* symbol ref has direct association */\n\t\t\t\t\t/*\tto object containing defn. */\n#define\tSYMINFO_FLG_PASSTHRU\t0x0002\t/* ignored - see SYMINFO_FLG_FILTER */\n#define\tSYMINFO_FLG_COPY\t0x0004\t/* symbol is a copy-reloc */\n#define\tSYMINFO_FLG_LAZYLOAD\t0x0008\t/* object containing defn should be */\n\t\t\t\t\t/*\tlazily-loaded */\n#define\tSYMINFO_FLG_DIRECTBIND\t0x0010\t/* ref should be bound directly to */\n\t\t\t\t\t/*\tobject containing defn. */\n#define\tSYMINFO_FLG_NOEXTDIRECT\t0x0020\t/* don't let an external reference */\n\t\t\t\t\t/*\tdirectly bind to this symbol */\n#define\tSYMINFO_FLG_FILTER\t0x0002\t/* symbol ref is associated to a */\n#define\tSYMINFO_FLG_AUXILIARY\t0x0040\t/* \tstandard or auxiliary filter */\n\n/*\n * Syminfo.si_boundto values.\n */\n#define\tSYMINFO_BT_SELF\t\t0xffff\t/* symbol bound to self */\n#define\tSYMINFO_BT_PARENT\t0xfffe\t/* symbol bound to parent */\n#define\tSYMINFO_BT_NONE\t\t0xfffd\t/* no special symbol binding */\n#define\tSYMINFO_BT_EXTERN\t0xfffc\t/* symbol defined as external */\n#define\tSYMINFO_BT_LOWRESERVE\t0xff00\t/* beginning of reserved entries */\n\n/*\n * Syminfo version values.\n */\n#define\tSYMINFO_NONE\t\t0\t/* Syminfo version */\n#define\tSYMINFO_CURRENT\t\t1\n#define\tSYMINFO_NUM\t\t2\n\n/*\n * Relocation types.\n *\n * All machine architectures are defined here to allow tools on one to\n * handle others.\n */\n\n#define\tR_386_NONE\t\t0\t/* No relocation. */\n#define\tR_386_32\t\t1\t/* Add symbol value. */\n#define\tR_386_PC32\t\t2\t/* Add PC-relative symbol value. */\n#define\tR_386_GOT32\t\t3\t/* Add PC-relative GOT offset. */\n#define\tR_386_PLT32\t\t4\t/* Add PC-relative PLT offset. */\n#define\tR_386_COPY\t\t5\t/* Copy data from shared object. */\n#define\tR_386_GLOB_DAT\t\t6\t/* Set GOT entry to data address. */\n#define\tR_386_JMP_SLOT\t\t7\t/* Set GOT entry to code address. */\n#define\tR_386_RELATIVE\t\t8\t/* Add load address of shared object. */\n#define\tR_386_GOTOFF\t\t9\t/* Add GOT-relative symbol address. */\n#define\tR_386_GOTPC\t\t10\t/* Add PC-relative GOT table address. */\n#define\tR_386_TLS_TPOFF\t\t14\t/* Negative offset in static TLS block */\n#define\tR_386_TLS_IE\t\t15\t/* Absolute address of GOT for -ve static TLS */\n#define\tR_386_TLS_GOTIE\t\t16\t/* GOT entry for negative static TLS block */\n#define\tR_386_TLS_LE\t\t17\t/* Negative offset relative to static TLS */\n#define\tR_386_TLS_GD\t\t18\t/* 32 bit offset to GOT (index,off) pair */\n#define\tR_386_TLS_LDM\t\t19\t/* 32 bit offset to GOT (index,zero) pair */\n#define\tR_386_TLS_GD_32\t\t24\t/* 32 bit offset to GOT (index,off) pair */\n#define\tR_386_TLS_GD_PUSH\t25\t/* pushl instruction for Sun ABI GD sequence */\n#define\tR_386_TLS_GD_CALL\t26\t/* call instruction for Sun ABI GD sequence */\n#define\tR_386_TLS_GD_POP\t27\t/* popl instruction for Sun ABI GD sequence */\n#define\tR_386_TLS_LDM_32\t28\t/* 32 bit offset to GOT (index,zero) pair */\n#define\tR_386_TLS_LDM_PUSH\t29\t/* pushl instruction for Sun ABI LD sequence */\n#define\tR_386_TLS_LDM_CALL\t30\t/* call instruction for Sun ABI LD sequence */\n#define\tR_386_TLS_LDM_POP\t31\t/* popl instruction for Sun ABI LD sequence */\n#define\tR_386_TLS_LDO_32\t32\t/* 32 bit offset from start of TLS block */\n#define\tR_386_TLS_IE_32\t\t33\t/* 32 bit offset to GOT static TLS offset entry */\n#define\tR_386_TLS_LE_32\t\t34\t/* 32 bit offset within static TLS block */\n#define\tR_386_TLS_DTPMOD32\t35\t/* GOT entry containing TLS index */\n#define\tR_386_TLS_DTPOFF32\t36\t/* GOT entry containing TLS offset */\n#define\tR_386_TLS_TPOFF32\t37\t/* GOT entry of -ve static TLS offset */\n#define\tR_386_IRELATIVE\t\t42\t/* PLT entry resolved indirectly at runtime */\n\n#define\tR_ARM_NONE\t\t0\t/* No relocation. */\n#define\tR_ARM_PC24\t\t1\n#define\tR_ARM_ABS32\t\t2\n#define\tR_ARM_REL32\t\t3\n#define\tR_ARM_PC13\t\t4\n#define\tR_ARM_ABS16\t\t5\n#define\tR_ARM_ABS12\t\t6\n#define\tR_ARM_THM_ABS5\t\t7\n#define\tR_ARM_ABS8\t\t8\n#define\tR_ARM_SBREL32\t\t9\n#define\tR_ARM_THM_PC22\t\t10\n#define\tR_ARM_THM_PC8\t\t11\n#define\tR_ARM_AMP_VCALL9\t12\n#define\tR_ARM_SWI24\t\t13\n#define\tR_ARM_THM_SWI8\t\t14\n#define\tR_ARM_XPC25\t\t15\n#define\tR_ARM_THM_XPC22\t\t16\n/* TLS relocations */\n#define\tR_ARM_TLS_DTPMOD32\t17\t/* ID of module containing symbol */\n#define\tR_ARM_TLS_DTPOFF32\t18\t/* Offset in TLS block */\n#define\tR_ARM_TLS_TPOFF32\t19\t/* Offset in static TLS block */\n#define\tR_ARM_COPY\t\t20\t/* Copy data from shared object. */\n#define\tR_ARM_GLOB_DAT\t\t21\t/* Set GOT entry to data address. */\n#define\tR_ARM_JUMP_SLOT\t\t22\t/* Set GOT entry to code address. */\n#define\tR_ARM_RELATIVE\t\t23\t/* Add load address of shared object. */\n#define\tR_ARM_GOTOFF\t\t24\t/* Add GOT-relative symbol address. */\n#define\tR_ARM_GOTPC\t\t25\t/* Add PC-relative GOT table address. */\n#define\tR_ARM_GOT32\t\t26\t/* Add PC-relative GOT offset. */\n#define\tR_ARM_PLT32\t\t27\t/* Add PC-relative PLT offset. */\n#define\tR_ARM_GNU_VTENTRY\t100\n#define\tR_ARM_GNU_VTINHERIT\t101\n#define\tR_ARM_RSBREL32\t\t250\n#define\tR_ARM_THM_RPC22\t\t251\n#define\tR_ARM_RREL32\t\t252\n#define\tR_ARM_RABS32\t\t253\n#define\tR_ARM_RPC24\t\t254\n#define\tR_ARM_RBASE\t\t255\n\n/*\tName\t\t\tValue\t   Field\tCalculation */\n#define\tR_IA_64_NONE\t\t0\t/* None */\n#define\tR_IA_64_IMM14\t\t0x21\t/* immediate14\tS + A */\n#define\tR_IA_64_IMM22\t\t0x22\t/* immediate22\tS + A */\n#define\tR_IA_64_IMM64\t\t0x23\t/* immediate64\tS + A */\n#define\tR_IA_64_DIR32MSB\t0x24\t/* word32 MSB\tS + A */\n#define\tR_IA_64_DIR32LSB\t0x25\t/* word32 LSB\tS + A */\n#define\tR_IA_64_DIR64MSB\t0x26\t/* word64 MSB\tS + A */\n#define\tR_IA_64_DIR64LSB\t0x27\t/* word64 LSB\tS + A */\n#define\tR_IA_64_GPREL22\t\t0x2a\t/* immediate22\t@gprel(S + A) */\n#define\tR_IA_64_GPREL64I\t0x2b\t/* immediate64\t@gprel(S + A) */\n#define\tR_IA_64_GPREL32MSB\t0x2c\t/* word32 MSB\t@gprel(S + A) */\n#define\tR_IA_64_GPREL32LSB\t0x2d\t/* word32 LSB\t@gprel(S + A) */\n#define\tR_IA_64_GPREL64MSB\t0x2e\t/* word64 MSB\t@gprel(S + A) */\n#define\tR_IA_64_GPREL64LSB\t0x2f\t/* word64 LSB\t@gprel(S + A) */\n#define\tR_IA_64_LTOFF22\t\t0x32\t/* immediate22\t@ltoff(S + A) */\n#define\tR_IA_64_LTOFF64I\t0x33\t/* immediate64\t@ltoff(S + A) */\n#define\tR_IA_64_PLTOFF22\t0x3a\t/* immediate22\t@pltoff(S + A) */\n#define\tR_IA_64_PLTOFF64I\t0x3b\t/* immediate64\t@pltoff(S + A) */\n#define\tR_IA_64_PLTOFF64MSB\t0x3e\t/* word64 MSB\t@pltoff(S + A) */\n#define\tR_IA_64_PLTOFF64LSB\t0x3f\t/* word64 LSB\t@pltoff(S + A) */\n#define\tR_IA_64_FPTR64I\t\t0x43\t/* immediate64\t@fptr(S + A) */\n#define\tR_IA_64_FPTR32MSB\t0x44\t/* word32 MSB\t@fptr(S + A) */\n#define\tR_IA_64_FPTR32LSB\t0x45\t/* word32 LSB\t@fptr(S + A) */\n#define\tR_IA_64_FPTR64MSB\t0x46\t/* word64 MSB\t@fptr(S + A) */\n#define\tR_IA_64_FPTR64LSB\t0x47\t/* word64 LSB\t@fptr(S + A) */\n#define\tR_IA_64_PCREL60B\t0x48\t/* immediate60 form1 S + A - P */\n#define\tR_IA_64_PCREL21B\t0x49\t/* immediate21 form1 S + A - P */\n#define\tR_IA_64_PCREL21M\t0x4a\t/* immediate21 form2 S + A - P */\n#define\tR_IA_64_PCREL21F\t0x4b\t/* immediate21 form3 S + A - P */\n#define\tR_IA_64_PCREL32MSB\t0x4c\t/* word32 MSB\tS + A - P */\n#define\tR_IA_64_PCREL32LSB\t0x4d\t/* word32 LSB\tS + A - P */\n#define\tR_IA_64_PCREL64MSB\t0x4e\t/* word64 MSB\tS + A - P */\n#define\tR_IA_64_PCREL64LSB\t0x4f\t/* word64 LSB\tS + A - P */\n#define\tR_IA_64_LTOFF_FPTR22\t0x52\t/* immediate22\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_LTOFF_FPTR64I\t0x53\t/* immediate64\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_LTOFF_FPTR32MSB\t0x54\t/* word32 MSB\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_LTOFF_FPTR32LSB\t0x55\t/* word32 LSB\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_LTOFF_FPTR64MSB\t0x56\t/* word64 MSB\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_LTOFF_FPTR64LSB\t0x57\t/* word64 LSB\t@ltoff(@fptr(S + A)) */\n#define\tR_IA_64_SEGREL32MSB\t0x5c\t/* word32 MSB\t@segrel(S + A) */\n#define\tR_IA_64_SEGREL32LSB\t0x5d\t/* word32 LSB\t@segrel(S + A) */\n#define\tR_IA_64_SEGREL64MSB\t0x5e\t/* word64 MSB\t@segrel(S + A) */\n#define\tR_IA_64_SEGREL64LSB\t0x5f\t/* word64 LSB\t@segrel(S + A) */\n#define\tR_IA_64_SECREL32MSB\t0x64\t/* word32 MSB\t@secrel(S + A) */\n#define\tR_IA_64_SECREL32LSB\t0x65\t/* word32 LSB\t@secrel(S + A) */\n#define\tR_IA_64_SECREL64MSB\t0x66\t/* word64 MSB\t@secrel(S + A) */\n#define\tR_IA_64_SECREL64LSB\t0x67\t/* word64 LSB\t@secrel(S + A) */\n#define\tR_IA_64_REL32MSB\t0x6c\t/* word32 MSB\tBD + A */\n#define\tR_IA_64_REL32LSB\t0x6d\t/* word32 LSB\tBD + A */\n#define\tR_IA_64_REL64MSB\t0x6e\t/* word64 MSB\tBD + A */\n#define\tR_IA_64_REL64LSB\t0x6f\t/* word64 LSB\tBD + A */\n#define\tR_IA_64_LTV32MSB\t0x74\t/* word32 MSB\tS + A */\n#define\tR_IA_64_LTV32LSB\t0x75\t/* word32 LSB\tS + A */\n#define\tR_IA_64_LTV64MSB\t0x76\t/* word64 MSB\tS + A */\n#define\tR_IA_64_LTV64LSB\t0x77\t/* word64 LSB\tS + A */\n#define\tR_IA_64_PCREL21BI\t0x79\t/* immediate21 form1 S + A - P */\n#define\tR_IA_64_PCREL22\t\t0x7a\t/* immediate22\tS + A - P */\n#define\tR_IA_64_PCREL64I\t0x7b\t/* immediate64\tS + A - P */\n#define\tR_IA_64_IPLTMSB\t\t0x80\t/* function descriptor MSB special */\n#define\tR_IA_64_IPLTLSB\t\t0x81\t/* function descriptor LSB speciaal */\n#define\tR_IA_64_SUB\t\t0x85\t/* immediate64\tA - S */\n#define\tR_IA_64_LTOFF22X\t0x86\t/* immediate22\tspecial */\n#define\tR_IA_64_LDXMOV\t\t0x87\t/* immediate22\tspecial */\n#define\tR_IA_64_TPREL14\t\t0x91\t/* imm14\t@tprel(S + A) */\n#define\tR_IA_64_TPREL22\t\t0x92\t/* imm22\t@tprel(S + A) */\n#define\tR_IA_64_TPREL64I\t0x93\t/* imm64\t@tprel(S + A) */\n#define\tR_IA_64_TPREL64MSB\t0x96\t/* word64 MSB\t@tprel(S + A) */\n#define\tR_IA_64_TPREL64LSB\t0x97\t/* word64 LSB\t@tprel(S + A) */\n#define\tR_IA_64_LTOFF_TPREL22\t0x9a\t/* imm22\t@ltoff(@tprel(S+A)) */\n#define\tR_IA_64_DTPMOD64MSB\t0xa6\t/* word64 MSB\t@dtpmod(S + A) */\n#define\tR_IA_64_DTPMOD64LSB\t0xa7\t/* word64 LSB\t@dtpmod(S + A) */\n#define\tR_IA_64_LTOFF_DTPMOD22\t0xaa\t/* imm22\t@ltoff(@dtpmod(S+A)) */\n#define\tR_IA_64_DTPREL14\t0xb1\t/* imm14\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL22\t0xb2\t/* imm22\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL64I\t0xb3\t/* imm64\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL32MSB\t0xb4\t/* word32 MSB\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL32LSB\t0xb5\t/* word32 LSB\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL64MSB\t0xb6\t/* word64 MSB\t@dtprel(S + A) */\n#define\tR_IA_64_DTPREL64LSB\t0xb7\t/* word64 LSB\t@dtprel(S + A) */\n#define\tR_IA_64_LTOFF_DTPREL22\t0xba\t/* imm22\t@ltoff(@dtprel(S+A)) */\n\n#define\tR_MIPS_NONE\t0\t/* No reloc */\n#define\tR_MIPS_16\t1\t/* Direct 16 bit */\n#define\tR_MIPS_32\t2\t/* Direct 32 bit */\n#define\tR_MIPS_REL32\t3\t/* PC relative 32 bit */\n#define\tR_MIPS_26\t4\t/* Direct 26 bit shifted */\n#define\tR_MIPS_HI16\t5\t/* High 16 bit */\n#define\tR_MIPS_LO16\t6\t/* Low 16 bit */\n#define\tR_MIPS_GPREL16\t7\t/* GP relative 16 bit */\n#define\tR_MIPS_LITERAL\t8\t/* 16 bit literal entry */\n#define\tR_MIPS_GOT16\t9\t/* 16 bit GOT entry */\n#define\tR_MIPS_PC16\t10\t/* PC relative 16 bit */\n#define\tR_MIPS_CALL16\t11\t/* 16 bit GOT entry for function */\n#define\tR_MIPS_GPREL32\t12\t/* GP relative 32 bit */\n#define\tR_MIPS_64\t18\t/* Direct 64 bit */\n#define\tR_MIPS_GOTHI16\t21\t/* GOT HI 16 bit */\n#define\tR_MIPS_GOTLO16\t22\t/* GOT LO 16 bit */\n#define\tR_MIPS_CALLHI16 30\t/* upper 16 bit GOT entry for function */\n#define\tR_MIPS_CALLLO16 31\t/* lower 16 bit GOT entry for function */\n\n#define\tR_PPC_NONE\t\t0\t/* No relocation. */\n#define\tR_PPC_ADDR32\t\t1\n#define\tR_PPC_ADDR24\t\t2\n#define\tR_PPC_ADDR16\t\t3\n#define\tR_PPC_ADDR16_LO\t\t4\n#define\tR_PPC_ADDR16_HI\t\t5\n#define\tR_PPC_ADDR16_HA\t\t6\n#define\tR_PPC_ADDR14\t\t7\n#define\tR_PPC_ADDR14_BRTAKEN\t8\n#define\tR_PPC_ADDR14_BRNTAKEN\t9\n#define\tR_PPC_REL24\t\t10\n#define\tR_PPC_REL14\t\t11\n#define\tR_PPC_REL14_BRTAKEN\t12\n#define\tR_PPC_REL14_BRNTAKEN\t13\n#define\tR_PPC_GOT16\t\t14\n#define\tR_PPC_GOT16_LO\t\t15\n#define\tR_PPC_GOT16_HI\t\t16\n#define\tR_PPC_GOT16_HA\t\t17\n#define\tR_PPC_PLTREL24\t\t18\n#define\tR_PPC_COPY\t\t19\n#define\tR_PPC_GLOB_DAT\t\t20\n#define\tR_PPC_JMP_SLOT\t\t21\n#define\tR_PPC_RELATIVE\t\t22\n#define\tR_PPC_LOCAL24PC\t\t23\n#define\tR_PPC_UADDR32\t\t24\n#define\tR_PPC_UADDR16\t\t25\n#define\tR_PPC_REL32\t\t26\n#define\tR_PPC_PLT32\t\t27\n#define\tR_PPC_PLTREL32\t\t28\n#define\tR_PPC_PLT16_LO\t\t29\n#define\tR_PPC_PLT16_HI\t\t30\n#define\tR_PPC_PLT16_HA\t\t31\n#define\tR_PPC_SDAREL16\t\t32\n#define\tR_PPC_SECTOFF\t\t33\n#define\tR_PPC_SECTOFF_LO\t34\n#define\tR_PPC_SECTOFF_HI\t35\n#define\tR_PPC_SECTOFF_HA\t36\n\n/*\n * 64-bit relocations\n */\n#define\tR_PPC64_ADDR64\t\t38\n#define\tR_PPC64_ADDR16_HIGHER\t39\n#define\tR_PPC64_ADDR16_HIGHERA\t40\n#define\tR_PPC64_ADDR16_HIGHEST\t41\n#define\tR_PPC64_ADDR16_HIGHESTA\t42\n#define\tR_PPC64_UADDR64\t\t43\n#define\tR_PPC64_REL64\t\t44\n#define\tR_PPC64_PLT64\t\t45\n#define\tR_PPC64_PLTREL64\t46\n#define\tR_PPC64_TOC16\t\t47\n#define\tR_PPC64_TOC16_LO\t48\n#define\tR_PPC64_TOC16_HI\t49\n#define\tR_PPC64_TOC16_HA\t50\n#define\tR_PPC64_TOC\t\t51\n#define\tR_PPC64_DTPMOD64\t68\n#define\tR_PPC64_TPREL64\t\t73\n#define\tR_PPC64_DTPREL64\t78\n\n/*\n * TLS relocations\n */\n#define\tR_PPC_TLS\t\t67\n#define\tR_PPC_DTPMOD32\t\t68\n#define\tR_PPC_TPREL16\t\t69\n#define\tR_PPC_TPREL16_LO\t70\n#define\tR_PPC_TPREL16_HI\t71\n#define\tR_PPC_TPREL16_HA\t72\n#define\tR_PPC_TPREL32\t\t73\n#define\tR_PPC_DTPREL16\t\t74\n#define\tR_PPC_DTPREL16_LO\t75\n#define\tR_PPC_DTPREL16_HI\t76\n#define\tR_PPC_DTPREL16_HA\t77\n#define\tR_PPC_DTPREL32\t\t78\n#define\tR_PPC_GOT_TLSGD16\t79\n#define\tR_PPC_GOT_TLSGD16_LO\t80\n#define\tR_PPC_GOT_TLSGD16_HI\t81\n#define\tR_PPC_GOT_TLSGD16_HA\t82\n#define\tR_PPC_GOT_TLSLD16\t83\n#define\tR_PPC_GOT_TLSLD16_LO\t84\n#define\tR_PPC_GOT_TLSLD16_HI\t85\n#define\tR_PPC_GOT_TLSLD16_HA\t86\n#define\tR_PPC_GOT_TPREL16\t87\n#define\tR_PPC_GOT_TPREL16_LO\t88\n#define\tR_PPC_GOT_TPREL16_HI\t89\n#define\tR_PPC_GOT_TPREL16_HA\t90\n\n/*\n * The remaining relocs are from the Embedded ELF ABI, and are not in the\n *  SVR4 ELF ABI.\n */\n\n#define\tR_PPC_EMB_NADDR32\t101\n#define\tR_PPC_EMB_NADDR16\t102\n#define\tR_PPC_EMB_NADDR16_LO\t103\n#define\tR_PPC_EMB_NADDR16_HI\t104\n#define\tR_PPC_EMB_NADDR16_HA\t105\n#define\tR_PPC_EMB_SDAI16\t106\n#define\tR_PPC_EMB_SDA2I16\t107\n#define\tR_PPC_EMB_SDA2REL\t108\n#define\tR_PPC_EMB_SDA21\t\t109\n#define\tR_PPC_EMB_MRKREF\t110\n#define\tR_PPC_EMB_RELSEC16\t111\n#define\tR_PPC_EMB_RELST_LO\t112\n#define\tR_PPC_EMB_RELST_HI\t113\n#define\tR_PPC_EMB_RELST_HA\t114\n#define\tR_PPC_EMB_BIT_FLD\t115\n#define\tR_PPC_EMB_RELSDA\t116\n\n#define\tR_SPARC_NONE\t\t0\n#define\tR_SPARC_8\t\t1\n#define\tR_SPARC_16\t\t2\n#define\tR_SPARC_32\t\t3\n#define\tR_SPARC_DISP8\t\t4\n#define\tR_SPARC_DISP16\t\t5\n#define\tR_SPARC_DISP32\t\t6\n#define\tR_SPARC_WDISP30\t\t7\n#define\tR_SPARC_WDISP22\t\t8\n#define\tR_SPARC_HI22\t\t9\n#define\tR_SPARC_22\t\t10\n#define\tR_SPARC_13\t\t11\n#define\tR_SPARC_LO10\t\t12\n#define\tR_SPARC_GOT10\t\t13\n#define\tR_SPARC_GOT13\t\t14\n#define\tR_SPARC_GOT22\t\t15\n#define\tR_SPARC_PC10\t\t16\n#define\tR_SPARC_PC22\t\t17\n#define\tR_SPARC_WPLT30\t\t18\n#define\tR_SPARC_COPY\t\t19\n#define\tR_SPARC_GLOB_DAT\t20\n#define\tR_SPARC_JMP_SLOT\t21\n#define\tR_SPARC_RELATIVE\t22\n#define\tR_SPARC_UA32\t\t23\n#define\tR_SPARC_PLT32\t\t24\n#define\tR_SPARC_HIPLT22\t\t25\n#define\tR_SPARC_LOPLT10\t\t26\n#define\tR_SPARC_PCPLT32\t\t27\n#define\tR_SPARC_PCPLT22\t\t28\n#define\tR_SPARC_PCPLT10\t\t29\n#define\tR_SPARC_10\t\t30\n#define\tR_SPARC_11\t\t31\n#define\tR_SPARC_64\t\t32\n#define\tR_SPARC_OLO10\t\t33\n#define\tR_SPARC_HH22\t\t34\n#define\tR_SPARC_HM10\t\t35\n#define\tR_SPARC_LM22\t\t36\n#define\tR_SPARC_PC_HH22\t\t37\n#define\tR_SPARC_PC_HM10\t\t38\n#define\tR_SPARC_PC_LM22\t\t39\n#define\tR_SPARC_WDISP16\t\t40\n#define\tR_SPARC_WDISP19\t\t41\n#define\tR_SPARC_GLOB_JMP\t42\n#define\tR_SPARC_7\t\t43\n#define\tR_SPARC_5\t\t44\n#define\tR_SPARC_6\t\t45\n#define\tR_SPARC_DISP64\t\t46\n#define\tR_SPARC_PLT64\t\t47\n#define\tR_SPARC_HIX22\t\t48\n#define\tR_SPARC_LOX10\t\t49\n#define\tR_SPARC_H44\t\t50\n#define\tR_SPARC_M44\t\t51\n#define\tR_SPARC_L44\t\t52\n#define\tR_SPARC_REGISTER\t53\n#define\tR_SPARC_UA64\t\t54\n#define\tR_SPARC_UA16\t\t55\n#define\tR_SPARC_TLS_GD_HI22\t56\n#define\tR_SPARC_TLS_GD_LO10\t57\n#define\tR_SPARC_TLS_GD_ADD\t58\n#define\tR_SPARC_TLS_GD_CALL\t59\n#define\tR_SPARC_TLS_LDM_HI22\t60\n#define\tR_SPARC_TLS_LDM_LO10\t61\n#define\tR_SPARC_TLS_LDM_ADD\t62\n#define\tR_SPARC_TLS_LDM_CALL\t63\n#define\tR_SPARC_TLS_LDO_HIX22\t64\n#define\tR_SPARC_TLS_LDO_LOX10\t65\n#define\tR_SPARC_TLS_LDO_ADD\t66\n#define\tR_SPARC_TLS_IE_HI22\t67\n#define\tR_SPARC_TLS_IE_LO10\t68\n#define\tR_SPARC_TLS_IE_LD\t69\n#define\tR_SPARC_TLS_IE_LDX\t70\n#define\tR_SPARC_TLS_IE_ADD\t71\n#define\tR_SPARC_TLS_LE_HIX22\t72\n#define\tR_SPARC_TLS_LE_LOX10\t73\n#define\tR_SPARC_TLS_DTPMOD32\t74\n#define\tR_SPARC_TLS_DTPMOD64\t75\n#define\tR_SPARC_TLS_DTPOFF32\t76\n#define\tR_SPARC_TLS_DTPOFF64\t77\n#define\tR_SPARC_TLS_TPOFF32\t78\n#define\tR_SPARC_TLS_TPOFF64\t79\n\n#define\tR_X86_64_NONE\t\t0\t/* No relocation. */\n#define\tR_X86_64_64\t\t1\t/* Add 64 bit symbol value. */\n#define\tR_X86_64_PC32\t\t2\t/* PC-relative 32 bit signed sym value. */\n#define\tR_X86_64_GOT32\t\t3\t/* PC-relative 32 bit GOT offset. */\n#define\tR_X86_64_PLT32\t\t4\t/* PC-relative 32 bit PLT offset. */\n#define\tR_X86_64_COPY\t\t5\t/* Copy data from shared object. */\n#define\tR_X86_64_GLOB_DAT\t6\t/* Set GOT entry to data address. */\n#define\tR_X86_64_JMP_SLOT\t7\t/* Set GOT entry to code address. */\n#define\tR_X86_64_RELATIVE\t8\t/* Add load address of shared object. */\n#define\tR_X86_64_GOTPCREL\t9\t/* Add 32 bit signed pcrel offset to GOT. */\n#define\tR_X86_64_32\t\t10\t/* Add 32 bit zero extended symbol value */\n#define\tR_X86_64_32S\t\t11\t/* Add 32 bit sign extended symbol value */\n#define\tR_X86_64_16\t\t12\t/* Add 16 bit zero extended symbol value */\n#define\tR_X86_64_PC16\t\t13\t/* Add 16 bit signed extended pc relative symbol value */\n#define\tR_X86_64_8\t\t14\t/* Add 8 bit zero extended symbol value */\n#define\tR_X86_64_PC8\t\t15\t/* Add 8 bit signed extended pc relative symbol value */\n#define\tR_X86_64_DTPMOD64\t16\t/* ID of module containing symbol */\n#define\tR_X86_64_DTPOFF64\t17\t/* Offset in TLS block */\n#define\tR_X86_64_TPOFF64\t18\t/* Offset in static TLS block */\n#define\tR_X86_64_TLSGD\t\t19\t/* PC relative offset to GD GOT entry */\n#define\tR_X86_64_TLSLD\t\t20\t/* PC relative offset to LD GOT entry */\n#define\tR_X86_64_DTPOFF32\t21\t/* Offset in TLS block */\n#define\tR_X86_64_GOTTPOFF\t22\t/* PC relative offset to IE GOT entry */\n#define\tR_X86_64_TPOFF32\t23\t/* Offset in static TLS block */\n#define\tR_X86_64_IRELATIVE\t37\n\n#define NT_GNU_BUILD_ID     3   /* Note type for .note.gnu.build-id */\n\n#endif /* !_SYS_ELF_COMMON_H_ */\n"
  },
  {
    "path": "src/filepath.c",
    "content": "#include <sys/stat.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n\n#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#endif\n\n#include \"types.h\"\n#include \"filepath.h\"\n\nvoid os_strncpy(oschar_t *dst, const char *src, size_t size) {\n#ifdef _WIN32\n    MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size);\n#else\n    strncpy(dst, src, size);\n#endif\n}\n\nvoid os_strncpy_to_char(char *dst, const oschar_t *src, size_t size) {\n#ifdef _WIN32\n    WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, size, NULL, NULL);\n#else\n    strncpy(dst, src, size);\n#endif\n}\n\nint os_makedir(const oschar_t *dir) {\n#ifdef _WIN32\n    return _wmkdir(dir);\n#else\n    return mkdir(dir, 0777);\n#endif\n}\n\nint os_rmdir(const oschar_t *dir) {\n#ifdef _WIN32\n    return _wrmdir(dir);\n#else\n    return remove(dir);\n#endif\n}\n\nvoid filepath_update(filepath_t *fpath) {\n    memset(fpath->os_path, 0, MAX_SWITCHPATH * sizeof(oschar_t));\n    os_strncpy(fpath->os_path, fpath->char_path, MAX_SWITCHPATH);\n}\n\nvoid filepath_init(filepath_t *fpath) {\n    fpath->valid = VALIDITY_INVALID;\n}\n\nvoid filepath_copy(filepath_t *fpath, filepath_t *copy) {\n    if (copy != NULL && copy->valid == VALIDITY_VALID)\n        memcpy(fpath, copy, sizeof(filepath_t));\n    else\n        memset(fpath, 0, sizeof(filepath_t));\n}\n\nvoid filepath_os_append(filepath_t *fpath, oschar_t *path) {\n    char tmppath[MAX_SWITCHPATH];\n    if (fpath->valid == VALIDITY_INVALID)\n        return;\n    \n    memset(tmppath, 0, MAX_SWITCHPATH);\n    \n    os_strncpy_to_char(tmppath, path, MAX_SWITCHPATH);\n    strcat(fpath->char_path, OS_PATH_SEPARATOR);\n    strcat(fpath->char_path, tmppath);\n    filepath_update(fpath);\n}\n\nvoid filepath_append(filepath_t *fpath, const char *format, ...) {\n    char tmppath[MAX_SWITCHPATH];\n    va_list args;\n\n    if (fpath->valid == VALIDITY_INVALID)\n        return;\n\n    memset(tmppath, 0, MAX_SWITCHPATH);\n\n    va_start(args, format);\n    vsnprintf(tmppath, sizeof(tmppath), format, args);\n    va_end(args);\n\n    strcat(fpath->char_path, OS_PATH_SEPARATOR);\n    strcat(fpath->char_path, tmppath);\n    filepath_update(fpath);\n}\n\nvoid filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...) {\n    char tmppath[MAX_SWITCHPATH];\n    va_list args;\n\n    if (fpath->valid == VALIDITY_INVALID || n > MAX_SWITCHPATH)\n        return;\n\n    memset(tmppath, 0, MAX_SWITCHPATH);\n\n    va_start(args, format);\n    vsnprintf(tmppath, sizeof(tmppath), format, args);\n    va_end(args);\n\n    strcat(fpath->char_path, OS_PATH_SEPARATOR);\n    strncat(fpath->char_path, tmppath, n);\n    filepath_update(fpath);\n}\n\nvoid filepath_set(filepath_t *fpath, const char *path) {\n    if (strlen(path) < MAX_SWITCHPATH) {\n        fpath->valid = VALIDITY_VALID;\n        memset(fpath->char_path, 0, MAX_SWITCHPATH);\n        strncpy(fpath->char_path, path, MAX_SWITCHPATH);\n        filepath_update(fpath);\n    } else {\n        fpath->valid = VALIDITY_INVALID;\n    }\n}\n\noschar_t *filepath_get(filepath_t *fpath) {\n    if (fpath->valid == VALIDITY_INVALID)\n        return NULL;\n    else\n        return fpath->os_path;\n}\n"
  },
  {
    "path": "src/filepath.h",
    "content": "#pragma once\n\n#include \"types.h\"\n#include <dirent.h>\n#ifdef _WIN32\n#include <direct.h>\n#include <wchar.h>\n#endif\n\n#define MAX_SWITCHPATH 0x300\n\ntypedef enum {\n    VALIDITY_UNCHECKED = 0,\n    VALIDITY_INVALID,\n    VALIDITY_VALID\n} validity_t;\n\n#ifdef _MSC_VER\ninline int fseeko64(FILE *__stream, long long __off, int __whence)\n{\n    return _fseeki64(__stream, __off, __whence);\n}\n#else\n    /* off_t is 64-bit with large file support */\n    #define fseeko64 fseek\n#endif\n\n#ifdef _WIN32\ntypedef wchar_t oschar_t; /* utf-16 */\ntypedef _WDIR osdir_t;\ntypedef struct _wdirent osdirent_t;\ntypedef struct _stati64 os_stat64_t;\n\n#define os_fopen _wfopen\n#define os_opendir _wopendir\n#define os_closedir _wclosedir\n#define os_readdir _wreaddir\n#define os_stat _wstati64\n#define os_fclose fclose\n\n#define OS_MODE_READ L\"rb\"\n#define OS_MODE_WRITE L\"wb\"\n#define OS_MODE_EDIT L\"rb+\"\n#else\ntypedef char oschar_t; /* utf-8 */\ntypedef DIR osdir_t;\ntypedef struct dirent osdirent_t;\ntypedef struct stat os_stat64_t;\n\n#define os_fopen fopen\n#define os_opendir opendir\n#define os_closedir closedir\n#define os_readdir readdir\n#define os_stat stat\n#define os_fclose fclose\n\n#define OS_MODE_READ \"rb\"\n#define OS_MODE_WRITE \"wb\"\n#define OS_MODE_EDIT \"rb+\"\n#endif\n\n#define OS_PATH_SEPARATOR \"/\"\n\ntypedef struct filepath {\n    char char_path[MAX_SWITCHPATH];\n    oschar_t os_path[MAX_SWITCHPATH];\n    validity_t valid;\n} filepath_t;\n\nvoid os_strncpy(oschar_t *dst, const char *src, size_t size);\nvoid os_strncpy_to_char(char *dst, const oschar_t *src, size_t size);\nint os_makedir(const oschar_t *dir);\nint os_rmdir(const oschar_t *dir);\n\nvoid filepath_init(filepath_t *fpath);\nvoid filepath_copy(filepath_t *fpath, filepath_t *copy);\nvoid filepath_os_append(filepath_t *fpath, oschar_t *path);\nvoid filepath_append(filepath_t *fpath, const char *format, ...);\nvoid filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...);\nvoid filepath_set(filepath_t *fpath, const char *path);\noschar_t *filepath_get(filepath_t *fpath);\n"
  },
  {
    "path": "src/nacptool.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <inttypes.h>\n\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint8_t u8;\n\ntypedef struct {\n    char name[0x200];\n    char author[0x100];\n} NacpLanguageEntry;\n\ntypedef struct {\n    NacpLanguageEntry lang[12];\n    NacpLanguageEntry lang_unk[4];//?\n\n    u8  x3000_unk[0x24];////Normally all-zero?\n    u32 x3024_unk;\n    u32 x3028_unk;\n    u32 x302C_unk;\n    u32 x3030_unk;\n    u32 x3034_unk;\n    u64 titleid0;\n\n    u8 x3040_unk[0x20];\n    char version[0x10];\n\n    u64 titleid_dlcbase;\n    u64 titleid1;\n\n    u32 x3080_unk;\n    u32 x3084_unk;\n    u32 x3088_unk;\n    u8 x308C_unk[0x24];//zeros?\n\n    u64 titleid2;\n    u64 titleids[7];//\"Array of application titleIDs, normally the same as the above app-titleIDs. Only set for game-updates?\"\n\n    u32 x30F0_unk;\n    u32 x30F4_unk;\n\n    u64 titleid3;//\"Application titleID. Only set for game-updates?\"\n\n    char bcat_passphrase[0x40];\n    u8 x3140_unk[0xEC0];//Normally all-zero?\n} NacpStruct;\n\nint main(int argc, char* argv[]) {\n    if (argc < 6 || strncmp(argv[1], \"--create\", 8)!=0) {\n        fprintf(stderr, \"%s --create <name> <author> <version> <outfile> [options]\\n\\n\", argv[0]);\n        fprintf(stderr, \"FLAGS:\\n\");\n        fprintf(stderr, \"--create : Create control.nacp for use with Switch homebrew applications.\\n\");\n        fprintf(stderr, \"Options:\\n\");\n        fprintf(stderr, \"--titleid=<titleID> Set the application titleID.\\n\");\n        return EXIT_FAILURE;\n    }\n\n    NacpStruct nacp;\n    memset(&nacp, 0, sizeof(nacp));\n\n    if (sizeof(NacpStruct) != 0x4000) {\n        fprintf(stderr, \"Bad compile environment!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    char *name = argv[2];\n    char *author = argv[3];\n    char *names[12];\n    char *authors[12];\n\n    int i;\n    for (i=0; i<12; i++) {\n        names[i] = name;\n        authors[i] = author;\n    }\n\n    int argi;\n    u64 titleid=0;\n    for (argi=6; argi<argc; argi++) {\n        if (strncmp(argv[argi], \"--titleid=\", 10)==0) sscanf(&argv[argi][10], \"%016\" SCNx64, &titleid);\n    }\n\n    for (i=0; i<12; i++) {//These are UTF-8.\n        strncpy(nacp.lang[i].name, names[i], sizeof(nacp.lang[i].name)-1);\n        strncpy(nacp.lang[i].author, authors[i], sizeof(nacp.lang[i].author)-1);\n    }\n\n    strncpy(nacp.version, argv[4], sizeof(nacp.version)-1);\n\n    if (titleid) {\n        nacp.titleid0 = titleid;\n        nacp.titleid_dlcbase = titleid+0x1000;\n        nacp.titleid1 = titleid;\n        nacp.titleid2 = titleid;\n    }\n\n    u8 unk_data[0x20] = {0x0C, 0xFF, 0xFF, 0x0A, 0xFF, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\n\n    nacp.x3024_unk = 0x100;\n    nacp.x302C_unk = 0xbff;\n    nacp.x3034_unk = 0x10000;\n\n    memcpy(nacp.x3040_unk, unk_data, sizeof(unk_data));\n\n    nacp.x3080_unk = 0x3e00000;\n    nacp.x3088_unk = 0x180000;\n    nacp.x30F0_unk = 0x102;\n\n    FILE* out = fopen(argv[5], \"wb\");\n\n    if (out == NULL) {\n        fprintf(stderr, \"Failed to open output file!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    fwrite(&nacp, sizeof(nacp), 1, out);\n\n    fclose(out);\n\n    return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/npdmtool.c",
    "content": "// Copyright 2018 SciresM\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <errno.h>\n#include <limits.h>\n#include \"cJSON.h\"\n\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAGIC_META 0x4154454D\n#define MAGIC_ACID 0x44494341\n#define MAGIC_ACI0 0x30494341\n\n/* FAC, FAH need to be tightly packed. */\n#pragma pack(push, 1)\ntypedef struct {\n    u8 Version;\n    u8 CoiCount;\n    u8 SdoiCount;\n    u8 pad;\n    u64 Perms;\n    u64 CoiMin;\n    u64 CoiMax;\n    u64 SdoiMin;\n    u64 SdoiMax;\n} FilesystemAccessControl;\n#pragma pack(pop)\n\n#pragma pack(push, 1)\ntypedef struct {\n    u32 Version;\n    u64 Perms;\n    u32 CoiOffset;\n    u32 CoiSize;\n    u32 SdoiOffset;\n    u32 SdoiSize;\n} FilesystemAccessHeader;\n#pragma pack(pop)\n\ntypedef struct {\n    u32 Magic;\n    u8 _0x4[0xC];\n    u64 ProgramId;\n    u64 _0x18;\n    u32 FahOffset;\n    u32 FahSize;\n    u32 SacOffset;\n    u32 SacSize;\n    u32 KacOffset;\n    u32 KacSize;\n    u64 Padding;\n} NpdmAci0;\n\ntypedef struct {\n    u8 Signature[0x100];\n    u8 Modulus[0x100];\n    u32 Magic;\n    u32 Size;\n    u32 _0x208;\n    u32 Flags;\n    u64 ProgramIdRangeMin;\n    u64 ProgramIdRangeMax;\n    u32 FacOffset;\n    u32 FacSize;\n    u32 SacOffset;\n    u32 SacSize;\n    u32 KacOffset;\n    u32 KacSize;\n    u64 Padding;\n} NpdmAcid;\n\ntypedef struct {\n    u32 Magic;\n    u32 SignatureKeyGeneration;\n    u32 _0x8;\n    u8 MmuFlags;\n    u8 _0xD;\n    u8 MainThreadPriority;\n    u8 DefaultCpuId;\n    u32 _0x10;\n    u32 SystemResourceSize;\n    u32 Version;\n    u32 MainThreadStackSize;\n    char Name[0x10];\n    char ProductCode[0x10];\n    u8 _0x40[0x30];\n    u32 Aci0Offset;\n    u32 Aci0Size;\n    u32 AcidOffset;\n    u32 AcidSize;\n} NpdmHeader;\n\n\nuint8_t* ReadEntireFile(const char* fn, size_t* len_out) {\n    FILE* fd = fopen(fn, \"rb\");\n    if (fd == NULL)\n        return NULL;\n\n    fseek(fd, 0, SEEK_END);\n    size_t len = ftell(fd);\n    fseek(fd, 0, SEEK_SET);\n\n    uint8_t* buf = malloc(len);\n    if (buf == NULL) {\n        fclose(fd);\n        return NULL;\n    }\n\n    size_t rc = fread(buf, 1, len, fd);\n    if (rc != len) {\n        fclose(fd);\n        free(buf);\n        return NULL;\n    }\n\n    *len_out = len;\n    return buf;\n}\n\nint cJSON_GetString(const cJSON *obj, const char *field, const char **out) {\n  const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n  if (cJSON_IsString(config)) {\n    *out = config->valuestring;\n    return 1;\n  } else {\n    fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n    return 0;\n  }\n}\n\nint cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsNumber(config)) {\n        *out = (u8)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsNumber(config)) {\n        *out = (u16)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {\n    if (cJSON_IsNumber(config)) {\n        *out = (u16)config->valueint;\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", config->string);\n        return 0;\n    }\n}\n\nint cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsBool(config)) {\n        if (cJSON_IsTrue(config)) {\n            *out = 1;\n        } else if (cJSON_IsFalse(config)) {\n            *out = 0;\n        } else {\n            fprintf(stderr, \"Unknown boolean value in %s.\\n\", field);\n            return 0;\n        }\n        return 1;\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsBool(config)) {\n        if (cJSON_IsTrue(config)) {\n            *out = 1;\n        } else if (cJSON_IsFalse(config)) {\n            *out = 0;\n        } else {\n            fprintf(stderr, \"Unknown boolean value in %s.\\n\", field);\n            return 0;\n        }\n    } else {\n        *out = 0;\n    }\n    return 1;\n}\n\nint cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoull(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", field);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", field);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", field);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", field);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {\n    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoul(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", field);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", field);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", field);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", field);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", field);\n        return 0;\n    }\n}\n\nint cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {\n    if (cJSON_IsString(config) && (config->valuestring != NULL)) {\n        char *endptr = NULL;\n        *out = strtoull(config->valuestring, &endptr, 16);\n        if (config->valuestring == endptr) {\n            fprintf(stderr, \"Failed to get %s (empty string)\\n\", config->string);\n            return 0;\n        } else if (errno == ERANGE) {\n            fprintf(stderr, \"Failed to get %s (value out of range)\\n\", config->string);\n            return 0;\n        } else if (errno == EINVAL) {\n            fprintf(stderr, \"Failed to get %s (not base16 string)\\n\", config->string);\n            return 0;\n        } else if (errno) {\n            fprintf(stderr, \"Failed to get %s (unknown error)\\n\", config->string);\n            return 0;\n        } else {\n            return 1;\n        }\n    } else {\n        fprintf(stderr, \"Failed to get %s (field not present).\\n\", config->string);\n        return 0;\n    }\n}\n\nint CreateNpdm(const char *json, void **dst, u32 *dst_size) {\n    NpdmHeader header = {0};\n    NpdmAci0 *aci0 = calloc(1, 0x100000);\n    NpdmAcid *acid = calloc(1, 0x100000);\n    if (aci0 == NULL || acid == NULL) {\n        fprintf(stderr, \"Failed to allocate NPDM resources!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    const cJSON *capability = NULL;\n    const cJSON *capabilities = NULL;\n    const cJSON *service = NULL;\n    const cJSON *services = NULL;\n    const cJSON *fsaccess = NULL;\n    const cJSON *cois = NULL;\n    const cJSON *coi = NULL;\n    const cJSON *sdois = NULL;\n    const cJSON *sdoi = NULL;\n\n    int status = 0;\n    cJSON *npdm_json = cJSON_Parse(json);\n    if (npdm_json == NULL) {\n        const char *error_ptr = cJSON_GetErrorPtr();\n        if (error_ptr != NULL) {\n            fprintf(stderr, \"JSON Parse Error: %s\\n\", error_ptr);\n        }\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    /* Initialize default NPDM values. */\n    header.Magic = MAGIC_META; /* \"META\" */\n\n\n    /* Parse name. */\n    const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, \"name\");\n    if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {\n        strncpy(header.Name, title_name->valuestring, sizeof(header.Name) - 1);\n    } else {\n        fprintf(stderr, \"Failed to get title name (name field not present).\\n\");\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    /* Parse main_thread_stack_size. */\n    u64 stack_size = 0;\n    if (!cJSON_GetU64(npdm_json, \"main_thread_stack_size\", &stack_size)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    if (stack_size >> 32) {\n        fprintf(stderr, \"Error: Main thread stack size must be a u32!\\n\");\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    header.MainThreadStackSize = (u32)(stack_size & 0xFFFFFFFF);\n\n    /* Parse various config. */\n    if (!cJSON_GetU8(npdm_json, \"main_thread_priority\", &header.MainThreadPriority)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    if (!cJSON_GetU8(npdm_json, \"default_cpu_id\", &header.DefaultCpuId)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    cJSON_GetU32(npdm_json, \"system_resource_size\", &header.SystemResourceSize); // optional\n\n    /* Get version (deprecated name \"process_category\"). */\n    if (!cJSON_GetU32(npdm_json, \"version\", &header.Version) && !cJSON_GetU32(npdm_json, \"process_category\", &header.Version)) { // optional\n        header.Version = 0;\n    }\n\n    if (!cJSON_GetU8(npdm_json, \"address_space_type\", (u8 *)&header.MmuFlags)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    header.MmuFlags &= 3;\n    header.MmuFlags <<= 1;\n    int is_64_bit;\n    if (!cJSON_GetBoolean(npdm_json, \"is_64_bit\", &is_64_bit)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    header.MmuFlags |= is_64_bit;\n\n    int optimize_memory_allocation; // optional\n    if (cJSON_GetBoolean(npdm_json, \"optimize_memory_allocation\", &optimize_memory_allocation)) {\n        header.MmuFlags |= ((optimize_memory_allocation & 1) << 4);\n    }\n\n    int disable_device_address_space_merge; // optional\n    if (cJSON_GetBoolean(npdm_json, \"disable_device_address_space_merge\", &disable_device_address_space_merge)) {\n        header.MmuFlags |= ((disable_device_address_space_merge & 1) << 5);\n    }\n\n    int enable_alias_region_extra_size; // optional\n    if (cJSON_GetBoolean(npdm_json, \"enable_alias_region_extra_size\", &enable_alias_region_extra_size)) {\n        header.MmuFlags |= ((enable_alias_region_extra_size & 1) << 6);\n    }\n\n    int prevent_code_reads; // optional\n    if (cJSON_GetBoolean(npdm_json, \"prevent_code_reads\", &prevent_code_reads)) {\n        header.MmuFlags |= ((prevent_code_reads & 1) << 7);\n    }\n\n    u8 signature_key_generation; // optional\n    if (cJSON_GetU8(npdm_json, \"signature_key_generation\", &signature_key_generation)) {\n        header.SignatureKeyGeneration = signature_key_generation;\n    } else {\n        header.SignatureKeyGeneration = 0;\n    }\n\n    /* ACID. */\n    memset(acid->Signature, 0, sizeof(acid->Signature));\n    memset(acid->Modulus, 0, sizeof(acid->Modulus));\n    acid->Magic = MAGIC_ACID; /* \"ACID\" */\n    int is_retail;\n    if (!cJSON_GetBoolean(npdm_json, \"is_retail\", &is_retail)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    acid->Flags |= is_retail;\n    u8 pool_partition;\n    if (!cJSON_GetU8(npdm_json, \"pool_partition\", &pool_partition)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    acid->Flags |= (pool_partition & 3) << 2;\n\n    if (!cJSON_GetU64(npdm_json, \"program_id_range_min\", &acid->ProgramIdRangeMin) && !cJSON_GetU64(npdm_json, \"title_id_range_min\", &acid->ProgramIdRangeMin)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n    if (!cJSON_GetU64(npdm_json, \"program_id_range_max\", &acid->ProgramIdRangeMax) && !cJSON_GetU64(npdm_json, \"title_id_range_max\", &acid->ProgramIdRangeMax)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    /* ACI0. */\n    aci0->Magic = MAGIC_ACI0; /* \"ACI0\" */\n    /* Parse program_id (or deprecated title_id). */\n    if (!cJSON_GetU64(npdm_json, \"program_id\", &aci0->ProgramId) && !cJSON_GetU64(npdm_json, \"title_id\", &aci0->ProgramId)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    /* Fac. */\n    fsaccess = cJSON_GetObjectItemCaseSensitive(npdm_json, \"filesystem_access\");\n    if (!cJSON_IsObject(fsaccess)) {\n        fprintf(stderr, \"Filesystem Access must be an object!\\n\");\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    FilesystemAccessControl *fac = (FilesystemAccessControl *)((u8 *)acid + sizeof(NpdmAcid));\n    fac->Version = 1;\n    if (!cJSON_GetU64(fsaccess, \"permissions\", &fac->Perms)) {\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    fac->CoiMin    = 0;\n    fac->CoiMax    = 0;\n    fac->SdoiMin   = 0;\n    fac->SdoiMax   = 0;\n    fac->CoiCount  = 0;\n    fac->SdoiCount = 0;\n\n    acid->FacOffset = sizeof(NpdmAcid);\n    acid->FacSize = sizeof(FilesystemAccessControl);\n    acid->SacOffset = (acid->FacOffset + acid->FacSize + 0xF) & ~0xF;\n\n    /* Fah. */\n    FilesystemAccessHeader *fah = (FilesystemAccessHeader *)((u8 *)aci0 + sizeof(NpdmAci0));\n    fah->Version = 1;\n    fah->Perms = fac->Perms;\n    fah->CoiOffset = sizeof(FilesystemAccessHeader);\n    fah->CoiSize   = 0;\n\n    cois = cJSON_GetObjectItemCaseSensitive(fsaccess, \"content_owner_ids\");\n    if (cJSON_IsArray(cois)) {\n        u32 *count = (u32 *)((u8 *)fah + fah->CoiOffset);\n        u64 *id = (u64 *)((u8 *)count + sizeof(u32));\n        cJSON_ArrayForEach(coi, cois) {\n            if (!cJSON_GetU64FromObjectValue(coi, id)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            ++id;\n            ++(*count);\n        }\n\n        if (*count > 0) {\n            fah->CoiSize = sizeof(u32) + sizeof(u64) * (*count);\n        }\n    }\n\n    fah->SdoiOffset = fah->CoiOffset + fah->CoiSize;\n    fah->SdoiSize   = 0;\n\n    sdois = cJSON_GetObjectItemCaseSensitive(fsaccess, \"save_data_owner_ids\");\n    if (cJSON_IsArray(sdois)) {\n        u32 *count = (u32 *)((u8 *)fah + fah->SdoiOffset);\n        cJSON_ArrayForEach(sdoi, sdois) {\n            if (!cJSON_IsObject(sdoi)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            ++(*count);\n        }\n\n        u8 *accessibility = (u8 *)count + sizeof(u32);\n        u64 *id = (u64 *)(accessibility + (((*count) + 3ULL) & ~3ULL));\n\n        cJSON_ArrayForEach(sdoi, sdois) {\n            if (!cJSON_GetU8(sdoi, \"accessibility\", accessibility)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            if (!cJSON_GetU64(sdoi, \"id\", id)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n\n            ++accessibility;\n            ++id;\n        }\n\n        if (*count > 0) {\n            fah->SdoiSize = sizeof(u32) + sizeof(u8) * ((((*count) + 3ULL) & ~3ULL)) + sizeof(u64) * (*count);\n        }\n    }\n\n    aci0->FahOffset = sizeof(NpdmAci0);\n    aci0->FahSize = sizeof(FilesystemAccessHeader) + fah->CoiSize + fah->SdoiSize;\n    aci0->SacOffset = (aci0->FahOffset + aci0->FahSize + 0xF) & ~0xF;\n\n    /* Sac. */\n    u8 *sac = (u8*)aci0 + aci0->SacOffset;\n    u32 sac_size = 0;\n\n    services = cJSON_GetObjectItemCaseSensitive(npdm_json, \"service_host\");\n    if (services != NULL && !cJSON_IsArray(services)) {\n        fprintf(stderr, \"Service Host must be an array!\\n\");\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    cJSON_ArrayForEach(service, services) {\n        int is_host = 1;\n        char *service_name;\n\n        if (!cJSON_IsString(service)) {\n            fprintf(stderr, \"service_access must be an array of string\\n\");\n            status = 0;\n            goto NPDM_BUILD_END;\n        }\n        service_name = service->valuestring;\n\n        int cur_srv_len = strlen(service_name);\n        if (cur_srv_len > 8 || cur_srv_len == 0) {\n            fprintf(stderr, \"Services must have name length 1 <= len <= 8!\\n\");\n            status = 0;\n            goto NPDM_BUILD_END;\n        }\n        u8 ctrl = (u8)(cur_srv_len - 1);\n        if (is_host) {\n            ctrl |= 0x80;\n        }\n        sac[sac_size++] = ctrl;\n        memcpy(sac + sac_size, service_name, cur_srv_len);\n        sac_size += cur_srv_len;\n    }\n\n    services = cJSON_GetObjectItemCaseSensitive(npdm_json, \"service_access\");\n    if (!(services == NULL || cJSON_IsObject(services) || cJSON_IsArray(services))) {\n      fprintf(stderr, \"Service Access must be an array!\\n\");\n      status = 0;\n      goto NPDM_BUILD_END;\n    }\n\n    int sac_obj = 0;\n    if (services != NULL && cJSON_IsObject(services)) {\n      sac_obj = 1;\n      fprintf(stderr, \"Using deprecated service_access format. Please turn it into an array.\\n\");\n    }\n\n    cJSON_ArrayForEach(service, services) {\n        int is_host = 0;\n        char *service_name;\n\n        if (sac_obj) {\n            if (!cJSON_IsBool(service)) {\n                fprintf(stderr, \"Services must be of form service_name (str) : is_host (bool)\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            is_host = cJSON_IsTrue(service);\n            service_name = service->string;\n        } else {\n            if (!cJSON_IsString(service)) {\n                fprintf(stderr, \"service_access must be an array of string\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            is_host = 0;\n            service_name = service->valuestring;\n        }\n\n        int cur_srv_len = strlen(service_name);\n        if (cur_srv_len > 8 || cur_srv_len == 0) {\n            fprintf(stderr, \"Services must have name length 1 <= len <= 8!\\n\");\n            status = 0;\n            goto NPDM_BUILD_END;\n        }\n        u8 ctrl = (u8)(cur_srv_len - 1);\n        if (is_host) {\n            ctrl |= 0x80;\n        }\n        sac[sac_size++] = ctrl;\n        memcpy(sac + sac_size, service_name, cur_srv_len);\n        sac_size += cur_srv_len;\n    }\n\n\n    memcpy((u8 *)acid + acid->SacOffset, sac, sac_size);\n    aci0->SacSize = sac_size;\n    acid->SacSize = sac_size;\n    aci0->KacOffset = (aci0->SacOffset + aci0->SacSize + 0xF) & ~0xF;\n    acid->KacOffset = (acid->SacOffset + acid->SacSize + 0xF) & ~0xF;\n\n    /* Parse capabilities. */\n    capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, \"kernel_capabilities\");\n    if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {\n        fprintf(stderr, \"Kernel Capabilities must be an array!\\n\");\n        status = 0;\n        goto NPDM_BUILD_END;\n    }\n\n    int kac_obj = 0;\n    if (cJSON_IsObject(capabilities)) {\n        kac_obj = 1;\n        fprintf(stderr, \"Using deprecated kernel_capabilities format. Please turn it into an array.\\n\");\n    }\n\n    u32 *caps = (u32 *)((u8 *)aci0 + aci0->KacOffset);\n    u32 cur_cap = 0;\n    u32 desc;\n    cJSON_ArrayForEach(capability, capabilities) {\n        desc = 0;\n        const char *type_str;\n        const cJSON *value;\n\n        if (kac_obj) {\n          type_str = capability->string;\n          value = capability;\n        } else {\n          if (!cJSON_GetString(capability, \"type\", &type_str)) {\n            status = 0;\n            goto NPDM_BUILD_END;\n          }\n          value = cJSON_GetObjectItemCaseSensitive(capability, \"value\");\n        }\n\n        if (!strcmp(type_str, \"kernel_flags\")) {\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Kernel Flags Capability value must be object!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;\n            if (!cJSON_GetU8(value, \"highest_thread_priority\", &highest_prio) ||\n                !cJSON_GetU8(value, \"lowest_thread_priority\", &lowest_prio) ||\n                !cJSON_GetU8(value, \"highest_cpu_id\", &highest_cpu) ||\n                !cJSON_GetU8(value, \"lowest_cpu_id\", &lowest_cpu)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n\n            u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;\n            u8 real_lowest_prio  = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;\n\n            desc = highest_cpu;\n            desc <<= 8;\n            desc |= lowest_cpu;\n            desc <<= 6;\n            desc |= (real_highest_prio & 0x3F);\n            desc <<= 6;\n            desc |= (real_lowest_prio & 0x3F);\n            caps[cur_cap++] = (u32)((desc << 4) | (0x0007));\n        } else if (!strcmp(type_str, \"syscalls\")) {\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Syscalls Capability value must be object!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            u32 num_descriptors;\n            u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */\n            char field_name[8] = {0};\n            const cJSON *cur_syscall = NULL;\n            u64 syscall_value = 0;\n            cJSON_ArrayForEach(cur_syscall, value) {\n                if (cJSON_IsNumber(cur_syscall)) {\n                    syscall_value = (u64)cur_syscall->valueint;\n                } else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {\n                    fprintf(stderr, \"Error: Syscall entries must be integers or hex strings.\\n\");\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n\n                if (syscall_value >= 0xC0) {\n                    fprintf(stderr, \"Error: All syscall entries must be numbers in [0, 0xBF]\\n\");\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n                descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));\n            }\n            for (unsigned int i = 0; i < 8; i++) {\n                if (descriptors[i]) {\n                    desc = descriptors[i] | (i << 24);\n                    caps[cur_cap++] = (u32)((desc << 5) | (0x000F));\n                }\n            }\n        } else if (!strcmp(type_str, \"map\")) {\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Map Capability value must be object!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            u64 map_address = 0;\n            u64 map_size = 0;\n            int is_ro;\n            int is_io;\n            if (!cJSON_GetU64(value, \"address\", &map_address) ||\n                !cJSON_GetU64(value, \"size\", &map_size) ||\n                !cJSON_GetBoolean(value, \"is_ro\", &is_ro) ||\n                !cJSON_GetBoolean(value, \"is_io\", &is_io)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);\n            desc |= is_ro << 24;\n            caps[cur_cap++] = (u32)((desc << 7) | (0x003F));\n\n            desc = (u32)((map_size >> 12) & 0x000FFFFFULL);\n            desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);\n            is_io ^= 1;\n            desc |= is_io << 24;\n            caps[cur_cap++] = (u32)((desc << 7) | (0x003F));\n        } else if (!strcmp(type_str, \"map_page\")) {\n            u64 page_address = 0;\n            if (!cJSON_GetU64FromObjectValue(value, &page_address)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);\n            caps[cur_cap++] = (u32)((desc << 8) | (0x007F));\n        } else if (!strcmp(type_str, \"map_region\")) {\n            if (cur_cap + 1 > 0x20) {\n                fprintf(stderr, \"Error: Too many capabilities!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            if (!cJSON_IsArray(value)) {\n                fprintf(stderr, \"Map Region capability value must be array!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            u8 regions[3] = {0};\n            int is_ro[3] = {0};\n            const cJSON *cur_region = NULL;\n            int index = 0;\n            cJSON_ArrayForEach(cur_region, value) {\n                if (index >= 3) {\n                    fprintf(stderr, \"Too many region descriptors!\\n\");\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n                if (!cJSON_IsObject(cur_region)) {\n                    fprintf(stderr, \"Region descriptor value must be object!\\n\");\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n\n                if (!cJSON_GetU8(cur_region, \"region_type\", &regions[index]) ||\n                    !cJSON_GetBoolean(cur_region, \"is_ro\", &is_ro[index])) {\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n\n                index++;\n            }\n\n            u32 capability = 0x3FF;\n            for (int i = 0; i < 3; ++i) {\n                capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);\n            }\n            caps[cur_cap++] = capability;\n        } else if (!strcmp(type_str, \"irq_pair\")) {\n            if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {\n                fprintf(stderr, \"Error: IRQ Pairs must have size 2 array value.\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            const cJSON *irq = NULL;\n            int desc_idx = 0;\n            cJSON_ArrayForEach(irq, value) {\n                if (cJSON_IsNull(irq)) {\n                    desc |= 0x3FF << desc_idx;\n                } else if (cJSON_IsNumber(irq)) {\n                    desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;\n                } else {\n                    fprintf(stderr, \"Failed to parse IRQ value.\\n\");\n                    status = 0;\n                    goto NPDM_BUILD_END;\n                }\n                desc_idx += 10;\n            }\n            caps[cur_cap++] = (u32)((desc << 12) | (0x07FF));\n        } else if (!strcmp(type_str, \"application_type\")) {\n            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            desc &= 7;\n            caps[cur_cap++] = (u32)((desc << 14) | (0x1FFF));\n        } else if (!strcmp(type_str, \"min_kernel_version\")) {\n            u64 kern_ver = 0;\n            if (cJSON_IsNumber(value)) {\n                kern_ver = (u64)value->valueint;\n            } else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {\n                fprintf(stderr, \"Error: Kernel version must be integer or hex strings.\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            desc = (kern_ver) & 0xFFFF;\n            caps[cur_cap++] = (u32)((desc << 15) | (0x3FFF));\n        } else if (!strcmp(type_str, \"handle_table_size\")) {\n            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            caps[cur_cap++] = (u32)((desc << 16) | (0x7FFF));\n        } else if (!strcmp(type_str, \"debug_flags\")) {\n            if (!cJSON_IsObject(value)) {\n                fprintf(stderr, \"Debug Flag Capability value must be object!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            int allow_debug = 0;\n            int force_debug = 0;\n            int force_debug_prod = 0;\n            cJSON_GetBoolean(value, \"allow_debug\", &allow_debug);\n            cJSON_GetBoolean(value, \"force_debug\", &force_debug);\n            cJSON_GetBoolean(value, \"force_debug_prod\", &force_debug_prod);\n            if ( allow_debug + force_debug + force_debug_prod > 1 ) {\n                fprintf(stderr, \"Only one of allow_debug, force_debug, or force_debug_prod can be set!\\n\");\n                status = 0;\n                goto NPDM_BUILD_END;\n            }\n            desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);\n            caps[cur_cap++] = (u32)((desc << 17) | (0xFFFF));\n        }\n    }\n    aci0->KacSize = cur_cap * sizeof(u32);\n    acid->KacSize = aci0->KacSize;\n    memcpy((u8 *)acid + acid->KacOffset, caps, aci0->KacSize);\n\n    header.AcidOffset = sizeof(header);\n    header.AcidSize = acid->KacOffset + acid->KacSize;\n    acid->Size = header.AcidSize - sizeof(acid->Signature);\n    header.Aci0Offset = (header.AcidOffset + header.AcidSize + 0xF) & ~0xF;\n    header.Aci0Size = aci0->KacOffset + aci0->KacSize;\n    u32 total_size = header.Aci0Offset + header.Aci0Size;\n    u8 *npdm = calloc(1, total_size);\n    if (npdm == NULL) {\n        fprintf(stderr, \"Failed to allocate output!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    memcpy(npdm, &header, sizeof(header));\n    memcpy(npdm + header.AcidOffset, acid, header.AcidSize);\n    memcpy(npdm + header.Aci0Offset, aci0, header.Aci0Size);\n    free(acid);\n    free(aci0);\n    *dst = npdm;\n    *dst_size = total_size;\n\n    status = 1;\n    NPDM_BUILD_END:\n    cJSON_Delete(npdm_json);\n    return status;\n}\n\nint main(int argc, char* argv[]) {\n    if (argc != 3) {\n        fprintf(stderr, \"%s <json-file> <npdm-file>\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n\n    void *npdm;\n    u32 npdm_size;\n\n    if (sizeof(NpdmHeader) != 0x80 || sizeof(NpdmAcid) != 0x240 || sizeof(NpdmAci0) != 0x40) {\n        fprintf(stderr, \"Bad compile environment!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    size_t json_len;\n    uint8_t* json = ReadEntireFile(argv[1], &json_len);\n    if (json == NULL) {\n        fprintf(stderr, \"Failed to read descriptor json!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    if (!CreateNpdm(json, &npdm, &npdm_size)) {\n        fprintf(stderr, \"Failed to parse descriptor json!\\n\");\n        return EXIT_FAILURE;\n    }\n\n    FILE *f_out = fopen(argv[2], \"wb\");\n    if (f_out == NULL) {\n        fprintf(stderr, \"Failed to open %s for writing!\\n\", argv[2]);\n        return EXIT_FAILURE;\n    }\n    if (fwrite(npdm, 1, npdm_size, f_out) != npdm_size) {\n        fprintf(stderr, \"Failed to write NPDM to %s!\\n\", argv[2]);\n        return EXIT_FAILURE;\n    }\n    fclose(f_out);\n    free(npdm);\n\n    return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/nxlink.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <sys/time.h>\n#include <stdint.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <errno.h>\n\n#ifndef __WIN32__\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <poll.h>\n#define closesocket close\n#else\n#include <winsock2.h>\n#include <ws2tcpip.h>\ntypedef int socklen_t;\ntypedef uint32_t in_addr_t;\n#define SHUT_RD SD_RECEIVE\n#define SHUT_WR SD_SEND\n#define SHUT_RDWR SD_BOTH\n#ifdef EWOULDBLOCK\n#undef EWOULDBLOCK\n#endif\n#define EWOULDBLOCK WSAEWOULDBLOCK\n#define poll WSAPoll\n#endif\n\n#include <zlib.h>\n#include <assert.h>\n\n#define ZLIB_CHUNK (16 * 1024)\n\n#define NETLOADER_SERVER_PORT 28280\n#define NETLOADER_CLIENT_PORT 28771\n\n\nstatic char cmdbuf[3072];\nstatic uint32_t cmdlen=0;\n\n//---------------------------------------------------------------------------------\nstatic void shutdownSocket(int socket, int flags) {\n//---------------------------------------------------------------------------------\n\tif (flags)\n\t\tshutdown(socket, flags);\n\tclosesocket(socket);\n}\n\n//---------------------------------------------------------------------------------\nstatic int setSocketNonblocking(int sock) {\n//---------------------------------------------------------------------------------\n\n#ifndef __WIN32__\n\tint flags = fcntl(sock, F_GETFL);\n\n\tif (flags == -1) return -1;\n\n\tint rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);\n\n\tif (rc != 0) return -1;\n#else\n\tu_long iMode = 1; // non-blocking\n\n\tint rc = ioctlsocket(sock, FIONBIO, &iMode);\n\n\tif (rc != NO_ERROR) return -1;\n#endif\n\n\treturn 0;\n}\n\n//---------------------------------------------------------------------------------\nstatic int socketError(const char *msg) {\n//---------------------------------------------------------------------------------\n#ifndef _WIN32\n\tint ret = errno;\n\tif (ret == EAGAIN)\n\t\tret = EWOULDBLOCK;\n\tperror(msg);\n#else\n\tint ret = WSAGetLastError();\n\twchar_t *s = NULL;\n\tFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n               NULL, ret,\n               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n               (LPWSTR)&s, 0, NULL);\n\tfprintf(stderr, \"%S\\n\", s);\n\tLocalFree(s);\n\tif (ret == WSAEWOULDBLOCK)\n\t\tret = EWOULDBLOCK;\n#endif\n\n\treturn ret;\n}\n\n//---------------------------------------------------------------------------------\nint pollSocket(int fd, int events, int timeout) {\n//---------------------------------------------------------------------------------\n#ifndef __WIN32__\n\tstruct pollfd pfd;\n#else\n\tWSAPOLLFD pfd;\n#endif\n\n\tpfd.fd = fd;\n\tpfd.events = events;\n\tpfd.revents = 0;\n\n\tint ret = poll(&pfd, 1, timeout);\n\tif (ret < 0) {\n\t\tsocketError(\"poll\");\n\t\treturn -1;\n\t}\n\n\tif (ret == 0)\n\t\treturn -1;\n\n\tif (!(pfd.revents & events)) {\n\t\tint err = 0;\n\t\tint len = sizeof(err);\n\t\tgetsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len);\n\t\tfprintf(stderr, \"socket error 0x%x on poll\\n\", err);\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n//---------------------------------------------------------------------------------\nstatic struct in_addr findSwitch(int retries) {\n//---------------------------------------------------------------------------------\n\n\tprintf(\"pinging switch\\n\");\n\n\tstruct sockaddr_in s, remote, rs;\n\tchar recvbuf[256];\n\tchar mess[] = \"nxboot\";\n\n\tint broadcastSock = socket(PF_INET, SOCK_DGRAM, 0);\n\tif (broadcastSock < 0) socketError(\"create send socket\");\n\n\tint optval = 1, len;\n\tsetsockopt(broadcastSock, SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval));\n\n\tmemset(&s, '\\0', sizeof(struct sockaddr_in));\n\ts.sin_family = AF_INET;\n\ts.sin_port = htons(NETLOADER_SERVER_PORT);\n\ts.sin_addr.s_addr = INADDR_BROADCAST;\n\n\tmemset(&rs, '\\0', sizeof(struct sockaddr_in));\n\trs.sin_family = AF_INET;\n\trs.sin_port = htons(NETLOADER_CLIENT_PORT);\n\trs.sin_addr.s_addr = INADDR_ANY;\n\n\tint recvSock = socket(PF_INET, SOCK_DGRAM, 0);\n\n\tif (recvSock < 0)  socketError(\"create receive socket\");\n\n\tif (bind(recvSock, (struct sockaddr*) &rs, sizeof(rs)) < 0) socketError(\"bind receive socket\");\n\tsetSocketNonblocking(recvSock);\n\n\twhile (retries) {\n\t\tif (sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(s)) < 0)\n\t\t\tsocketError(\"sendto\");\n\n\t\tif (pollSocket(recvSock, POLLIN, 150) == 0) {\n\t\t\tsocklen_t socklen = sizeof(remote);\n\t\t\tlen = recvfrom(recvSock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&remote, &socklen);\n\t\t\tif (len != -1) {\n\t\t\t\tif (strncmp(\"bootnx\", recvbuf, strlen(\"bootnx\")) == 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t--retries;\n\t}\n\n\tif (retries == 0)\n\t\tremote.sin_addr.s_addr =  INADDR_NONE;\n\n\tshutdownSocket(broadcastSock, 0);\n\tshutdownSocket(recvSock, SHUT_RD);\n\n\treturn remote.sin_addr;\n}\n\n//---------------------------------------------------------------------------------\nstatic int sendData(int sock, int sendsize, void *buffer) {\n//---------------------------------------------------------------------------------\n\tchar *buf = (char*)buffer;\n\twhile (sendsize) {\n\t\tif (pollSocket(sock, POLLOUT, -1))\n\t\t\treturn 1;\n\n\t\tint len = send(sock, buf, sendsize, 0);\n\t\tif (len == 0)\n\t\t\treturn 1;\n\n\t\tif (len == -1) {\n\t\t\tif (socketError(\"send\") != EWOULDBLOCK)\n\t\t\t\treturn 1;\n\t\t} else {\n\t\t\tsendsize -= len;\n\t\t\tbuf += len;\n\t\t}\n\t}\n\n\treturn sendsize != 0;\n}\n\n//---------------------------------------------------------------------------------\nstatic int recvData(int sock, void *buffer, int size, int flags) {\n//---------------------------------------------------------------------------------\n\tint len, sizeleft = size;\n\tchar *buf = (char*)buffer;\n\twhile (sizeleft) {\n\t\tif (pollSocket(sock, POLLIN, -1))\n\t\t\treturn 0;\n\n\t\tlen = recv(sock,buf,sizeleft,flags);\n\t\tif (len == 0)\n\t\t\treturn 0;\n\n\t\tif (len == -1) {\n\t\t\tif (socketError(\"recv\") != EWOULDBLOCK)\n\t\t\t\treturn 0;\n\t\t} else {\n\t\t\tsizeleft -=len;\n\t\t\tbuf +=len;\n\t\t}\n\t}\n\n\treturn size;\n}\n\n\n//---------------------------------------------------------------------------------\nstatic int sendInt32LE(int socket, uint32_t size) {\n//---------------------------------------------------------------------------------\n\tunsigned char lenbuf[4];\n\tlenbuf[0] = size & 0xff;\n\tlenbuf[1] = (size >>  8) & 0xff;\n\tlenbuf[2] = (size >> 16) & 0xff;\n\tlenbuf[3] = (size >> 24) & 0xff;\n\n\treturn sendData(socket, 4, lenbuf);\n}\n\n//---------------------------------------------------------------------------------\nstatic int recvInt32LE(int socket, int32_t *data) {\n//---------------------------------------------------------------------------------\n\tunsigned char intbuf[4];\n\tint len = recvData(socket, intbuf, 4, 0);\n\n\tif (len == 4) {\n\t\t*data = intbuf[0] & 0xff + (intbuf[1] <<  8) + (intbuf[2] <<  16) + (intbuf[3] <<  24);\n\t\treturn 0;\n\t}\n\n\treturn -1;\n}\n\nstatic unsigned char in[ZLIB_CHUNK];\nstatic unsigned char out[ZLIB_CHUNK];\n\n//---------------------------------------------------------------------------------\nstatic int sendNROFile(in_addr_t nxaddr, char *name, size_t filesize, FILE *fh) {\n//---------------------------------------------------------------------------------\n\n\tint retval = 0;\n\n\tint ret, flush;\n\tunsigned have;\n\tz_stream strm;\n\n\t/* allocate deflate state */\n\tstrm.zalloc = Z_NULL;\n\tstrm.zfree = Z_NULL;\n\tstrm.opaque = Z_NULL;\n\tret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);\n\tif (ret != Z_OK) return ret;\n\n\tint sock = socket(AF_INET,SOCK_STREAM,0);\n\tif (sock < 0) {\n\t\tsocketError(\"create connection socket\");\n\t\treturn -1;\n\t}\n\n\tstruct sockaddr_in s;\n\tmemset(&s, '\\0', sizeof(struct sockaddr_in));\n\ts.sin_family = AF_INET;\n\ts.sin_port = htons(NETLOADER_SERVER_PORT);\n\ts.sin_addr.s_addr = nxaddr;\n\n\tif (connect(sock,(struct sockaddr *)&s,sizeof(s)) < 0) {\n\t\tstruct in_addr address;\n\t\taddress.s_addr = nxaddr;\n\t\tfprintf(stderr,\"Connection to %s failed\\n\",inet_ntoa(address));\n\t\treturn -1;\n\t}\n\n\tint namelen = strlen(name);\n\n\tif (sendInt32LE(sock,namelen)) {\n\t\tfprintf(stderr,\"Failed sending filename length\\n\");\n\t\tretval = -1;\n\t\tgoto error;\n\t}\n\n\tif (sendData(sock,namelen,name)) {\n\t\tfprintf(stderr,\"Failed sending filename\\n\");\n\t\tretval = -1;\n\t\tgoto error;\n\t}\n\n\tif (sendInt32LE(sock,filesize)) {\n\t\tfprintf(stderr,\"Failed sending file length\\n\");\n\t\tretval = -1;\n\t\tgoto error;\n\t}\n\n\tint response;\n\n\tif (recvInt32LE(sock,&response)!=0) {\n\t\tfprintf(stderr,\"Invalid response\\n\");\n\t\tretval = 1;\n\t\tgoto error;\n\t}\n\n\tif (response!=0) {\n\t\tswitch(response) {\n\t\t\tcase -1:\n\t\t\t\tfprintf(stderr,\"Failed to create file\\n\");\n\t\t\t\tbreak;\n\t\t\tcase -2:\n\t\t\t\tfprintf(stderr,\"Insufficient space\\n\");\n\t\t\t\tbreak;\n\t\t\tcase -3:\n\t\t\t\tfprintf(stderr,\"Insufficient memory\\n\");\n\t\t\t\tbreak;\n\t\t}\n\t\tretval = 1;\n\t\tgoto error;\n\t}\n\n\tprintf(\"Sending %s, %zd bytes\\n\",name, filesize);\n\n\tsize_t totalsent = 0, blocks = 0;\n\n\n\tdo {\n\t\tstrm.avail_in = fread(in, 1, ZLIB_CHUNK, fh);\n\t\tif (ferror(fh)) {\n\t\t\t(void)deflateEnd(&strm);\n\t\t\treturn Z_ERRNO;\n\t\t}\n\t\tflush = feof(fh) ? Z_FINISH : Z_NO_FLUSH;\n\t\tstrm.next_in = in;\n\t\t/* run deflate() on input until output buffer not full, finish\n\t\t   compression if all of source has been read in */\n\t\tdo {\n\t\t\tstrm.avail_out = ZLIB_CHUNK;\n\t\t\tstrm.next_out = out;\n\t\t\tret = deflate(&strm, flush);    /* no bad return value */\n\t\t\tassert(ret != Z_STREAM_ERROR);  /* state not clobbered */\n\t\t\thave = ZLIB_CHUNK - strm.avail_out;\n\n\t\t\tif (have != 0) {\n\t\t\t\tif (sendInt32LE(sock,have)) {\n\t\t\t\t\tfprintf(stderr,\"Failed sending chunk size\\n\");\n\t\t\t\t\tretval = -1;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\n\t\t\t\tif (sendData(sock,have,out)) {\n\t\t\t\t\tfprintf(stderr,\"Failed sending %s\\n\", name);\n\t\t\t\t\tretval = 1;\n\t\t\t\t\t(void)deflateEnd(&strm);\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\n\t\t\t\ttotalsent += have;\n\t\t\t\tblocks++;\n\t\t\t}\n\t\t} while (strm.avail_out == 0);\n\t\tassert(strm.avail_in == 0);     /* all input will be used */\n\t\t/* done when last data in file processed */\n\t} while (flush != Z_FINISH);\n\tassert(ret == Z_STREAM_END);        /* stream will be complete */\n\t(void)deflateEnd(&strm);\n\n\tprintf(\"%zu sent (%.2f%%), %zd blocks\\n\",totalsent, (float)(totalsent * 100.0)/ filesize, blocks);\n\n\tif (recvInt32LE(sock,&response)!=0) {\n\t\tfprintf(stderr,\"Failed sending %s\\n\",name);\n\t\tretval = 1;\n\t\tgoto error;\n\t}\n\n\n\tif (sendData(sock,cmdlen+4,(unsigned char*)cmdbuf)) {\n\n\t\tfprintf(stderr,\"Failed sending command line\\n\");\n\t\tretval = 1;\n\n\t}\n\nerror:\n\tshutdownSocket(sock, SHUT_WR);\n\treturn retval;\n}\n\n//---------------------------------------------------------------------------------\nstatic void showHelp() {\n//---------------------------------------------------------------------------------\n\tputs(\"Usage: nxlink [options] nrofile\\n\");\n\tputs(\"--help,    -h   Display this information\");\n\tputs(\"--address, -a   Hostname or IPv4 address of Switch\");\n\tputs(\"--retries, -r   number of times to ping before giving up\");\n\tputs(\"--path   , -p   set upload path for file\");\n\tputs(\"--args          args to send to nro\");\n\tputs(\"--server , -s   start server after completed upload\");\n\tputs(\"\\n\");\n}\n\n\n//---------------------------------------------------------------------------------\nstatic int addExtraArgs(int len, char *buf, char *extra_args) {\n//---------------------------------------------------------------------------------\n\n\tif (NULL==extra_args) return len;\n\n\n\tint extra_len = strlen(extra_args);\n\n\tchar *dst = &buf[len];\n\tchar *src = extra_args;\n\n\tdo {\n\t\tint c;\n\n\t\tdo {\n\t\t\tc = *src++;\n\t\t\textra_len--;\n\t\t} while (c ==' ' && extra_len >= 0);\n\n\t\tif (c == '\\\"' || c == '\\'') {\n\t\t\tint quote = c;\n\t\t\tdo {\n\t\t\t\tc = *src++;\n\t\t\t\tif (c != quote) *dst++ = c;\n\t\t\t\textra_len--;\n\t\t\t} while (c != quote && extra_len >= 0);\n\n\t\t\t*dst++ = '\\0';\n\n\t\t\tcontinue;\n\t\t}\n\t\tdo {\n\t\t\t*dst++ = c;\n\t\t\textra_len--;\n\t\t\tc = *src++;\n\t\t} while (c != ' ' && extra_len >= 0);\n\n\t\t*dst++ = '\\0';\n\t} while (extra_len >= 0);\n\n\treturn dst - buf;\n}\n\n#define NRO_ARGS\t1000\n\n#ifdef __WIN32__\nstatic void win32_socket_cleanup(void) {\n\tWSACleanup();\n}\n#endif\n\n//---------------------------------------------------------------------------------\nint main(int argc, char **argv) {\n//---------------------------------------------------------------------------------\n\tchar *address = NULL;\n\tchar *basepath = NULL;\n\tchar *finalpath = NULL;\n\tchar *endarg = NULL;\n\tchar *extra_args = NULL;\n\tint retries = 10;\n\tstatic int server = 0;\n\n\tif (argc < 2) {\n\t\tshowHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\twhile (1) {\n\t\tstatic struct option long_options[] = {\n\t\t\t{\"address\", required_argument, 0,\t'a'},\n\t\t\t{\"retries\", required_argument, 0,\t'r'},\n\t\t\t{\"path\",    required_argument, 0,\t'p'},\n\t\t\t{\"args\",    required_argument, 0,  NRO_ARGS},\n\t\t\t{\"help\",    no_argument,       0,\t'h'},\n\t\t\t{\"server\",  no_argument,       &server,  1 },\n\t\t\t{0, 0, 0, 0}\n\t\t};\n\n\t\t/* getopt_long stores the option index here. */\n\t\tint option_index = 0, c;\n\n\t\tc = getopt_long (argc, argv, \"a:r:hp:s\", long_options, &option_index);\n\n\t\t/* Detect the end of the options. */\n\t\tif (c == -1)\n\t\t\tbreak;\n\n\t\tswitch(c) {\n\n\t\tcase 'a':\n\t\t\taddress = optarg;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\terrno = 0;\n\t\t\tretries = strtoul(optarg, &endarg, 0);\n\t\t\tif (endarg == optarg) errno = EINVAL;\n\t\t\tif (errno != 0) {\n\t\t\t\tperror(\"--retries\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\tbasepath = optarg;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tserver = 1;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tshowHelp();\n\t\t\treturn EXIT_FAILURE;\n\t\tcase NRO_ARGS:\n\t\t\textra_args=optarg;\n\t\t\tbreak;\n\t\t}\n\n\t}\n\n\tchar *filename = argv[optind++];\n\tif (filename== NULL) {\n\t\tshowHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tmemset(cmdbuf, '\\0', sizeof(cmdbuf));\n\n\tFILE *fh = fopen(filename,\"rb\");\n\tif (fh == NULL) {\n\t\tfprintf(stderr,\"Failed to open %s\\n\",filename);\n\t\treturn EXIT_FAILURE;\n\t}\n\n#ifdef _WIN32\n\tsetvbuf(stdout, 0, _IONBF, 0);\n#endif\n\n\tfseek(fh,0,SEEK_END);\n\tsize_t filesize = ftell(fh);\n\tfseek(fh,0,SEEK_SET);\n\n\tchar *basename = NULL;\n\tif ((basename=strrchr(filename,'/'))!=NULL) {\n\t\tbasename++;\n\t} else if ((basename=strrchr(filename,'\\\\'))!=NULL) {\n\t\tbasename++;\n\t} else {\n\t\tbasename = filename;\n\t}\n\n\tif (basepath) {\n\t\tsize_t finalpath_len = strlen(basepath);\n\t\tif (basepath[finalpath_len] == '/') {\n\t\t\tfinalpath_len += (strlen(basename) + 1);\n\t\t\tfinalpath = malloc(finalpath_len);\n\t\t\tsprintf(finalpath, \"%s%s\", basepath, basename);\n\t\t} else {\n\t\t\tfinalpath = basepath;\n\t\t}\n\t} else {\n\t\tfinalpath = basename;\n\t}\n\n\tcmdlen = 0;\n\n\tfor (int index = optind; index < argc; index++) {\n\t\tint len=strlen(argv[index]);\n\t\tif ((cmdlen + len + 5) >= (sizeof(cmdbuf) - 2)) break;\n\t\tstrcpy(&cmdbuf[cmdlen+4],argv[index]);\n\t\tcmdlen+= len + 1;\n\t}\n\n\tcmdlen = addExtraArgs(cmdlen, &cmdbuf[4], extra_args);\n\n\tcmdbuf[0] = cmdlen & 0xff;\n\tcmdbuf[1] = (cmdlen>>8) & 0xff;\n\tcmdbuf[2] = (cmdlen>>16) & 0xff;\n\tcmdbuf[3] = (cmdlen>>24) & 0xff;\n\n#ifdef __WIN32__\n\tWSADATA wsa_data;\n\tif (WSAStartup (MAKEWORD(2,2), &wsa_data)) {\n\t\tprintf (\"WSAStartup failed\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tatexit(&win32_socket_cleanup);\n#endif\n\n\tstruct in_addr nxaddr;\n\tnxaddr.s_addr  =  INADDR_NONE;\n\n\tif (address == NULL) {\n\t\tnxaddr = findSwitch(retries);\n\n\t\tif (nxaddr.s_addr == INADDR_NONE) {\n\t\t\tprintf(\"No response from Switch!\\n\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t} else {\n\t\tstruct addrinfo *info;\n\t\tif (getaddrinfo(address, NULL, NULL, &info) == 0) {\n\t\t\tnxaddr = ((struct sockaddr_in*)info->ai_addr)->sin_addr;\n\t\t\tfreeaddrinfo(info);\n\t\t}\n\t}\n\n\tif (nxaddr.s_addr == INADDR_NONE) {\n\t\tfprintf(stderr,\"Invalid address\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tint res = sendNROFile(nxaddr.s_addr,finalpath,filesize,fh);\n\n\tfclose(fh);\n\n\tif (res != 0)\n\t\treturn EXIT_FAILURE;\n\n\tif (!server)\n\t\treturn EXIT_SUCCESS;\n\n\tprintf(\"starting server\\n\");\n\n\tstruct sockaddr_in serv_addr;\n\n\tmemset(&serv_addr, '0', sizeof(serv_addr));\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tserv_addr.sin_port = htons(NETLOADER_CLIENT_PORT);\n\n\tint listenfd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (listenfd < 0) {\n\t\tsocketError(\"socket\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tint rc = bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));\n\tif (rc != 0) {\n\t\tsocketError(\"bind listen socket\");\n\t\tshutdownSocket(listenfd, 0);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\trc = setSocketNonblocking(listenfd);\n\tif (rc == -1) {\n\t\tsocketError(\"listen fcntl\");\n\t\tshutdownSocket(listenfd, 0);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\trc = listen(listenfd, 10);\n\tif (rc != 0) {\n\t\tsocketError(\"listen\");\n\t\tshutdownSocket(listenfd, 0);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tprintf(\"server active ...\\n\");\n\n\tint datafd = -1;\n\n\twhile (listenfd != -1 || datafd != -1) {\n\t\tstruct sockaddr_in sa_remote;\n\n\t\tif (pollSocket(listenfd >= 0 ? listenfd : datafd, POLLIN, -1))\n\t\t\tbreak;\n\n\t\tif (listenfd >= 0) {\n\t\t\tsocklen_t addrlen = sizeof(sa_remote);\n\t\t\tdatafd = accept(listenfd, (struct sockaddr*)&sa_remote, &addrlen);\n\n\t\t\tif (datafd < 0 && socketError(\"accept\") != EWOULDBLOCK)\n\t\t\t\tbreak;\n\n\t\t\tif (datafd >= 0) {\n\t\t\t\tshutdownSocket(listenfd, 0);\n\t\t\t\tlistenfd = -1;\n\t\t\t}\n\t\t} else {\n\t\t\tchar recvbuf[256];\n\t\t\tint len = recv(datafd, recvbuf, sizeof(recvbuf), 0);\n\n\t\t\tif (len == 0 || (len < 0 && socketError(\"recv\") != EWOULDBLOCK)) {\n\t\t\t\tshutdownSocket(datafd, 0);\n\t\t\t\tdatafd = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (len > 0)\n\t\t\t\tfwrite(recvbuf, 1, len, stdout);\n\t\t}\n\t}\n\n\tif (listenfd >= 0)\n\t\tshutdownSocket(listenfd, 0);\n\tif (datafd >= 0)\n\t\tshutdownSocket(datafd, SHUT_RD);\n\n\tprintf(\"exiting ... \\n\");\n\n\treturn EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/romfs.c",
    "content": "#include <string.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <dirent.h>\n\n#include \"types.h\"\n#include \"romfs.h\"\n#include \"filepath.h\"\n\n#include <sys/stat.h>\n#include <sys/types.h>\n\nstruct romfs_fent_ctx;\n\ntypedef struct romfs_dirent_ctx {\n    filepath_t sum_path;\n    filepath_t cur_path;\n    uint32_t entry_offset;\n    struct romfs_dirent_ctx *parent; /* Parent node */\n    struct romfs_dirent_ctx *child; /* Child node */\n    struct romfs_dirent_ctx *sibling; /* Sibling node */\n    struct romfs_fent_ctx *file; /* File node */\n    struct romfs_dirent_ctx *next; /* Next node */\n} romfs_dirent_ctx_t;\n\ntypedef struct romfs_fent_ctx {\n    filepath_t sum_path;\n    filepath_t cur_path;\n    uint32_t entry_offset;\n    uint64_t offset;\n    uint64_t size;\n    romfs_dirent_ctx_t *parent; /* Parent dir */\n    struct romfs_fent_ctx *sibling; /* Sibling file */\n    struct romfs_fent_ctx *next; /* Logical next file */\n} romfs_fent_ctx_t;\n\ntypedef struct {\n    romfs_fent_ctx_t *files;\n    uint64_t num_dirs;\n    uint64_t num_files;\n    uint64_t dir_table_size;\n    uint64_t file_table_size;\n    uint64_t dir_hash_table_size;\n    uint64_t file_hash_table_size;\n    uint64_t file_partition_size;\n} romfs_ctx_t;\n\ntypedef struct {\n    uint64_t header_size;\n    uint64_t dir_hash_table_ofs;\n    uint64_t dir_hash_table_size;\n    uint64_t dir_table_ofs;\n    uint64_t dir_table_size;\n    uint64_t file_hash_table_ofs;\n    uint64_t file_hash_table_size;\n    uint64_t file_table_ofs;\n    uint64_t file_table_size;\n    uint64_t file_partition_ofs;\n} romfs_header_t;\n\ntypedef struct {\n    uint32_t parent;\n    uint32_t sibling;\n    uint32_t child;\n    uint32_t file;\n    uint32_t hash;\n    uint32_t name_size;\n    char name[];\n} romfs_direntry_t;\n\ntypedef struct {\n    uint32_t parent;\n    uint32_t sibling;\n    uint64_t offset;\n    uint64_t size;\n    uint32_t hash;\n    uint32_t name_size;\n    char name[];\n} romfs_fentry_t;\n\n#define ROMFS_ENTRY_EMPTY 0xFFFFFFFF\n#define ROMFS_FILEPARTITION_OFS 0x200\n\nromfs_direntry_t *romfs_get_direntry(romfs_direntry_t *directories, uint32_t offset) {\n    return (romfs_direntry_t *)((char *)directories + offset);\n}\n\nromfs_fentry_t *romfs_get_fentry(romfs_fentry_t *files, uint32_t offset) {\n    return (romfs_fentry_t *)((char *)files + offset);\n}\n\nuint32_t calc_path_hash(uint32_t parent, const unsigned char *path, uint32_t start, size_t path_len) {\n    uint32_t hash = parent ^ 123456789;\n    for (uint32_t i = 0; i < path_len; i++) {\n        hash = (hash >> 5) | (hash << 27);\n        hash ^= path[start + i];\n    }\n\n    return hash;\n}\n\nuint32_t align(uint32_t offset, uint32_t alignment) {\n    uint32_t mask = ~(alignment-1);\n\n    return (offset + (alignment-1)) & mask;\n}\n\nuint64_t align64(uint64_t offset, uint64_t alignment) {\n    uint64_t mask = ~(uint64_t)(alignment-1);\n\n    return (offset + (alignment-1)) & mask;\n}\n\nuint32_t romfs_get_hash_table_count(uint32_t num_entries) {\n    if (num_entries < 3) {\n        return 3;\n    } else if (num_entries < 19) {\n        return num_entries | 1;\n    }\n    uint32_t count = num_entries;\n    while (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 || count % 11 == 0 || count % 13 == 0 || count % 17 == 0) {\n        count++;\n    }\n    return count;\n}\n\nvoid romfs_visit_dir(romfs_dirent_ctx_t *parent, romfs_ctx_t *romfs_ctx) {\n    osdir_t *dir = NULL;\n    osdirent_t *cur_dirent = NULL;\n    romfs_dirent_ctx_t *child_dir_tree = NULL;\n    romfs_fent_ctx_t *child_file_tree = NULL;\n    romfs_dirent_ctx_t *cur_dir = NULL;\n    romfs_fent_ctx_t *cur_file = NULL;\n    filepath_t cur_path;\n    filepath_t cur_sum_path;\n\n    os_stat64_t cur_stats;\n\n    if ((dir = os_opendir(parent->sum_path.os_path)) == NULL) {\n        fprintf(stderr, \"Failed to open directory %s!\\n\", parent->sum_path.char_path);\n        exit(EXIT_FAILURE);\n    }\n\n    while ((cur_dirent = os_readdir(dir))) {\n        filepath_init(&cur_path);\n        filepath_set(&cur_path, \"\");\n        filepath_os_append(&cur_path, cur_dirent->d_name);\n\n        if (strcmp(cur_path.char_path, \"/.\") == 0 || strcmp(cur_path.char_path, \"/..\") == 0) {\n            /* Special case . and .. */\n            continue;\n        }\n\n        filepath_copy(&cur_sum_path, &parent->sum_path);\n        filepath_os_append(&cur_sum_path, cur_dirent->d_name);\n\n        if (os_stat(cur_sum_path.os_path, &cur_stats) == -1) {\n            fprintf(stderr, \"Failed to stat %s\\n\", cur_sum_path.char_path);\n            exit(EXIT_FAILURE);\n        }\n\n        if ((cur_stats.st_mode & S_IFMT) == S_IFDIR) {\n            /* Directory */\n            if ((cur_dir = calloc(1, sizeof(romfs_dirent_ctx_t))) == NULL) {\n                fprintf(stderr, \"Failed to allocate RomFS directory context!\\n\");\n                exit(EXIT_FAILURE);\n            }\n\n            romfs_ctx->num_dirs++;\n\n            cur_dir->parent = parent;\n            filepath_copy(&cur_dir->sum_path, &cur_sum_path);\n            filepath_copy(&cur_dir->cur_path, &cur_path);\n\n            romfs_ctx->dir_table_size += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);\n\n            /* Ordered insertion on sibling */\n            if (child_dir_tree == NULL || strcmp(cur_dir->sum_path.char_path, child_dir_tree->sum_path.char_path) < 0) {\n                cur_dir->sibling = child_dir_tree;\n                child_dir_tree = cur_dir;\n            } else {\n                romfs_dirent_ctx_t *child, *prev;\n                prev = child_dir_tree;\n                child = child_dir_tree->sibling;\n                while (child != NULL) {\n                    if (strcmp(cur_dir->sum_path.char_path, child->sum_path.char_path) < 0) {\n                        break;\n                    }\n                    prev = child;\n                    child = child->sibling;\n                }\n\n                prev->sibling = cur_dir;\n                cur_dir->sibling = child;\n            }\n\n            /* Ordered insertion on next */\n            romfs_dirent_ctx_t *tmp = parent->next, *tmp_prev = parent;\n            while (tmp != NULL) {\n                if (strcmp(cur_dir->sum_path.char_path, tmp->sum_path.char_path) < 0) {\n                    break;\n                }\n                tmp_prev = tmp;\n                tmp = tmp->next;\n            }\n            tmp_prev->next = cur_dir;\n            cur_dir->next = tmp;\n\n            cur_dir = NULL;\n        } else if ((cur_stats.st_mode & S_IFMT) == S_IFREG) {\n            /* File */\n            if ((cur_file = calloc(1, sizeof(romfs_fent_ctx_t))) == NULL) {\n                fprintf(stderr, \"Failed to allocate RomFS File context!\\n\");\n                exit(EXIT_FAILURE);\n            }\n\n            romfs_ctx->num_files++;\n\n            cur_file->parent = parent;\n            filepath_copy(&cur_file->sum_path, &cur_sum_path);\n            filepath_copy(&cur_file->cur_path, &cur_path);\n            cur_file->size = cur_stats.st_size;\n\n            romfs_ctx->file_table_size += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);\n\n            /* Ordered insertion on sibling */\n            if (child_file_tree == NULL || strcmp(cur_file->sum_path.char_path, child_file_tree->sum_path.char_path) < 0) {\n                cur_file->sibling = child_file_tree;\n                child_file_tree = cur_file;\n            } else {\n                romfs_fent_ctx_t *child, *prev;\n                prev = child_file_tree;\n                child = child_file_tree->sibling;\n                while (child != NULL) {\n                    if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {\n                        break;\n                    }\n                    prev = child;\n                    child = child->sibling;\n                }\n\n                prev->sibling = cur_file;\n                cur_file->sibling = child;\n            }\n\n            /* Ordered insertion on next */\n            if (romfs_ctx->files == NULL || strcmp(cur_file->sum_path.char_path, romfs_ctx->files->sum_path.char_path) < 0) {\n                cur_file->next = romfs_ctx->files;\n                romfs_ctx->files = cur_file;\n            } else {\n                romfs_fent_ctx_t *child, *prev;\n                prev = romfs_ctx->files;\n                child = romfs_ctx->files->next;\n                while (child != NULL) {\n                    if (strcmp(cur_file->sum_path.char_path, child->sum_path.char_path) < 0) {\n                        break;\n                    }\n                    prev = child;\n                    child = child->next;\n                }\n\n                prev->next = cur_file;\n                cur_file->next = child;\n            }\n\n            cur_file = NULL;\n        } else {\n            fprintf(stderr, \"Invalid FS object type for %s!\\n\", cur_path.char_path);\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    os_closedir(dir);\n    parent->child = child_dir_tree;\n    parent->file = child_file_tree;\n\n    cur_dir = child_dir_tree;\n    while (cur_dir != NULL) {\n        romfs_visit_dir(cur_dir, romfs_ctx);\n        cur_dir = cur_dir->sibling;\n    }\n}\n\nsize_t build_romfs_into_file(filepath_t *in_dirpath, FILE *f_out, off_t base_offset) {\n    romfs_dirent_ctx_t *root_ctx = calloc(1, sizeof(romfs_dirent_ctx_t));\n    if (root_ctx == NULL) {\n        fprintf(stderr, \"Failed to allocate root context!\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    root_ctx->parent = root_ctx;\n\n    romfs_ctx_t romfs_ctx;\n    memset(&romfs_ctx, 0, sizeof(romfs_ctx));\n\n    filepath_copy(&root_ctx->sum_path, in_dirpath);\n    filepath_init(&root_ctx->cur_path);\n    filepath_set(&root_ctx->cur_path, \"\");\n    romfs_ctx.dir_table_size = 0x18; /* Root directory. */\n    romfs_ctx.num_dirs = 1;\n\n    /* Visit all directories. */\n    printf(\"Visiting directories...\\n\");\n    romfs_visit_dir(root_ctx, &romfs_ctx);\n    uint32_t dir_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_dirs);\n    uint32_t file_hash_table_entry_count = romfs_get_hash_table_count(romfs_ctx.num_files);\n    romfs_ctx.dir_hash_table_size = 4 * dir_hash_table_entry_count;\n    romfs_ctx.file_hash_table_size = 4 * file_hash_table_entry_count;\n\n    romfs_header_t header;\n    memset(&header, 0, sizeof(header));\n    romfs_fent_ctx_t *cur_file = NULL;\n    romfs_dirent_ctx_t *cur_dir = NULL;\n    uint32_t entry_offset = 0;\n\n\n    uint32_t *dir_hash_table = malloc(romfs_ctx.dir_hash_table_size);\n    if (dir_hash_table == NULL) {\n        fprintf(stderr, \"Failed to allocate directory hash table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    for (uint32_t i = 0; i < dir_hash_table_entry_count; i++) {\n        dir_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);\n    }\n\n    uint32_t *file_hash_table = malloc(romfs_ctx.file_hash_table_size);\n    if (file_hash_table == NULL) {\n        fprintf(stderr, \"Failed to allocate file hash table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    for (uint32_t i = 0; i < file_hash_table_entry_count; i++) {\n        file_hash_table[i] = le_word(ROMFS_ENTRY_EMPTY);\n    }\n\n    romfs_direntry_t *dir_table = calloc(1, romfs_ctx.dir_table_size);\n    if (dir_table == NULL) {\n        fprintf(stderr, \"Failed to allocate directory table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    romfs_fentry_t *file_table = calloc(1, romfs_ctx.file_table_size);\n    if (file_table == NULL) {\n        fprintf(stderr, \"Failed to allocate file table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    printf(\"Calculating metadata...\\n\");\n    /* Determine file offsets. */\n    cur_file = romfs_ctx.files;\n    entry_offset = 0;\n    while (cur_file != NULL) {\n        romfs_ctx.file_partition_size = align64(romfs_ctx.file_partition_size, 0x10);\n        cur_file->offset = romfs_ctx.file_partition_size;\n        romfs_ctx.file_partition_size += cur_file->size;\n        cur_file->entry_offset = entry_offset;\n        entry_offset += 0x20 + align(strlen(cur_file->cur_path.char_path)-1, 4);\n        cur_file = cur_file->next;\n    }\n\n    /* Determine dir offsets. */\n    cur_dir = root_ctx;\n    entry_offset = 0;\n    while (cur_dir != NULL) {\n        cur_dir->entry_offset = entry_offset;\n        if (cur_dir == root_ctx) {\n            entry_offset += 0x18;\n        } else {\n            entry_offset += 0x18 + align(strlen(cur_dir->cur_path.char_path)-1, 4);\n        }\n        cur_dir = cur_dir->next;\n    }\n\n    /* Populate file tables. */\n    cur_file = romfs_ctx.files;\n    while (cur_file != NULL) {\n        romfs_fentry_t *cur_entry = romfs_get_fentry(file_table, cur_file->entry_offset);\n        cur_entry->parent = le_word(cur_file->parent->entry_offset);\n        cur_entry->sibling = le_word(cur_file->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_file->sibling->entry_offset);\n        cur_entry->offset = le_dword(cur_file->offset);\n        cur_entry->size = le_dword(cur_file->size);\n\n        uint32_t name_size = strlen(cur_file->cur_path.char_path)-1;\n        uint32_t hash = calc_path_hash(cur_file->parent->entry_offset, (unsigned char *)cur_file->cur_path.char_path, 1, name_size);\n        cur_entry->hash = file_hash_table[hash % file_hash_table_entry_count];\n        file_hash_table[hash % file_hash_table_entry_count] = le_word(cur_file->entry_offset);\n\n        cur_entry->name_size = name_size;\n        memcpy(cur_entry->name, cur_file->cur_path.char_path + 1, name_size);\n\n        cur_file = cur_file->next;\n    }\n\n    /* Populate dir tables. */\n    cur_dir = root_ctx;\n    while (cur_dir != NULL) {\n        romfs_direntry_t *cur_entry = romfs_get_direntry(dir_table, cur_dir->entry_offset);\n        cur_entry->parent = le_word(cur_dir->parent->entry_offset);\n        cur_entry->sibling = le_word(cur_dir->sibling == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->sibling->entry_offset);\n        cur_entry->child = le_word(cur_dir->child == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->child->entry_offset);\n        cur_entry->file = le_word(cur_dir->file == NULL ? ROMFS_ENTRY_EMPTY : cur_dir->file->entry_offset);\n\n        uint32_t name_size = (cur_dir == root_ctx) ? 0 : strlen(cur_dir->cur_path.char_path)-1;\n        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);\n        cur_entry->hash = dir_hash_table[hash % dir_hash_table_entry_count];\n        dir_hash_table[hash % dir_hash_table_entry_count] = le_word(cur_dir->entry_offset);\n\n        cur_entry->name_size = name_size;\n        memcpy(cur_entry->name, cur_dir->cur_path.char_path + 1, name_size);\n\n        cur_dir = cur_dir->next;\n    }\n\n    header.header_size = le_dword(sizeof(header));\n    header.file_hash_table_size = le_dword(romfs_ctx.file_hash_table_size);\n    header.file_table_size = le_dword(romfs_ctx.file_table_size);\n    header.dir_hash_table_size = le_dword(romfs_ctx.dir_hash_table_size);\n    header.dir_table_size = le_dword(romfs_ctx.dir_table_size);\n    header.file_partition_ofs = le_dword(ROMFS_FILEPARTITION_OFS);\n\n    /* Abuse of endianness follows. */\n    uint64_t dir_hash_table_ofs = align64(romfs_ctx.file_partition_size + ROMFS_FILEPARTITION_OFS, 4);\n    header.dir_hash_table_ofs = dir_hash_table_ofs;\n    header.dir_table_ofs = header.dir_hash_table_ofs + romfs_ctx.dir_hash_table_size;\n    header.file_hash_table_ofs = header.dir_table_ofs + romfs_ctx.dir_table_size;\n    header.file_table_ofs = header.file_hash_table_ofs + romfs_ctx.file_hash_table_size;\n    header.dir_hash_table_ofs = le_dword(header.dir_hash_table_ofs);\n    header.dir_table_ofs = le_dword(header.dir_table_ofs);\n    header.file_hash_table_ofs = le_dword(header.file_hash_table_ofs);\n    header.file_table_ofs = le_dword(header.file_table_ofs);\n\n    fseeko64(f_out, base_offset, SEEK_SET);\n    fwrite(&header, 1, sizeof(header), f_out);\n\n    /* Write files. */\n    unsigned char *buffer = malloc(0x400000);\n    if (buffer == NULL) {\n        fprintf(stderr, \"Failed to allocate work buffer!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    cur_file = romfs_ctx.files;\n    while (cur_file != NULL) {\n        FILE *f_in = os_fopen(cur_file->sum_path.os_path, OS_MODE_READ);\n        if (f_in == NULL) {\n            fprintf(stderr, \"Failed to open %s!\\n\", cur_file->sum_path.char_path);\n            exit(EXIT_FAILURE);\n        }\n\n        printf(\"Writing %s to RomFS image...\\n\", cur_file->sum_path.char_path);\n        fseeko64(f_out, base_offset + cur_file->offset + ROMFS_FILEPARTITION_OFS, SEEK_SET);\n        uint64_t offset = 0;\n        uint64_t read_size = 0x400000;\n        while (offset < cur_file->size) {\n            if (cur_file->size - offset < read_size) {\n                read_size = cur_file->size - offset;\n            }\n\n            if (fread(buffer, 1, read_size, f_in) != read_size) {\n                fprintf(stderr, \"Failed to read from %s!\\n\", cur_file->sum_path.char_path);\n                exit(EXIT_FAILURE);\n            }\n\n            if (fwrite(buffer, 1, read_size, f_out) != read_size) {\n                fprintf(stderr, \"Failed to write to output!\\n\");\n                exit(EXIT_FAILURE);\n            }\n\n            offset += read_size;\n        }\n\n        os_fclose(f_in);\n\n        cur_file = cur_file->next;\n    }\n    free(buffer);\n\n    /* Free all files. */\n    cur_file = romfs_ctx.files;\n    while (cur_file != NULL) {\n        romfs_fent_ctx_t *temp = cur_file;\n        cur_file = cur_file->next;\n        free(temp);\n    }\n    romfs_ctx.files = NULL;\n\n    /* Free all directories. */\n    cur_dir = root_ctx;\n    while (cur_dir != NULL) {\n        romfs_dirent_ctx_t *temp = cur_dir;\n        cur_dir = cur_dir->next;\n        free(temp);\n    }\n    root_ctx = NULL;\n\n    fseeko64(f_out, base_offset + dir_hash_table_ofs, SEEK_SET);\n    if (fwrite(dir_hash_table, 1, romfs_ctx.dir_hash_table_size, f_out) != romfs_ctx.dir_hash_table_size) {\n        fprintf(stderr, \"Failed to write dir hash table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    free(dir_hash_table);\n\n    if (fwrite(dir_table, 1, romfs_ctx.dir_table_size, f_out) != romfs_ctx.dir_table_size) {\n        fprintf(stderr, \"Failed to write dir table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    free(dir_table);\n\n    if (fwrite(file_hash_table, 1, romfs_ctx.file_hash_table_size, f_out) != romfs_ctx.file_hash_table_size) {\n        fprintf(stderr, \"Failed to write file hash table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    free(file_hash_table);\n\n    if (fwrite(file_table, 1, romfs_ctx.file_table_size, f_out) != romfs_ctx.file_table_size) {\n        fprintf(stderr, \"Failed to write file table!\\n\");\n        exit(EXIT_FAILURE);\n    }\n    free(file_table);\n\n    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;\n}\n\nsize_t build_romfs(filepath_t *in_dirpath, filepath_t *out_romfspath) {\n    FILE *f_out = NULL;\n\n    if ((f_out = os_fopen(out_romfspath->os_path, OS_MODE_WRITE)) == NULL) {\n        fprintf(stderr, \"Failed to open %s!\\n\", out_romfspath->char_path);\n        exit(EXIT_FAILURE);\n    }\n\n    size_t sz = build_romfs_into_file(in_dirpath, f_out, 0);\n\n    fclose(f_out);\n    return sz;\n}\n\nsize_t build_romfs_by_paths(char *dir, char *out_fn) {\n    filepath_t dirpath;\n    filepath_t outpath;\n\n    filepath_init(&dirpath);\n    filepath_init(&outpath);\n\n    filepath_set(&dirpath, dir);\n    filepath_set(&outpath, out_fn);\n\n    return build_romfs(&dirpath, &outpath);\n}\n\nsize_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t offset) {\n    filepath_t dirpath;\n\n    filepath_init(&dirpath);\n\n    filepath_set(&dirpath, dir);\n\n    return build_romfs_into_file(&dirpath, f_out, offset);\n}\n"
  },
  {
    "path": "src/romfs.h",
    "content": "#pragma once\n\n#include \"filepath.h\"\n\nsize_t build_romfs_by_paths(char *dir, char *out_fn);\n\nsize_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t base_offset);"
  },
  {
    "path": "src/sha256.c",
    "content": "/*********************************************************************\n* Filename:   sha256.c\n* Author:     Brad Conte (brad AT bradconte.com)\n* Copyright:\n* Disclaimer: This code is presented \"as is\" without any guarantees.\n* Details:    Implementation of the SHA-256 hashing algorithm.\n              SHA-256 is one of the three algorithms in the SHA2\n              specification. The others, SHA-384 and SHA-512, are not\n              offered in this implementation.\n              Algorithm specification can be found here:\n               * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf\n              This implementation uses little endian byte order.\n*********************************************************************/\n\n/*************************** HEADER FILES ***************************/\n#include <stdlib.h>\n#include <memory.h>\n#include \"sha256.h\"\n\n/****************************** MACROS ******************************/\n#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))\n#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))\n\n#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))\n#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))\n#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))\n#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))\n#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))\n#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))\n\n/**************************** VARIABLES *****************************/\nstatic const WORD k[64] = {\n\t0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,\n\t0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,\n\t0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,\n\t0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,\n\t0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,\n\t0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,\n\t0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,\n\t0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2\n};\n\n/*********************** FUNCTION DEFINITIONS ***********************/\nvoid sha256_transform(SHA256_CTX *ctx, const BYTE data[])\n{\n\tWORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];\n\n\tfor (i = 0, j = 0; i < 16; ++i, j += 4)\n\t\tm[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);\n\tfor ( ; i < 64; ++i)\n\t\tm[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];\n\n\ta = ctx->state[0];\n\tb = ctx->state[1];\n\tc = ctx->state[2];\n\td = ctx->state[3];\n\te = ctx->state[4];\n\tf = ctx->state[5];\n\tg = ctx->state[6];\n\th = ctx->state[7];\n\n\tfor (i = 0; i < 64; ++i) {\n\t\tt1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];\n\t\tt2 = EP0(a) + MAJ(a,b,c);\n\t\th = g;\n\t\tg = f;\n\t\tf = e;\n\t\te = d + t1;\n\t\td = c;\n\t\tc = b;\n\t\tb = a;\n\t\ta = t1 + t2;\n\t}\n\n\tctx->state[0] += a;\n\tctx->state[1] += b;\n\tctx->state[2] += c;\n\tctx->state[3] += d;\n\tctx->state[4] += e;\n\tctx->state[5] += f;\n\tctx->state[6] += g;\n\tctx->state[7] += h;\n}\n\nvoid sha256_init(SHA256_CTX *ctx)\n{\n\tctx->datalen = 0;\n\tctx->bitlen = 0;\n\tctx->state[0] = 0x6a09e667;\n\tctx->state[1] = 0xbb67ae85;\n\tctx->state[2] = 0x3c6ef372;\n\tctx->state[3] = 0xa54ff53a;\n\tctx->state[4] = 0x510e527f;\n\tctx->state[5] = 0x9b05688c;\n\tctx->state[6] = 0x1f83d9ab;\n\tctx->state[7] = 0x5be0cd19;\n}\n\nvoid sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len)\n{\n\tWORD i;\n\n\tfor (i = 0; i < len; ++i) {\n\t\tctx->data[ctx->datalen] = data[i];\n\t\tctx->datalen++;\n\t\tif (ctx->datalen == 64) {\n\t\t\tsha256_transform(ctx, ctx->data);\n\t\t\tctx->bitlen += 512;\n\t\t\tctx->datalen = 0;\n\t\t}\n\t}\n}\n\nvoid sha256_final(SHA256_CTX *ctx, BYTE hash[])\n{\n\tWORD i;\n\n\ti = ctx->datalen;\n\n\t// Pad whatever data is left in the buffer.\n\tif (ctx->datalen < 56) {\n\t\tctx->data[i++] = 0x80;\n\t\twhile (i < 56)\n\t\t\tctx->data[i++] = 0x00;\n\t}\n\telse {\n\t\tctx->data[i++] = 0x80;\n\t\twhile (i < 64)\n\t\t\tctx->data[i++] = 0x00;\n\t\tsha256_transform(ctx, ctx->data);\n\t\tmemset(ctx->data, 0, 56);\n\t}\n\n\t// Append to the padding the total message's length in bits and transform.\n\tctx->bitlen += ctx->datalen * 8;\n\tctx->data[63] = ctx->bitlen;\n\tctx->data[62] = ctx->bitlen >> 8;\n\tctx->data[61] = ctx->bitlen >> 16;\n\tctx->data[60] = ctx->bitlen >> 24;\n\tctx->data[59] = ctx->bitlen >> 32;\n\tctx->data[58] = ctx->bitlen >> 40;\n\tctx->data[57] = ctx->bitlen >> 48;\n\tctx->data[56] = ctx->bitlen >> 56;\n\tsha256_transform(ctx, ctx->data);\n\n\t// Since this implementation uses little endian byte ordering and SHA uses big endian,\n\t// reverse all the bytes when copying the final state to the output hash.\n\tfor (i = 0; i < 4; ++i) {\n\t\thash[i]      = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 4]  = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 8]  = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;\n\t\thash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;\n\t}\n}\n"
  },
  {
    "path": "src/sha256.h",
    "content": "/*********************************************************************\n* Filename:   sha256.h\n* Author:     Brad Conte (brad AT bradconte.com)\n* Copyright:\n* Disclaimer: This code is presented \"as is\" without any guarantees.\n* Details:    Defines the API for the corresponding SHA1 implementation.\n*********************************************************************/\n\n#ifndef SHA256_H\n#define SHA256_H\n\n/*************************** HEADER FILES ***************************/\n#include <stddef.h>\n\n/****************************** MACROS ******************************/\n#define SHA256_BLOCK_SIZE 32            // SHA256 outputs a 32 byte digest\n\n/**************************** DATA TYPES ****************************/\ntypedef unsigned char BYTE;             // 8-bit byte\ntypedef unsigned int  WORD;             // 32-bit word, change to \"long\" for 16-bit machines\n\ntypedef struct {\n\tBYTE data[64];\n\tWORD datalen;\n\tunsigned long long bitlen;\n\tWORD state[8];\n} SHA256_CTX;\n\n/*********************** FUNCTION DECLARATIONS **********************/\nvoid sha256_init(SHA256_CTX *ctx);\nvoid sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);\nvoid sha256_final(SHA256_CTX *ctx, BYTE hash[]);\n\n#endif   // SHA256_H\n"
  },
  {
    "path": "src/types.h",
    "content": "#pragma once\n#include <stdint.h>\n\ntypedef uint64_t dword_t;\ntypedef uint32_t word_t;\ntypedef uint16_t hword_t;\ntypedef uint8_t byte_t;\ntypedef int64_t dlong_t;\ntypedef int32_t long_t;\ntypedef int16_t short_t;\ntypedef int8_t char_t;\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define BIT(n) (1U << (n))\n\nstatic inline uint16_t __local_bswap16(uint16_t x) {\n\treturn ((x << 8) & 0xff00) | ((x >> 8) & 0x00ff);\n}\n\n\nstatic inline uint32_t __local_bswap32(uint32_t x) {\n\treturn\t((x << 24) & 0xff000000 ) |\n\t\t\t((x <<  8) & 0x00ff0000 ) |\n\t\t\t((x >>  8) & 0x0000ff00 ) |\n\t\t\t((x >> 24) & 0x000000ff );\n}\n\nstatic inline uint64_t __local_bswap64(uint64_t x)\n{\n\treturn (uint64_t)__local_bswap32(x>>32) |\n\t      ((uint64_t)__local_bswap32(x&0xFFFFFFFF) << 32);\n}\n\n#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n#define be_dword(a) __local_bswap64(a)\n#define be_word(a)  __local_bswap32(a)\n#define be_hword(a) __local_bswap16(a)\n#define le_dword(a) (a)\n#define le_word(a)  (a)\n#define le_hword(a) (a)\n#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n#define be_dword(a) (a)\n#define be_word(a)  (a)\n#define be_hword(a) (a)\n#define le_dword(a) __local_bswap64(a)\n#define le_word(a)  __local_bswap32(a)\n#define le_hword(a) __local_bswap16(a)\n#else\n#error \"What's the endianness of the platform you're targeting?\"\n#endif\n\n"
  }
]