Full Code of switchbrew/switch-tools for AI

master 22756068dd0e cached
28 files
268.1 KB
77.9k tokens
278 symbols
1 requests
Download .txt
Showing preview only (279K chars total). Download the full file or copy to clipboard to get everything.
Repository: switchbrew/switch-tools
Branch: master
Commit: 22756068dd0e
Files: 28
Total size: 268.1 KB

Directory structure:
gitextract_cljm8jeo/

├── .gitignore
├── AUTHORS
├── COPYING
├── ChangeLog
├── Makefile.am
├── NEWS
├── README
├── autogen.sh
├── configure.ac
└── src/
    ├── blz.c
    ├── blz.h
    ├── cJSON.c
    ├── cJSON.h
    ├── elf2kip.c
    ├── elf2nro.c
    ├── elf2nso.c
    ├── elf64.h
    ├── elf_common.h
    ├── filepath.c
    ├── filepath.h
    ├── nacptool.c
    ├── npdmtool.c
    ├── nxlink.c
    ├── romfs.c
    ├── romfs.h
    ├── sha256.c
    ├── sha256.h
    └── types.h

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
build*
INSTALL
Makefile.in
aclocal.m4
autom4te.cache
config.guess
config.sub
configure
depcomp
install-sh
missing
compile
.deps
Makefile
config.status
config.log
.dirstamp
elf2nro
elf2nso
elf2kip
nacptool
npdmtool
nxlink
*.o
*.elf
*.kip
*.nro
*.nso
*.npdm
*.json


================================================
FILE: AUTHORS
================================================


================================================
FILE: COPYING
================================================
Copyright 2017 libnx Authors

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

================================================
FILE: ChangeLog
================================================


================================================
FILE: Makefile.am
================================================
# Makefile.am -- Process this file with automake to produce Makefile.in
bin_PROGRAMS = elf2nso elf2nro elf2kip build_pfs0 build_romfs nacptool npdmtool nxlink

build_pfs0_SOURCES	=	src/build_pfs0.c src/types.h

build_romfs_SOURCES = src/build_romfs.c src/romfs.c src/romfs.h src/filepath.c src/filepath.h src/types.h

elf2nro_SOURCES	=	src/elf2nro.c src/elf64.h src/romfs.c src/filepath.c src/filepath.h src/romfs.h src/elf_common.h

elf2nso_SOURCES	=	src/elf2nso.c src/sha256.c src/sha256.h src/elf64.h src/elf_common.h

elf2kip_SOURCES	=	src/elf2kip.c src/cJSON.c src/cJSON.h src/blz.c src/blz.h src/elf64.h src/elf_common.h

nacptool_SOURCES	=	src/nacptool.c

npdmtool_SOURCES	=	src/npdmtool.c src/cJSON.c src/cJSON.h

nxlink_SOURCES = src/nxlink.c

nxlink_CPPFLAGS = @ZLIB_CFLAGS@
nxlink_LDADD = @ZLIB_LIBS@ @NET_LIBS@

elf2nso_CPPFLAGS = @LZ4_CFLAGS@
elf2nso_LDADD = @LZ4_LIBS@

elf2nro_CPPFLAGS = @LZ4_CFLAGS@
elf2nro_LDADD = @LZ4_LIBS@


EXTRA_DIST = autogen.sh


================================================
FILE: NEWS
================================================


================================================
FILE: README
================================================


================================================
FILE: autogen.sh
================================================
aclocal
autoconf
automake --add-missing -c


================================================
FILE: configure.ac
================================================
#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ(2.61)
AC_INIT([switch-tools],[1.13.1],[https://github.com/switchbrew/switch-tools/issues])
AC_CONFIG_SRCDIR([src/build_pfs0.c])

AM_INIT_AUTOMAKE([subdir-objects])

AC_CANONICAL_BUILD
AC_CANONICAL_HOST

AC_PROG_CC

AC_SYS_LARGEFILE

PKG_CHECK_MODULES([LZ4],
		[liblz4 >= 1.7.1 liblz4 < 100],
		[have_lz4="yes"],
		[PKG_CHECK_MODULES([LZ4],
			[liblz4 >= 131],
			[have_lz4="yes"])
])

PKG_CHECK_MODULES([ZLIB], zlib, [
  AC_DEFINE([HAVE_LIBZ], [1], [Define if using zlib.])
])

NET_LIBS=""

case "$host" in
   *-*-mingw*)
      NET_LIBS="-lws2_32"
      CFLAGS="$CFLAGS -D__USE_MINGW_ANSI_STDIO -D_WIN32_WINNT=0x0600"
      ;;
esac

CFLAGS="$CFLAGS -std=gnu99"

AC_SUBST(ZLIB_CFLAGS)
AC_SUBST(ZLIB_LIBS)
AC_SUBST(NET_LIBS)
AC_SUBST(LZ4_CFLAGS)
AC_SUBST(LZ4_LIBS)
AC_CONFIG_FILES([Makefile])
AC_OUTPUT


================================================
FILE: src/blz.c
================================================
/*----------------------------------------------------------------------------*/
/*--  blz.c - Bottom LZ coding for Nintendo GBA/DS                          --*/
/*--  Copyright (C) 2011 CUE                                                --*/
/*--                                                                        --*/
/*--  This program is free software: you can redistribute it and/or modify  --*/
/*--  it under the terms of the GNU General Public License as published by  --*/
/*--  the Free Software Foundation, either version 3 of the License, or     --*/
/*--  (at your option) any later version.                                   --*/
/*--                                                                        --*/
/*--  This program is distributed in the hope that it will be useful,       --*/
/*--  but WITHOUT ANY WARRANTY; without even the implied warranty of        --*/
/*--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the          --*/
/*--  GNU General Public License for more details.                          --*/
/*--                                                                        --*/
/*--  You should have received a copy of the GNU General Public License     --*/
/*--  along with this program. If not, see <http://www.gnu.org/licenses/>.  --*/
/*----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
#include "blz.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*----------------------------------------------------------------------------*/
#define CMD_DECODE    0x00       // decode
#define CMD_ENCODE    0x01       // encode

#define BLZ_SHIFT     1          // bits to shift
#define BLZ_MASK      0x80       // bits to check:
                                 // ((((1 << BLZ_SHIFT) - 1) << (8 - BLZ_SHIFT)

#define BLZ_THRESHOLD 2          // max number of bytes to not encode
#define BLZ_N         0x1002     // max offset ((1 << 12) + 2)
#define BLZ_F         0x12       // max coded ((1 << 4) + BLZ_THRESHOLD)

#define RAW_MINIM     0x00000000 // empty file, 0 bytes
#define RAW_MAXIM     0x00FFFFFF // 3-bytes length, 16MB - 1

#define BLZ_MINIM     0x00000004 // header only (empty RAW file)
#define BLZ_MAXIM     0x01400000 // 0x0120000A, padded to 20MB:
                                 // * length, RAW_MAXIM
                                 // * flags, (RAW_MAXIM + 7) / 8
                                 // * header, 11
                                 // 0x00FFFFFF + 0x00200000 + 12 + padding

/*----------------------------------------------------------------------------*/
#define BREAK(text)   { printf(text); return; }
#define EXIT(text)    { printf(text); exit(-1); }

/*----------------------------------------------------------------------------*/
u8 *Memory(int length, int size);

u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
void  BLZ_Invert(u8 *buffer, int length);

/*----------------------------------------------------------------------------*/
u8 *Memory(int length, int size) {
  u8 *fb;

  fb = (u8 *) calloc(length * size, size);
  if (fb == NULL) EXIT("\nMemory error\n");

  return(fb);
}

/*----------------------------------------------------------------------------*/
void BLZ_Decode(char *filename) {
  // u8 *pak_buffer, *raw_buffer, *pak, *raw, *pak_end, *raw_end;
  // u32   pak_len, raw_len, len, pos, inc_len, hdr_len, enc_len, dec_len;
  // u8  flags, mask;

  // printf("- decoding '%s'", filename);

  // // pak_buffer = Load(filename, &pak_len, BLZ_MINIM, BLZ_MAXIM);

  // inc_len = *(u32 *)(pak_buffer + pak_len - 4);
  // if (!inc_len) {
  //   enc_len = 0;
  //   dec_len = pak_len - 4;
  //   pak_len = 0;
  //   raw_len = dec_len;
  // } else {
  //   if (pak_len < 8) EXIT("File has a bad header\n");
  //   hdr_len = pak_buffer[pak_len - 5];
  //   if ((hdr_len < 0x08) || (hdr_len > 0x0B)) EXIT("Bad header length\n");
  //   if (pak_len <= hdr_len) EXIT("Bad length\n");
  //   enc_len = *(u32 *)(pak_buffer + pak_len - 8) & 0x00FFFFFF;
  //   dec_len = pak_len - enc_len;
  //   pak_len = enc_len - hdr_len;
  //   raw_len = dec_len + enc_len + inc_len;
  //   if (raw_len > RAW_MAXIM) EXIT("Bad decoded length\n");
  // }

  // raw_buffer = (u8 *) Memory(raw_len, sizeof(char));

  // pak = pak_buffer;
  // raw = raw_buffer;
  // pak_end = pak_buffer + dec_len + pak_len;
  // raw_end = raw_buffer + raw_len;

  // for (len = 0; len < dec_len; len++) *(raw++) = *(pak++);

  // BLZ_Invert(pak_buffer + dec_len, pak_len);

  // mask = 0;

  // while (raw < raw_end) {
  //   if (!(mask >>= BLZ_SHIFT)) {
  //     if (pak == pak_end) break;
  //     flags = *pak++;
  //     mask = BLZ_MASK;
  //   }

  //   if (!(flags & mask)) {
  //     if (pak == pak_end) break;
  //     *raw++ = *pak++;
  //   } else {
  //     if (pak + 1 >= pak_end) break;
  //     pos = *pak++ << 8;
  //     pos |= *pak++;
  //     len = (pos >> 12) + BLZ_THRESHOLD + 1;
  //     if (raw + len > raw_end) {
  //       printf(", WARNING: wrong decoded length!");
  //       len = raw_end - raw;
  //     }
  //     pos = (pos & 0xFFF) + 3;
  //     while (len--) *(raw++) = *(raw - pos);
  //   }
  // }

  // BLZ_Invert(raw_buffer + dec_len, raw_len - dec_len);

  // raw_len = raw - raw_buffer;

  // if (raw != raw_end) printf(", WARNING: unexpected end of encoded file!");

  // // Save(filename, raw_buffer, raw_len);

  // free(raw_buffer);
  // free(pak_buffer);

  // printf("\n");
}

u8 *Load(char *filename, u32 *length, int min, int max) {
  FILE *fp;
  int   fs;
  u8 *fb;

  if ((fp = fopen(filename, "rb")) == NULL) EXIT("\nFile open error\n");
  fseek(fp, 0, SEEK_END);
  fs = ftell(fp);
  fseek(fp, 0, SEEK_SET);
  if ((fs < min) || (fs > max)) EXIT("\nFile size error\n");
  fb = Memory(fs + 3, sizeof(char));
  if (fread(fb, 1, fs, fp) != fs) EXIT("\nFile read error\n");
  if (fclose(fp) == EOF) EXIT("\nFile close error\n");

  *length = fs;

  return(fb);
}

/*----------------------------------------------------------------------------*/
u8* BLZ_Encode(char *filename, u32* pak_len, int mode) {
  u8 *raw_buffer, *pak_buffer, *new_buffer;
  u32   raw_len, new_len;

  raw_buffer = Load(filename, &raw_len, RAW_MINIM, RAW_MAXIM);

  pak_buffer = NULL;
  *pak_len = BLZ_MAXIM + 1;

  new_buffer = BLZ_Code(raw_buffer, raw_len, &new_len, mode);
  if (new_len < *pak_len) {
    if (pak_buffer != NULL) free(pak_buffer);
    pak_buffer = new_buffer;
    *pak_len = new_len;
  }

  return pak_buffer;
}

/*----------------------------------------------------------------------------*/
u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best) {
  u8 *pak_buffer, *pak, *raw, *raw_end, *flg = NULL, *tmp;
  u32   pak_len, inc_len, hdr_len, enc_len, len, pos, max;
  u32   len_best, pos_best = 0, len_next, pos_next, len_post, pos_post;
  u32   pak_tmp, raw_tmp;
  u8  mask;

#define SEARCH(l,p) { \
  l = BLZ_THRESHOLD;                                          \
                                                              \
  max = raw - raw_buffer >= BLZ_N ? BLZ_N : raw - raw_buffer; \
  for (pos = 3; pos <= max; pos++) {                          \
    for (len = 0; len < BLZ_F; len++) {                       \
      if (raw + len == raw_end) break;                        \
      if (len >= pos) break;                                  \
      if (*(raw + len) != *(raw + len - pos)) break;          \
    }                                                         \
                                                              \
    if (len > l) {                                            \
      p = pos;                                                \
      if ((l = len) == BLZ_F) break;                          \
    }                                                         \
  }                                                           \
}

  pak_tmp = 0;
  raw_tmp = raw_len;

  pak_len = raw_len + ((raw_len + 7) / 8) + 15;
  pak_buffer = (u8 *) Memory(pak_len, sizeof(char));

  BLZ_Invert(raw_buffer, raw_len);

  pak = pak_buffer;
  raw = raw_buffer;
  raw_end = raw_buffer + raw_len;

  mask = 0;

  while (raw < raw_end) {
    if (!(mask >>= BLZ_SHIFT)) {
      *(flg = pak++) = 0;
      mask = BLZ_MASK;
    }

    SEARCH(len_best, pos_best);

    // LZ-CUE optimization start
    if (best) {
      if (len_best > BLZ_THRESHOLD) {
        if (raw + len_best < raw_end) {
          raw += len_best;
          SEARCH(len_next, pos_next);
          raw -= len_best - 1;
          SEARCH(len_post, pos_post);
          raw--;

          if (len_next <= BLZ_THRESHOLD) len_next = 1;
          if (len_post <= BLZ_THRESHOLD) len_post = 1;

          if (len_best + len_next <= 1 + len_post) len_best = 1;
        }
      }
    }
    // LZ-CUE optimization end

    *flg <<= 1;
    if (len_best > BLZ_THRESHOLD) {
      raw += len_best;
      *flg |= 1;
      *pak++ = ((len_best - (BLZ_THRESHOLD+1)) << 4) | ((pos_best - 3) >> 8);
      *pak++ = (pos_best - 3) & 0xFF;
    } else {
      *pak++ = *raw++;
    }

    if (pak - pak_buffer + raw_len - (raw - raw_buffer) < pak_tmp + raw_tmp) {
      pak_tmp = pak - pak_buffer;
      raw_tmp = raw_len - (raw - raw_buffer);
    }
  }

  while (mask && (mask != 1)) {
    mask >>= BLZ_SHIFT;
    *flg <<= 1;
  }

  pak_len = pak - pak_buffer;

  BLZ_Invert(raw_buffer, raw_len);
  BLZ_Invert(pak_buffer, pak_len);

  if (!pak_tmp || (raw_len + 4 < ((pak_tmp + raw_tmp + 3) & -4) + 8)) {
    pak = pak_buffer;
    raw = raw_buffer;
    raw_end = raw_buffer + raw_len;

    while (raw < raw_end) *pak++ = *raw++;

    while ((pak - pak_buffer) & 3) *pak++ = 0;

    *(u32 *)pak = 0; pak += 4;
  } else {
    tmp = (u8 *) Memory(raw_tmp + pak_tmp + 15, sizeof(char));

    for (len = 0; len < raw_tmp; len++)
      tmp[len] = raw_buffer[len];

    for (len = 0; len < pak_tmp; len++)
      tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];

    pak = pak_buffer;
    pak_buffer = tmp;

    free(pak);

    pak = pak_buffer + raw_tmp + pak_tmp;

    enc_len = pak_tmp;
    hdr_len = 12;
    inc_len = raw_len - pak_tmp - raw_tmp;

    while ((pak - pak_buffer) & 3) {
      *pak++ = 0xFF;
      hdr_len++;
    }

    *(u32 *)pak = enc_len + hdr_len; pak += 4;
    *(u32 *)pak = hdr_len;           pak += 4;
    *(u32 *)pak = inc_len - hdr_len; pak += 4;
  }

  *new_len = pak - pak_buffer;

  return(pak_buffer);
}

/*----------------------------------------------------------------------------*/
void BLZ_Invert(u8 *buffer, int length) {
  u8 *bottom, ch;

  bottom = buffer + length - 1;

  while (buffer < bottom) {
    ch = *buffer;
    *buffer++ = *bottom;
    *bottom-- = ch;
  }
}

/*----------------------------------------------------------------------------*/
/*--  EOF                                           Copyright (C) 2011 CUE  --*/
/*----------------------------------------------------------------------------*/


================================================
FILE: src/blz.h
================================================
#pragma once

#include <stdint.h>

typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;

#define BLZ_NORMAL    0          // normal mode
#define BLZ_BEST      1          // best mode

u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);

================================================
FILE: src/cJSON.c
================================================
/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

/* cJSON */
/* JSON parser in C. */

/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif

#ifdef __GNUC__
#pragma GCC visibility push(default)
#endif
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>

#ifdef ENABLE_LOCALES
#include <locale.h>
#endif

#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#ifdef __GNUC__
#pragma GCC visibility pop
#endif

#include "cJSON.h"

/* define our own boolean type */
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)

typedef struct {
    const unsigned char *json;
    size_t position;
} error;
static error global_error = { NULL, 0 };

CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
{
    return (const char*) (global_error.json + global_error.position);
}

CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) {
    if (!cJSON_IsString(item)) {
        return NULL;
    }

    return item->valuestring;
}

/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 6)
    #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
#endif

CJSON_PUBLIC(const char*) cJSON_Version(void)
{
    static char version[15];
    sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);

    return version;
}

/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
{
    if ((string1 == NULL) || (string2 == NULL))
    {
        return 1;
    }

    if (string1 == string2)
    {
        return 0;
    }

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
    {
        if (*string1 == '\0')
        {
            return 0;
        }
    }

    return tolower(*string1) - tolower(*string2);
}

typedef struct internal_hooks
{
    void *(*allocate)(size_t size);
    void (*deallocate)(void *pointer);
    void *(*reallocate)(void *pointer, size_t size);
} internal_hooks;

#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dillimport '...' is not static */
static void *internal_malloc(size_t size)
{
    return malloc(size);
}
static void internal_free(void *pointer)
{
    free(pointer);
}
static void *internal_realloc(void *pointer, size_t size)
{
    return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif

static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };

static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
{
    size_t length = 0;
    unsigned char *copy = NULL;

    if (string == NULL)
    {
        return NULL;
    }

    length = strlen((const char*)string) + sizeof("");
    copy = (unsigned char*)hooks->allocate(length);
    if (copy == NULL)
    {
        return NULL;
    }
    memcpy(copy, string, length);

    return copy;
}

CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
{
    if (hooks == NULL)
    {
        /* Reset hooks */
        global_hooks.allocate = malloc;
        global_hooks.deallocate = free;
        global_hooks.reallocate = realloc;
        return;
    }

    global_hooks.allocate = malloc;
    if (hooks->malloc_fn != NULL)
    {
        global_hooks.allocate = hooks->malloc_fn;
    }

    global_hooks.deallocate = free;
    if (hooks->free_fn != NULL)
    {
        global_hooks.deallocate = hooks->free_fn;
    }

    /* use realloc only if both free and malloc are used */
    global_hooks.reallocate = NULL;
    if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
    {
        global_hooks.reallocate = realloc;
    }
}

/* Internal constructor. */
static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
{
    cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
    if (node)
    {
        memset(node, '\0', sizeof(cJSON));
    }

    return node;
}

/* Delete a cJSON structure. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
{
    cJSON *next = NULL;
    while (item != NULL)
    {
        next = item->next;
        if (!(item->type & cJSON_IsReference) && (item->child != NULL))
        {
            cJSON_Delete(item->child);
        }
        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
        {
            global_hooks.deallocate(item->valuestring);
        }
        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
        {
            global_hooks.deallocate(item->string);
        }
        global_hooks.deallocate(item);
        item = next;
    }
}

/* get the decimal point character of the current locale */
static unsigned char get_decimal_point(void)
{
#ifdef ENABLE_LOCALES
    struct lconv *lconv = localeconv();
    return (unsigned char) lconv->decimal_point[0];
#else
    return '.';
#endif
}

typedef struct
{
    const unsigned char *content;
    size_t length;
    size_t offset;
    size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
    internal_hooks hooks;
} parse_buffer;

/* check if the given size is left to read in a given parse buffer (starting with 1) */
#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
/* check if the buffer can be accessed at the given index (starting with 0) */
#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
/* get a pointer to the buffer at the position */
#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)

/* Parse the input text to generate a number, and populate the result into item. */
static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
{
    double number = 0;
    unsigned char *after_end = NULL;
    unsigned char number_c_string[64];
    unsigned char decimal_point = get_decimal_point();
    size_t i = 0;

    if ((input_buffer == NULL) || (input_buffer->content == NULL))
    {
        return false;
    }

    /* copy the number into a temporary buffer and replace '.' with the decimal point
     * of the current locale (for strtod)
     * This also takes care of '\0' not necessarily being available for marking the end of the input */
    for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++)
    {
        switch (buffer_at_offset(input_buffer)[i])
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '+':
            case '-':
            case 'e':
            case 'E':
                number_c_string[i] = buffer_at_offset(input_buffer)[i];
                break;

            case '.':
                number_c_string[i] = decimal_point;
                break;

            default:
                goto loop_end;
        }
    }
loop_end:
    number_c_string[i] = '\0';

    number = strtod((const char*)number_c_string, (char**)&after_end);
    if (number_c_string == after_end)
    {
        return false; /* parse_error */
    }

    item->valuedouble = number;

    /* use saturation in case of overflow */
    if (number >= INT_MAX)
    {
        item->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        item->valueint = INT_MIN;
    }
    else
    {
        item->valueint = (int)number;
    }

    item->type = cJSON_Number;

    input_buffer->offset += (size_t)(after_end - number_c_string);
    return true;
}

/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
{
    if (number >= INT_MAX)
    {
        object->valueint = INT_MAX;
    }
    else if (number <= INT_MIN)
    {
        object->valueint = INT_MIN;
    }
    else
    {
        object->valueint = (int)number;
    }

    return object->valuedouble = number;
}

typedef struct
{
    unsigned char *buffer;
    size_t length;
    size_t offset;
    size_t depth; /* current nesting depth (for formatted printing) */
    cJSON_bool noalloc;
    cJSON_bool format; /* is this print a formatted print */
    internal_hooks hooks;
} printbuffer;

/* realloc printbuffer if necessary to have at least "needed" bytes more */
static unsigned char* ensure(printbuffer * const p, size_t needed)
{
    unsigned char *newbuffer = NULL;
    size_t newsize = 0;

    if ((p == NULL) || (p->buffer == NULL))
    {
        return NULL;
    }

    if ((p->length > 0) && (p->offset >= p->length))
    {
        /* make sure that offset is valid */
        return NULL;
    }

    if (needed > INT_MAX)
    {
        /* sizes bigger than INT_MAX are currently not supported */
        return NULL;
    }

    needed += p->offset + 1;
    if (needed <= p->length)
    {
        return p->buffer + p->offset;
    }

    if (p->noalloc) {
        return NULL;
    }

    /* calculate new buffer size */
    if (needed > (INT_MAX / 2))
    {
        /* overflow of int, use INT_MAX if possible */
        if (needed <= INT_MAX)
        {
            newsize = INT_MAX;
        }
        else
        {
            return NULL;
        }
    }
    else
    {
        newsize = needed * 2;
    }

    if (p->hooks.reallocate != NULL)
    {
        /* reallocate with realloc if available */
        newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
        if (newbuffer == NULL)
        {
            p->hooks.deallocate(p->buffer);
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
    }
    else
    {
        /* otherwise reallocate manually */
        newbuffer = (unsigned char*)p->hooks.allocate(newsize);
        if (!newbuffer)
        {
            p->hooks.deallocate(p->buffer);
            p->length = 0;
            p->buffer = NULL;

            return NULL;
        }
        if (newbuffer)
        {
            memcpy(newbuffer, p->buffer, p->offset + 1);
        }
        p->hooks.deallocate(p->buffer);
    }
    p->length = newsize;
    p->buffer = newbuffer;

    return newbuffer + p->offset;
}

/* calculate the new length of the string in a printbuffer and update the offset */
static void update_offset(printbuffer * const buffer)
{
    const unsigned char *buffer_pointer = NULL;
    if ((buffer == NULL) || (buffer->buffer == NULL))
    {
        return;
    }
    buffer_pointer = buffer->buffer + buffer->offset;

    buffer->offset += strlen((const char*)buffer_pointer);
}

/* Render the number nicely from the given item into a string. */
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
{
    unsigned char *output_pointer = NULL;
    double d = item->valuedouble;
    int length = 0;
    size_t i = 0;
    unsigned char number_buffer[26]; /* temporary buffer to print the number into */
    unsigned char decimal_point = get_decimal_point();
    double test;

    if (output_buffer == NULL)
    {
        return false;
    }

    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
        length = sprintf((char*)number_buffer, "null");
    }
    else
    {
        /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
        length = sprintf((char*)number_buffer, "%1.15g", d);

        /* Check whether the original double can be recovered */
        if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d))
        {
            /* If not, print with 17 decimal places of precision */
            length = sprintf((char*)number_buffer, "%1.17g", d);
        }
    }

    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
    {
        return false;
    }

    /* reserve appropriate space in the output */
    output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
    if (output_pointer == NULL)
    {
        return false;
    }

    /* copy the printed number to the output and replace locale
     * dependent decimal point with '.' */
    for (i = 0; i < ((size_t)length); i++)
    {
        if (number_buffer[i] == decimal_point)
        {
            output_pointer[i] = '.';
            continue;
        }

        output_pointer[i] = number_buffer[i];
    }
    output_pointer[i] = '\0';

    output_buffer->offset += (size_t)length;

    return true;
}

/* parse 4 digit hexadecimal number */
static unsigned parse_hex4(const unsigned char * const input)
{
    unsigned int h = 0;
    size_t i = 0;

    for (i = 0; i < 4; i++)
    {
        /* parse digit */
        if ((input[i] >= '0') && (input[i] <= '9'))
        {
            h += (unsigned int) input[i] - '0';
        }
        else if ((input[i] >= 'A') && (input[i] <= 'F'))
        {
            h += (unsigned int) 10 + input[i] - 'A';
        }
        else if ((input[i] >= 'a') && (input[i] <= 'f'))
        {
            h += (unsigned int) 10 + input[i] - 'a';
        }
        else /* invalid */
        {
            return 0;
        }

        if (i < 3)
        {
            /* shift left to make place for the next nibble */
            h = h << 4;
        }
    }

    return h;
}

/* converts a UTF-16 literal to UTF-8
 * A literal can be one or two sequences of the form \uXXXX */
static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
{
    long unsigned int codepoint = 0;
    unsigned int first_code = 0;
    const unsigned char *first_sequence = input_pointer;
    unsigned char utf8_length = 0;
    unsigned char utf8_position = 0;
    unsigned char sequence_length = 0;
    unsigned char first_byte_mark = 0;

    if ((input_end - first_sequence) < 6)
    {
        /* input ends unexpectedly */
        goto fail;
    }

    /* get the first utf16 sequence */
    first_code = parse_hex4(first_sequence + 2);

    /* check that the code is valid */
    if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
    {
        goto fail;
    }

    /* UTF16 surrogate pair */
    if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
    {
        const unsigned char *second_sequence = first_sequence + 6;
        unsigned int second_code = 0;
        sequence_length = 12; /* \uXXXX\uXXXX */

        if ((input_end - second_sequence) < 6)
        {
            /* input ends unexpectedly */
            goto fail;
        }

        if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
        {
            /* missing second half of the surrogate pair */
            goto fail;
        }

        /* get the second utf16 sequence */
        second_code = parse_hex4(second_sequence + 2);
        /* check that the code is valid */
        if ((second_code < 0xDC00) || (second_code > 0xDFFF))
        {
            /* invalid second half of the surrogate pair */
            goto fail;
        }


        /* calculate the unicode codepoint from the surrogate pair */
        codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
    }
    else
    {
        sequence_length = 6; /* \uXXXX */
        codepoint = first_code;
    }

    /* encode as UTF-8
     * takes at maximum 4 bytes to encode:
     * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
    if (codepoint < 0x80)
    {
        /* normal ascii, encoding 0xxxxxxx */
        utf8_length = 1;
    }
    else if (codepoint < 0x800)
    {
        /* two bytes, encoding 110xxxxx 10xxxxxx */
        utf8_length = 2;
        first_byte_mark = 0xC0; /* 11000000 */
    }
    else if (codepoint < 0x10000)
    {
        /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
        utf8_length = 3;
        first_byte_mark = 0xE0; /* 11100000 */
    }
    else if (codepoint <= 0x10FFFF)
    {
        /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
        utf8_length = 4;
        first_byte_mark = 0xF0; /* 11110000 */
    }
    else
    {
        /* invalid unicode codepoint */
        goto fail;
    }

    /* encode as utf8 */
    for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
    {
        /* 10xxxxxx */
        (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
        codepoint >>= 6;
    }
    /* encode first byte */
    if (utf8_length > 1)
    {
        (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
    }
    else
    {
        (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
    }

    *output_pointer += utf8_length;

    return sequence_length;

fail:
    return 0;
}

/* Parse the input text into an unescaped cinput, and populate item. */
static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
{
    const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
    const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
    unsigned char *output_pointer = NULL;
    unsigned char *output = NULL;

    /* not a string */
    if (buffer_at_offset(input_buffer)[0] != '\"')
    {
        goto fail;
    }

    {
        /* calculate approximate size of the output (overestimate) */
        size_t allocation_length = 0;
        size_t skipped_bytes = 0;
        while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
        {
            /* is escape sequence */
            if (input_end[0] == '\\')
            {
                if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
                {
                    /* prevent buffer overflow when last input character is a backslash */
                    goto fail;
                }
                skipped_bytes++;
                input_end++;
            }
            input_end++;
        }
        if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
        {
            goto fail; /* string ended unexpectedly */
        }

        /* This is at most how much we need for the output */
        allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
        output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
        if (output == NULL)
        {
            goto fail; /* allocation failure */
        }
    }

    output_pointer = output;
    /* loop through the string literal */
    while (input_pointer < input_end)
    {
        if (*input_pointer != '\\')
        {
            *output_pointer++ = *input_pointer++;
        }
        /* escape sequence */
        else
        {
            unsigned char sequence_length = 2;
            if ((input_end - input_pointer) < 1)
            {
                goto fail;
            }

            switch (input_pointer[1])
            {
                case 'b':
                    *output_pointer++ = '\b';
                    break;
                case 'f':
                    *output_pointer++ = '\f';
                    break;
                case 'n':
                    *output_pointer++ = '\n';
                    break;
                case 'r':
                    *output_pointer++ = '\r';
                    break;
                case 't':
                    *output_pointer++ = '\t';
                    break;
                case '\"':
                case '\\':
                case '/':
                    *output_pointer++ = input_pointer[1];
                    break;

                /* UTF-16 literal */
                case 'u':
                    sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
                    if (sequence_length == 0)
                    {
                        /* failed to convert UTF16-literal to UTF-8 */
                        goto fail;
                    }
                    break;

                default:
                    goto fail;
            }
            input_pointer += sequence_length;
        }
    }

    /* zero terminate the output */
    *output_pointer = '\0';

    item->type = cJSON_String;
    item->valuestring = (char*)output;

    input_buffer->offset = (size_t) (input_end - input_buffer->content);
    input_buffer->offset++;

    return true;

fail:
    if (output != NULL)
    {
        input_buffer->hooks.deallocate(output);
    }

    if (input_pointer != NULL)
    {
        input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
    }

    return false;
}

/* Render the cstring provided to an escaped version that can be printed. */
static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
{
    const unsigned char *input_pointer = NULL;
    unsigned char *output = NULL;
    unsigned char *output_pointer = NULL;
    size_t output_length = 0;
    /* numbers of additional characters needed for escaping */
    size_t escape_characters = 0;

    if (output_buffer == NULL)
    {
        return false;
    }

    /* empty string */
    if (input == NULL)
    {
        output = ensure(output_buffer, sizeof("\"\""));
        if (output == NULL)
        {
            return false;
        }
        strcpy((char*)output, "\"\"");

        return true;
    }

    /* set "flag" to 1 if something needs to be escaped */
    for (input_pointer = input; *input_pointer; input_pointer++)
    {
        switch (*input_pointer)
        {
            case '\"':
            case '\\':
            case '\b':
            case '\f':
            case '\n':
            case '\r':
            case '\t':
                /* one character escape sequence */
                escape_characters++;
                break;
            default:
                if (*input_pointer < 32)
                {
                    /* UTF-16 escape sequence uXXXX */
                    escape_characters += 5;
                }
                break;
        }
    }
    output_length = (size_t)(input_pointer - input) + escape_characters;

    output = ensure(output_buffer, output_length + sizeof("\"\""));
    if (output == NULL)
    {
        return false;
    }

    /* no characters have to be escaped */
    if (escape_characters == 0)
    {
        output[0] = '\"';
        memcpy(output + 1, input, output_length);
        output[output_length + 1] = '\"';
        output[output_length + 2] = '\0';

        return true;
    }

    output[0] = '\"';
    output_pointer = output + 1;
    /* copy the string */
    for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
    {
        if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
        {
            /* normal character, copy */
            *output_pointer = *input_pointer;
        }
        else
        {
            /* character needs to be escaped */
            *output_pointer++ = '\\';
            switch (*input_pointer)
            {
                case '\\':
                    *output_pointer = '\\';
                    break;
                case '\"':
                    *output_pointer = '\"';
                    break;
                case '\b':
                    *output_pointer = 'b';
                    break;
                case '\f':
                    *output_pointer = 'f';
                    break;
                case '\n':
                    *output_pointer = 'n';
                    break;
                case '\r':
                    *output_pointer = 'r';
                    break;
                case '\t':
                    *output_pointer = 't';
                    break;
                default:
                    /* escape and print as unicode codepoint */
                    sprintf((char*)output_pointer, "u%04x", *input_pointer);
                    output_pointer += 4;
                    break;
            }
        }
    }
    output[output_length + 1] = '\"';
    output[output_length + 2] = '\0';

    return true;
}

/* Invoke print_string_ptr (which is useful) on an item. */
static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
{
    return print_string_ptr((unsigned char*)item->valuestring, p);
}

/* Predeclare these prototypes. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);

/* Utility to jump whitespace and cr/lf */
static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
{
    if ((buffer == NULL) || (buffer->content == NULL))
    {
        return NULL;
    }

    while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
    {
       buffer->offset++;
    }

    if (buffer->offset == buffer->length)
    {
        buffer->offset--;
    }

    return buffer;
}

/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
{
    if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
    {
        return NULL;
    }

    if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
    {
        buffer->offset += 3;
    }

    return buffer;
}

/* Parse an object - create a new root, and populate. */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
{
    parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
    cJSON *item = NULL;

    /* reset error position */
    global_error.json = NULL;
    global_error.position = 0;

    if (value == NULL)
    {
        goto fail;
    }

    buffer.content = (const unsigned char*)value;
    buffer.length = strlen((const char*)value) + sizeof("");
    buffer.offset = 0;
    buffer.hooks = global_hooks;

    item = cJSON_New_Item(&global_hooks);
    if (item == NULL) /* memory fail */
    {
        goto fail;
    }

    if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
    {
        /* parse failure. ep is set. */
        goto fail;
    }

    /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
    if (require_null_terminated)
    {
        buffer_skip_whitespace(&buffer);
        if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
        {
            goto fail;
        }
    }
    if (return_parse_end)
    {
        *return_parse_end = (const char*)buffer_at_offset(&buffer);
    }

    return item;

fail:
    if (item != NULL)
    {
        cJSON_Delete(item);
    }

    if (value != NULL)
    {
        error local_error;
        local_error.json = (const unsigned char*)value;
        local_error.position = 0;

        if (buffer.offset < buffer.length)
        {
            local_error.position = buffer.offset;
        }
        else if (buffer.length > 0)
        {
            local_error.position = buffer.length - 1;
        }

        if (return_parse_end != NULL)
        {
            *return_parse_end = (const char*)local_error.json + local_error.position;
        }

        global_error = local_error;
    }

    return NULL;
}

/* Default options for cJSON_Parse */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
{
    return cJSON_ParseWithOpts(value, 0, 0);
}

#define cjson_min(a, b) ((a < b) ? a : b)

static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
{
    static const size_t default_buffer_size = 256;
    printbuffer buffer[1];
    unsigned char *printed = NULL;

    memset(buffer, 0, sizeof(buffer));

    /* create buffer */
    buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
    buffer->length = default_buffer_size;
    buffer->format = format;
    buffer->hooks = *hooks;
    if (buffer->buffer == NULL)
    {
        goto fail;
    }

    /* print the value */
    if (!print_value(item, buffer))
    {
        goto fail;
    }
    update_offset(buffer);

    /* check if reallocate is available */
    if (hooks->reallocate != NULL)
    {
        printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
        buffer->buffer = NULL;
        if (printed == NULL) {
            goto fail;
        }
    }
    else /* otherwise copy the JSON over to a new buffer */
    {
        printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
        if (printed == NULL)
        {
            goto fail;
        }
        memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
        printed[buffer->offset] = '\0'; /* just to be sure */

        /* free the buffer */
        hooks->deallocate(buffer->buffer);
    }

    return printed;

fail:
    if (buffer->buffer != NULL)
    {
        hooks->deallocate(buffer->buffer);
    }

    if (printed != NULL)
    {
        hooks->deallocate(printed);
    }

    return NULL;
}

/* Render a cJSON item/entity/structure to text. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
{
    return (char*)print(item, true, &global_hooks);
}

CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
{
    return (char*)print(item, false, &global_hooks);
}

CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
{
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };

    if (prebuffer < 0)
    {
        return NULL;
    }

    p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
    if (!p.buffer)
    {
        return NULL;
    }

    p.length = (size_t)prebuffer;
    p.offset = 0;
    p.noalloc = false;
    p.format = fmt;
    p.hooks = global_hooks;

    if (!print_value(item, &p))
    {
        global_hooks.deallocate(p.buffer);
        return NULL;
    }

    return (char*)p.buffer;
}

CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt)
{
    printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };

    if ((len < 0) || (buf == NULL))
    {
        return false;
    }

    p.buffer = (unsigned char*)buf;
    p.length = (size_t)len;
    p.offset = 0;
    p.noalloc = true;
    p.format = fmt;
    p.hooks = global_hooks;

    return print_value(item, &p);
}

/* Parser core - when encountering text, process appropriately. */
static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
{
    if ((input_buffer == NULL) || (input_buffer->content == NULL))
    {
        return false; /* no input */
    }

    /* parse the different types of values */
    /* null */
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
    {
        item->type = cJSON_NULL;
        input_buffer->offset += 4;
        return true;
    }
    /* false */
    if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
    {
        item->type = cJSON_False;
        input_buffer->offset += 5;
        return true;
    }
    /* true */
    if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
    {
        item->type = cJSON_True;
        item->valueint = 1;
        input_buffer->offset += 4;
        return true;
    }
    /* string */
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
    {
        return parse_string(item, input_buffer);
    }
    /* number */
    if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
    {
        return parse_number(item, input_buffer);
    }
    /* array */
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
    {
        return parse_array(item, input_buffer);
    }
    /* object */
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
    {
        return parse_object(item, input_buffer);
    }

    return false;
}

/* Render a value to text. */
static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
{
    unsigned char *output = NULL;

    if ((item == NULL) || (output_buffer == NULL))
    {
        return false;
    }

    switch ((item->type) & 0xFF)
    {
        case cJSON_NULL:
            output = ensure(output_buffer, 5);
            if (output == NULL)
            {
                return false;
            }
            strcpy((char*)output, "null");
            return true;

        case cJSON_False:
            output = ensure(output_buffer, 6);
            if (output == NULL)
            {
                return false;
            }
            strcpy((char*)output, "false");
            return true;

        case cJSON_True:
            output = ensure(output_buffer, 5);
            if (output == NULL)
            {
                return false;
            }
            strcpy((char*)output, "true");
            return true;

        case cJSON_Number:
            return print_number(item, output_buffer);

        case cJSON_Raw:
        {
            size_t raw_length = 0;
            if (item->valuestring == NULL)
            {
                return false;
            }

            raw_length = strlen(item->valuestring) + sizeof("");
            output = ensure(output_buffer, raw_length);
            if (output == NULL)
            {
                return false;
            }
            memcpy(output, item->valuestring, raw_length);
            return true;
        }

        case cJSON_String:
            return print_string(item, output_buffer);

        case cJSON_Array:
            return print_array(item, output_buffer);

        case cJSON_Object:
            return print_object(item, output_buffer);

        default:
            return false;
    }
}

/* Build an array from input text. */
static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
{
    cJSON *head = NULL; /* head of the linked list */
    cJSON *current_item = NULL;

    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

    if (buffer_at_offset(input_buffer)[0] != '[')
    {
        /* not an array */
        goto fail;
    }

    input_buffer->offset++;
    buffer_skip_whitespace(input_buffer);
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
    {
        /* empty array */
        goto success;
    }

    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

    /* step back to character in front of the first element */
    input_buffer->offset--;
    /* loop through the comma separated array elements */
    do
    {
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }

        /* attach next item to list */
        if (head == NULL)
        {
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
        }

        /* parse next value */
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        if (!parse_value(current_item, input_buffer))
        {
            goto fail; /* failed to parse value */
        }
        buffer_skip_whitespace(input_buffer);
    }
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));

    if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
    {
        goto fail; /* expected end of array */
    }

success:
    input_buffer->depth--;

    item->type = cJSON_Array;
    item->child = head;

    input_buffer->offset++;

    return true;

fail:
    if (head != NULL)
    {
        cJSON_Delete(head);
    }

    return false;
}

/* Render an array to text */
static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
{
    unsigned char *output_pointer = NULL;
    size_t length = 0;
    cJSON *current_element = item->child;

    if (output_buffer == NULL)
    {
        return false;
    }

    /* Compose the output array. */
    /* opening square bracket */
    output_pointer = ensure(output_buffer, 1);
    if (output_pointer == NULL)
    {
        return false;
    }

    *output_pointer = '[';
    output_buffer->offset++;
    output_buffer->depth++;

    while (current_element != NULL)
    {
        if (!print_value(current_element, output_buffer))
        {
            return false;
        }
        update_offset(output_buffer);
        if (current_element->next)
        {
            length = (size_t) (output_buffer->format ? 2 : 1);
            output_pointer = ensure(output_buffer, length + 1);
            if (output_pointer == NULL)
            {
                return false;
            }
            *output_pointer++ = ',';
            if(output_buffer->format)
            {
                *output_pointer++ = ' ';
            }
            *output_pointer = '\0';
            output_buffer->offset += length;
        }
        current_element = current_element->next;
    }

    output_pointer = ensure(output_buffer, 2);
    if (output_pointer == NULL)
    {
        return false;
    }
    *output_pointer++ = ']';
    *output_pointer = '\0';
    output_buffer->depth--;

    return true;
}

/* Build an object from the text. */
static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
{
    cJSON *head = NULL; /* linked list head */
    cJSON *current_item = NULL;

    if (input_buffer->depth >= CJSON_NESTING_LIMIT)
    {
        return false; /* to deeply nested */
    }
    input_buffer->depth++;

    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
    {
        goto fail; /* not an object */
    }

    input_buffer->offset++;
    buffer_skip_whitespace(input_buffer);
    if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
    {
        goto success; /* empty object */
    }

    /* check if we skipped to the end of the buffer */
    if (cannot_access_at_index(input_buffer, 0))
    {
        input_buffer->offset--;
        goto fail;
    }

    /* step back to character in front of the first element */
    input_buffer->offset--;
    /* loop through the comma separated array elements */
    do
    {
        /* allocate next item */
        cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
        if (new_item == NULL)
        {
            goto fail; /* allocation failure */
        }

        /* attach next item to list */
        if (head == NULL)
        {
            /* start the linked list */
            current_item = head = new_item;
        }
        else
        {
            /* add to the end and advance */
            current_item->next = new_item;
            new_item->prev = current_item;
            current_item = new_item;
        }

        /* parse the name of the child */
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        if (!parse_string(current_item, input_buffer))
        {
            goto fail; /* faile to parse name */
        }
        buffer_skip_whitespace(input_buffer);

        /* swap valuestring and string, because we parsed the name */
        current_item->string = current_item->valuestring;
        current_item->valuestring = NULL;

        if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
        {
            goto fail; /* invalid object */
        }

        /* parse the value */
        input_buffer->offset++;
        buffer_skip_whitespace(input_buffer);
        if (!parse_value(current_item, input_buffer))
        {
            goto fail; /* failed to parse value */
        }
        buffer_skip_whitespace(input_buffer);
    }
    while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));

    if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
    {
        goto fail; /* expected end of object */
    }

success:
    input_buffer->depth--;

    item->type = cJSON_Object;
    item->child = head;

    input_buffer->offset++;
    return true;

fail:
    if (head != NULL)
    {
        cJSON_Delete(head);
    }

    return false;
}

/* Render an object to text. */
static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
{
    unsigned char *output_pointer = NULL;
    size_t length = 0;
    cJSON *current_item = item->child;

    if (output_buffer == NULL)
    {
        return false;
    }

    /* Compose the output: */
    length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
    output_pointer = ensure(output_buffer, length + 1);
    if (output_pointer == NULL)
    {
        return false;
    }

    *output_pointer++ = '{';
    output_buffer->depth++;
    if (output_buffer->format)
    {
        *output_pointer++ = '\n';
    }
    output_buffer->offset += length;

    while (current_item)
    {
        if (output_buffer->format)
        {
            size_t i;
            output_pointer = ensure(output_buffer, output_buffer->depth);
            if (output_pointer == NULL)
            {
                return false;
            }
            for (i = 0; i < output_buffer->depth; i++)
            {
                *output_pointer++ = '\t';
            }
            output_buffer->offset += output_buffer->depth;
        }

        /* print key */
        if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
        {
            return false;
        }
        update_offset(output_buffer);

        length = (size_t) (output_buffer->format ? 2 : 1);
        output_pointer = ensure(output_buffer, length);
        if (output_pointer == NULL)
        {
            return false;
        }
        *output_pointer++ = ':';
        if (output_buffer->format)
        {
            *output_pointer++ = '\t';
        }
        output_buffer->offset += length;

        /* print value */
        if (!print_value(current_item, output_buffer))
        {
            return false;
        }
        update_offset(output_buffer);

        /* print comma if not last */
        length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0));
        output_pointer = ensure(output_buffer, length + 1);
        if (output_pointer == NULL)
        {
            return false;
        }
        if (current_item->next)
        {
            *output_pointer++ = ',';
        }

        if (output_buffer->format)
        {
            *output_pointer++ = '\n';
        }
        *output_pointer = '\0';
        output_buffer->offset += length;

        current_item = current_item->next;
    }

    output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
    if (output_pointer == NULL)
    {
        return false;
    }
    if (output_buffer->format)
    {
        size_t i;
        for (i = 0; i < (output_buffer->depth - 1); i++)
        {
            *output_pointer++ = '\t';
        }
    }
    *output_pointer++ = '}';
    *output_pointer = '\0';
    output_buffer->depth--;

    return true;
}

/* Get Array size/item / object item. */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
{
    cJSON *child = NULL;
    size_t size = 0;

    if (array == NULL)
    {
        return 0;
    }

    child = array->child;

    while(child != NULL)
    {
        size++;
        child = child->next;
    }

    /* FIXME: Can overflow here. Cannot be fixed without breaking the API */

    return (int)size;
}

static cJSON* get_array_item(const cJSON *array, size_t index)
{
    cJSON *current_child = NULL;

    if (array == NULL)
    {
        return NULL;
    }

    current_child = array->child;
    while ((current_child != NULL) && (index > 0))
    {
        index--;
        current_child = current_child->next;
    }

    return current_child;
}

CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
{
    if (index < 0)
    {
        return NULL;
    }

    return get_array_item(array, (size_t)index);
}

static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
{
    cJSON *current_element = NULL;

    if ((object == NULL) || (name == NULL))
    {
        return NULL;
    }

    current_element = object->child;
    if (case_sensitive)
    {
        while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
        {
            current_element = current_element->next;
        }
    }
    else
    {
        while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
        {
            current_element = current_element->next;
        }
    }

    return current_element;
}

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
{
    return get_object_item(object, string, false);
}

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
{
    return get_object_item(object, string, true);
}

CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
{
    return cJSON_GetObjectItem(object, string) ? 1 : 0;
}

/* Utility for array list handling. */
static void suffix_object(cJSON *prev, cJSON *item)
{
    prev->next = item;
    item->prev = prev;
}

/* Utility for handling references. */
static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
{
    cJSON *reference = NULL;
    if (item == NULL)
    {
        return NULL;
    }

    reference = cJSON_New_Item(hooks);
    if (reference == NULL)
    {
        return NULL;
    }

    memcpy(reference, item, sizeof(cJSON));
    reference->string = NULL;
    reference->type |= cJSON_IsReference;
    reference->next = reference->prev = NULL;
    return reference;
}

static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
{
    cJSON *child = NULL;

    if ((item == NULL) || (array == NULL))
    {
        return false;
    }

    child = array->child;

    if (child == NULL)
    {
        /* list is empty, start new one */
        array->child = item;
    }
    else
    {
        /* append to the end */
        while (child->next)
        {
            child = child->next;
        }
        suffix_object(child, item);
    }

    return true;
}

/* Add item to array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
{
    add_item_to_array(array, item);
}

#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic push
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
/* helper function to cast away const */
static void* cast_away_const(const void* string)
{
    return (void*)string;
}
#if defined(__clang__) || (defined(__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
    #pragma GCC diagnostic pop
#endif


static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
{
    char *new_key = NULL;
    int new_type = cJSON_Invalid;

    if ((object == NULL) || (string == NULL) || (item == NULL))
    {
        return false;
    }

    if (constant_key)
    {
        new_key = (char*)cast_away_const(string);
        new_type = item->type | cJSON_StringIsConst;
    }
    else
    {
        new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
        if (new_key == NULL)
        {
            return false;
        }

        new_type = item->type & ~cJSON_StringIsConst;
    }

    if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
    {
        hooks->deallocate(item->string);
    }

    item->string = new_key;
    item->type = new_type;

    return add_item_to_array(object, item);
}

CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
{
    add_item_to_object(object, string, item, &global_hooks, false);
}

/* Add an item to an object with constant string as key */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
{
    add_item_to_object(object, string, item, &global_hooks, true);
}

CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
{
    if (array == NULL)
    {
        return;
    }

    add_item_to_array(array, create_reference(item, &global_hooks));
}

CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
{
    if ((object == NULL) || (string == NULL))
    {
        return;
    }

    add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
}

CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
{
    cJSON *null = cJSON_CreateNull();
    if (add_item_to_object(object, name, null, &global_hooks, false))
    {
        return null;
    }

    cJSON_Delete(null);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
{
    cJSON *true_item = cJSON_CreateTrue();
    if (add_item_to_object(object, name, true_item, &global_hooks, false))
    {
        return true_item;
    }

    cJSON_Delete(true_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
{
    cJSON *false_item = cJSON_CreateFalse();
    if (add_item_to_object(object, name, false_item, &global_hooks, false))
    {
        return false_item;
    }

    cJSON_Delete(false_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
{
    cJSON *bool_item = cJSON_CreateBool(boolean);
    if (add_item_to_object(object, name, bool_item, &global_hooks, false))
    {
        return bool_item;
    }

    cJSON_Delete(bool_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
{
    cJSON *number_item = cJSON_CreateNumber(number);
    if (add_item_to_object(object, name, number_item, &global_hooks, false))
    {
        return number_item;
    }

    cJSON_Delete(number_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
{
    cJSON *string_item = cJSON_CreateString(string);
    if (add_item_to_object(object, name, string_item, &global_hooks, false))
    {
        return string_item;
    }

    cJSON_Delete(string_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
{
    cJSON *raw_item = cJSON_CreateRaw(raw);
    if (add_item_to_object(object, name, raw_item, &global_hooks, false))
    {
        return raw_item;
    }

    cJSON_Delete(raw_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
{
    cJSON *object_item = cJSON_CreateObject();
    if (add_item_to_object(object, name, object_item, &global_hooks, false))
    {
        return object_item;
    }

    cJSON_Delete(object_item);
    return NULL;
}

CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
{
    cJSON *array = cJSON_CreateArray();
    if (add_item_to_object(object, name, array, &global_hooks, false))
    {
        return array;
    }

    cJSON_Delete(array);
    return NULL;
}

CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
{
    if ((parent == NULL) || (item == NULL))
    {
        return NULL;
    }

    if (item->prev != NULL)
    {
        /* not the first element */
        item->prev->next = item->next;
    }
    if (item->next != NULL)
    {
        /* not the last element */
        item->next->prev = item->prev;
    }

    if (item == parent->child)
    {
        /* first element */
        parent->child = item->next;
    }
    /* make sure the detached item doesn't point anywhere anymore */
    item->prev = NULL;
    item->next = NULL;

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
{
    if (which < 0)
    {
        return NULL;
    }

    return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
}

CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
{
    cJSON_Delete(cJSON_DetachItemFromArray(array, which));
}

CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
{
    cJSON *to_detach = cJSON_GetObjectItem(object, string);

    return cJSON_DetachItemViaPointer(object, to_detach);
}

CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
    cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);

    return cJSON_DetachItemViaPointer(object, to_detach);
}

CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObject(object, string));
}

CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
    cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}

/* Replace array/object items with new ones. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
{
    cJSON *after_inserted = NULL;

    if (which < 0)
    {
        return;
    }

    after_inserted = get_array_item(array, (size_t)which);
    if (after_inserted == NULL)
    {
        add_item_to_array(array, newitem);
        return;
    }

    newitem->next = after_inserted;
    newitem->prev = after_inserted->prev;
    after_inserted->prev = newitem;
    if (after_inserted == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }
}

CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
{
    if ((parent == NULL) || (replacement == NULL) || (item == NULL))
    {
        return false;
    }

    if (replacement == item)
    {
        return true;
    }

    replacement->next = item->next;
    replacement->prev = item->prev;

    if (replacement->next != NULL)
    {
        replacement->next->prev = replacement;
    }
    if (replacement->prev != NULL)
    {
        replacement->prev->next = replacement;
    }
    if (parent->child == item)
    {
        parent->child = replacement;
    }

    item->next = NULL;
    item->prev = NULL;
    cJSON_Delete(item);

    return true;
}

CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
    if (which < 0)
    {
        return;
    }

    cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
}

static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
{
    if ((replacement == NULL) || (string == NULL))
    {
        return false;
    }

    /* replace the name in the replacement */
    if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
    {
        cJSON_free(replacement->string);
    }
    replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
    replacement->type &= ~cJSON_StringIsConst;

    cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);

    return true;
}

CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
{
    replace_item_in_object(object, string, newitem, false);
}

CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
{
    replace_item_in_object(object, string, newitem, true);
}

/* Create basic types: */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_NULL;
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_True;
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_False;
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = b ? cJSON_True : cJSON_False;
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_Number;
        item->valuedouble = num;

        /* use saturation in case of overflow */
        if (num >= INT_MAX)
        {
            item->valueint = INT_MAX;
        }
        else if (num <= INT_MIN)
        {
            item->valueint = INT_MIN;
        }
        else
        {
            item->valueint = (int)num;
        }
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_String;
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL)
    {
        item->type = cJSON_String | cJSON_IsReference;
        item->valuestring = (char*)cast_away_const(string);
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL) {
        item->type = cJSON_Object | cJSON_IsReference;
        item->child = (cJSON*)cast_away_const(child);
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item != NULL) {
        item->type = cJSON_Array | cJSON_IsReference;
        item->child = (cJSON*)cast_away_const(child);
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type = cJSON_Raw;
        item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
        if(!item->valuestring)
        {
            cJSON_Delete(item);
            return NULL;
        }
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if(item)
    {
        item->type=cJSON_Array;
    }

    return item;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item)
    {
        item->type = cJSON_Object;
    }

    return item;
}

/* Create Arrays: */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
{
    size_t i = 0;
    cJSON *n = NULL;
    cJSON *p = NULL;
    cJSON *a = NULL;

    if ((count < 0) || (numbers == NULL))
    {
        return NULL;
    }

    a = cJSON_CreateArray();
    for(i = 0; a && (i < (size_t)count); i++)
    {
        n = cJSON_CreateNumber(numbers[i]);
        if (!n)
        {
            cJSON_Delete(a);
            return NULL;
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
{
    size_t i = 0;
    cJSON *n = NULL;
    cJSON *p = NULL;
    cJSON *a = NULL;

    if ((count < 0) || (numbers == NULL))
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0; a && (i < (size_t)count); i++)
    {
        n = cJSON_CreateNumber((double)numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
            return NULL;
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
{
    size_t i = 0;
    cJSON *n = NULL;
    cJSON *p = NULL;
    cJSON *a = NULL;

    if ((count < 0) || (numbers == NULL))
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for(i = 0;a && (i < (size_t)count); i++)
    {
        n = cJSON_CreateNumber(numbers[i]);
        if(!n)
        {
            cJSON_Delete(a);
            return NULL;
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p, n);
        }
        p = n;
    }

    return a;
}

CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count)
{
    size_t i = 0;
    cJSON *n = NULL;
    cJSON *p = NULL;
    cJSON *a = NULL;

    if ((count < 0) || (strings == NULL))
    {
        return NULL;
    }

    a = cJSON_CreateArray();

    for (i = 0; a && (i < (size_t)count); i++)
    {
        n = cJSON_CreateString(strings[i]);
        if(!n)
        {
            cJSON_Delete(a);
            return NULL;
        }
        if(!i)
        {
            a->child = n;
        }
        else
        {
            suffix_object(p,n);
        }
        p = n;
    }

    return a;
}

/* Duplication */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
{
    cJSON *newitem = NULL;
    cJSON *child = NULL;
    cJSON *next = NULL;
    cJSON *newchild = NULL;

    /* Bail on bad ptr */
    if (!item)
    {
        goto fail;
    }
    /* Create new item */
    newitem = cJSON_New_Item(&global_hooks);
    if (!newitem)
    {
        goto fail;
    }
    /* Copy over all vars */
    newitem->type = item->type & (~cJSON_IsReference);
    newitem->valueint = item->valueint;
    newitem->valuedouble = item->valuedouble;
    if (item->valuestring)
    {
        newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
        if (!newitem->valuestring)
        {
            goto fail;
        }
    }
    if (item->string)
    {
        newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
        if (!newitem->string)
        {
            goto fail;
        }
    }
    /* If non-recursive, then we're done! */
    if (!recurse)
    {
        return newitem;
    }
    /* Walk the ->next chain for the child. */
    child = item->child;
    while (child != NULL)
    {
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */
        if (!newchild)
        {
            goto fail;
        }
        if (next != NULL)
        {
            /* If newitem->child already set, then crosswire ->prev and ->next and move on */
            next->next = newchild;
            newchild->prev = next;
            next = newchild;
        }
        else
        {
            /* Set newitem->child and move to it */
            newitem->child = newchild;
            next = newchild;
        }
        child = child->next;
    }

    return newitem;

fail:
    if (newitem != NULL)
    {
        cJSON_Delete(newitem);
    }

    return NULL;
}

CJSON_PUBLIC(void) cJSON_Minify(char *json)
{
    unsigned char *into = (unsigned char*)json;

    if (json == NULL)
    {
        return;
    }

    while (*json)
    {
        if (*json == ' ')
        {
            json++;
        }
        else if (*json == '\t')
        {
            /* Whitespace characters. */
            json++;
        }
        else if (*json == '\r')
        {
            json++;
        }
        else if (*json=='\n')
        {
            json++;
        }
        else if ((*json == '/') && (json[1] == '/'))
        {
            /* double-slash comments, to end of line. */
            while (*json && (*json != '\n'))
            {
                json++;
            }
        }
        else if ((*json == '/') && (json[1] == '*'))
        {
            /* multiline comments. */
            while (*json && !((*json == '*') && (json[1] == '/')))
            {
                json++;
            }
            json += 2;
        }
        else if (*json == '\"')
        {
            /* string literals, which are \" sensitive. */
            *into++ = (unsigned char)*json++;
            while (*json && (*json != '\"'))
            {
                if (*json == '\\')
                {
                    *into++ = (unsigned char)*json++;
                }
                *into++ = (unsigned char)*json++;
            }
            *into++ = (unsigned char)*json++;
        }
        else
        {
            /* All other characters. */
            *into++ = (unsigned char)*json++;
        }
    }

    /* and null-terminate. */
    *into = '\0';
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Invalid;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_False;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xff) == cJSON_True;
}


CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & (cJSON_True | cJSON_False)) != 0;
}
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_NULL;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Number;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_String;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Array;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Object;
}

CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
{
    if (item == NULL)
    {
        return false;
    }

    return (item->type & 0xFF) == cJSON_Raw;
}

CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
{
    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a))
    {
        return false;
    }

    /* check if type is valid */
    switch (a->type & 0xFF)
    {
        case cJSON_False:
        case cJSON_True:
        case cJSON_NULL:
        case cJSON_Number:
        case cJSON_String:
        case cJSON_Raw:
        case cJSON_Array:
        case cJSON_Object:
            break;

        default:
            return false;
    }

    /* identical objects are equal */
    if (a == b)
    {
        return true;
    }

    switch (a->type & 0xFF)
    {
        /* in these cases and equal type is enough */
        case cJSON_False:
        case cJSON_True:
        case cJSON_NULL:
            return true;

        case cJSON_Number:
            if (a->valuedouble == b->valuedouble)
            {
                return true;
            }
            return false;

        case cJSON_String:
        case cJSON_Raw:
            if ((a->valuestring == NULL) || (b->valuestring == NULL))
            {
                return false;
            }
            if (strcmp(a->valuestring, b->valuestring) == 0)
            {
                return true;
            }

            return false;

        case cJSON_Array:
        {
            cJSON *a_element = a->child;
            cJSON *b_element = b->child;

            for (; (a_element != NULL) && (b_element != NULL);)
            {
                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }

                a_element = a_element->next;
                b_element = b_element->next;
            }

            /* one of the arrays is longer than the other */
            if (a_element != b_element) {
                return false;
            }

            return true;
        }

        case cJSON_Object:
        {
            cJSON *a_element = NULL;
            cJSON *b_element = NULL;
            cJSON_ArrayForEach(a_element, a)
            {
                /* TODO This has O(n^2) runtime, which is horrible! */
                b_element = get_object_item(b, a_element->string, case_sensitive);
                if (b_element == NULL)
                {
                    return false;
                }

                if (!cJSON_Compare(a_element, b_element, case_sensitive))
                {
                    return false;
                }
            }

            /* doing this twice, once on a and b to prevent true comparison if a subset of b
             * TODO: Do this the proper way, this is just a fix for now */
            cJSON_ArrayForEach(b_element, b)
            {
                a_element = get_object_item(a, b_element->string, case_sensitive);
                if (a_element == NULL)
                {
                    return false;
                }

                if (!cJSON_Compare(b_element, a_element, case_sensitive))
                {
                    return false;
                }
            }

            return true;
        }

        default:
            return false;
    }
}

CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
{
    return global_hooks.allocate(size);
}

CJSON_PUBLIC(void) cJSON_free(void *object)
{
    global_hooks.deallocate(object);
}


================================================
FILE: src/cJSON.h
================================================
/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

#ifndef cJSON__h
#define cJSON__h

#ifdef __cplusplus
extern "C"
{
#endif

/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 6

#include <stddef.h>

/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False  (1 << 0)
#define cJSON_True   (1 << 1)
#define cJSON_NULL   (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array  (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw    (1 << 7) /* raw json */

#define cJSON_IsReference 256
#define cJSON_StringIsConst 512

/* The cJSON structure: */
typedef struct cJSON
{
    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *next;
    struct cJSON *prev;
    /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
    struct cJSON *child;

    /* The type of the item, as above. */
    int type;

    /* The item's string, if type==cJSON_String  and type == cJSON_Raw */
    char *valuestring;
    /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
    int valueint;
    /* The item's number, if type==cJSON_Number */
    double valuedouble;

    /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
    char *string;
} cJSON;

typedef struct cJSON_Hooks
{
      void *(*malloc_fn)(size_t sz);
      void (*free_fn)(void *ptr);
} cJSON_Hooks;

typedef int cJSON_bool;

#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__

/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention.  For windows you have 2 define options:

CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol

For *nix builds that support visibility attribute, you can define similar behavior by

setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS

then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does

*/

/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif

#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type)   type __stdcall
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type)   __declspec(dllexport) type __stdcall
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type)   __declspec(dllimport) type __stdcall
#endif
#else /* !WIN32 */
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type)   __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif

/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
 * This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif

/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);

/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);

/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);

/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *c);

/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);

/* Check if the item is a string and return its valuestring */
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);

/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);

/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);

/* Create a string where valuestring references a string so
 * it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/arrray that only references it's elements so
 * they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);

/* These utilities create an Array of count items. */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);

/* Append item to the specified array/object. */
CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
 * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
 * writing to `item->string` */
CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);

/* Remove/Detatch items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);

/* Update array items. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);

/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
 * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);


CJSON_PUBLIC(void) cJSON_Minify(char *json);

/* Helper functions for creating and adding items to an object at the same time.
 * They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);

/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))

/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)

/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);

#ifdef __cplusplus
}
#endif

#endif


================================================
FILE: src/elf2kip.c
================================================
// Copyright 2018 SciresM
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include "cJSON.h"
#include "blz.h"
#include "elf64.h"

typedef struct {
    u32 DstOff;
    u32 DecompSz;
    u32 CompSz;
    u32 Attribute;
} KipSegment;

typedef struct {
    u8  Magic[4];
    u8  Name[0xC];
    u64 ProgramId;
    u32 Version;
    u8  MainThreadPriority;
    u8  DefaultCpuId;
    u8  Unk;
    u8  Flags;
    KipSegment Segments[6];
    u32 Capabilities[0x20];
} KipHeader;

uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
    FILE* fd = fopen(fn, "rb");
    if (fd == NULL)
        return NULL;

    fseek(fd, 0, SEEK_END);
    size_t len = ftell(fd);
    fseek(fd, 0, SEEK_SET);

    uint8_t* buf = malloc(len);
    if (buf == NULL) {
        fclose(fd);
        return NULL;
    }

    size_t rc = fread(buf, 1, len, fd);
    if (rc != len) {
        fclose(fd);
        free(buf);
        return NULL;
    }

    *len_out = len;
    return buf;
}

int cJSON_GetString(const cJSON *obj, const char *field, const char **out) {
  const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
  if (cJSON_IsString(config)) {
    *out = config->valuestring;
    return 1;
  } else {
    fprintf(stderr, "Failed to get %s (field not present).\n", field);
    return 0;
  }
}

int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsNumber(config)) {
        *out = (u8)config->valueint;
        return 1;
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", field);
        return 0;
    }
}

int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsNumber(config)) {
        *out = (u16)config->valueint;
        return 1;
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", field);
        return 0;
    }
}

int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
    if (cJSON_IsNumber(config)) {
        *out = (u16)config->valueint;
        return 1;
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
        return 0;
    }
}

int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsBool(config)) {
        if (cJSON_IsTrue(config)) {
            *out = 1;
        } else if (cJSON_IsFalse(config)) {
            *out = 0;
        } else {
            fprintf(stderr, "Unknown boolean value in %s.\n", field);
            return 0;
        }
        return 1;
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", field);
        return 0;
    }
}

int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsBool(config)) {
        if (cJSON_IsTrue(config)) {
            *out = 1;
        } else if (cJSON_IsFalse(config)) {
            *out = 0;
        } else {
            fprintf(stderr, "Unknown boolean value in %s.\n", field);
            return 0;
        }
        return 1;
    } else {
        *out = 0;
        return 0;
    }
}

int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsString(config) && (config->valuestring != NULL)) {
        char *endptr = NULL;
        *out = strtoull(config->valuestring, &endptr, 16);
        if (config->valuestring == endptr) {
            fprintf(stderr, "Failed to get %s (empty string)\n", field);
            return 0;
        } else if (errno == ERANGE) {
            fprintf(stderr, "Failed to get %s (value out of range)\n", field);
            return 0;
        } else if (errno == EINVAL) {
            fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
            return 0;
        } else if (errno) {
            fprintf(stderr, "Failed to get %s (unknown error)\n", field);
            return 0;
        } else {
            return 1;
        }
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", field);
        return 0;
    }
}

int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
    if (cJSON_IsString(config) && (config->valuestring != NULL)) {
        char *endptr = NULL;
        *out = strtoull(config->valuestring, &endptr, 16);
        if (config->valuestring == endptr) {
            fprintf(stderr, "Failed to get %s (empty string)\n", config->string);
            return 0;
        } else if (errno == ERANGE) {
            fprintf(stderr, "Failed to get %s (value out of range)\n", config->string);
            return 0;
        } else if (errno == EINVAL) {
            fprintf(stderr, "Failed to get %s (not base16 string)\n", config->string);
            return 0;
        } else if (errno) {
            fprintf(stderr, "Failed to get %s (unknown error)\n", config->string);
            return 0;
        } else {
            return 1;
        }
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", config->string);
        return 0;
    }
}

int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
    const cJSON *config = cJSON_GetObjectItemCaseSensitive(obj, field);
    if (cJSON_IsString(config) && (config->valuestring != NULL)) {
        char *endptr = NULL;
        *out = strtoul(config->valuestring, &endptr, 16);
        if (config->valuestring == endptr) {
            fprintf(stderr, "Failed to get %s (empty string)\n", field);
            return 0;
        } else if (errno == ERANGE) {
            fprintf(stderr, "Failed to get %s (value out of range)\n", field);
            return 0;
        } else if (errno == EINVAL) {
            fprintf(stderr, "Failed to get %s (not base16 string)\n", field);
            return 0;
        } else if (errno) {
            fprintf(stderr, "Failed to get %s (unknown error)\n", field);
            return 0;
        } else {
            return 1;
        }
    } else {
        fprintf(stderr, "Failed to get %s (field not present).\n", field);
        return 0;
    }
}

int ParseKipConfiguration(const char *json, KipHeader *kip_hdr) {
    const cJSON *capability = NULL;
    const cJSON *capabilities = NULL;
    int status = 0;
    cJSON *npdm_json = cJSON_Parse(json);
    if (npdm_json == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL) {
            fprintf(stderr, "JSON Parse Error: %s\n", error_ptr);
        }
        status = 0;
        goto PARSE_CAPS_END;
    }

    /* Parse name. */
    const cJSON *title_name = cJSON_GetObjectItemCaseSensitive(npdm_json, "name");
    if (cJSON_IsString(title_name) && (title_name->valuestring != NULL)) {
        strncpy(kip_hdr->Name, title_name->valuestring, sizeof(kip_hdr->Name) - 1);
    } else {
        fprintf(stderr, "Failed to get title name (name field not present).\n");
        status = 0;
        goto PARSE_CAPS_END;
    }

    /* Parse program_id (or deprecated title_id). */
    if (!cJSON_GetU64(npdm_json, "program_id", &kip_hdr->ProgramId) && !cJSON_GetU64(npdm_json, "title_id", &kip_hdr->ProgramId)) {
        status = 0;
        goto PARSE_CAPS_END;
    }

    /* Parse use secure memory. */
    /* This field is optional, and defaults to true (set before this function is called). */
    int use_secure_memory = 1;
    if (cJSON_GetBooleanOptional(npdm_json, "use_secure_memory", &use_secure_memory)) {
        if (use_secure_memory) {
            kip_hdr->Flags |= 0x20;
        } else {
            kip_hdr->Flags &= ~0x20;
        }
    }

    /* Parse immortality. */
    /* This field is optional, and defaults to true (set before this function is called). */
    int immortal = 1;
    if (cJSON_GetBooleanOptional(npdm_json, "immortal", &immortal)) {
        if (immortal) {
            kip_hdr->Flags |= 0x40;
        } else {
            kip_hdr->Flags &= ~0x40;
        }
    }

    /* Parse main_thread_stack_size. */
    u64 stack_size = 0;
    if (!cJSON_GetU64(npdm_json, "main_thread_stack_size", &stack_size)) {
        status = 0;
        goto PARSE_CAPS_END;
    }
    if (stack_size >> 32) {
        fprintf(stderr, "Error: Main thread stack size must be a u32!\n");
        status = 0;
        goto PARSE_CAPS_END;
    }
    kip_hdr->Segments[1].Attribute = (u32)(stack_size & 0xFFFFFFFF);

    /* Parse various config. */
    if (!cJSON_GetU8(npdm_json, "main_thread_priority", &kip_hdr->MainThreadPriority)) {
        status = 0;
        goto PARSE_CAPS_END;
    }
    if (!cJSON_GetU8(npdm_json, "default_cpu_id", &kip_hdr->DefaultCpuId)) {
        status = 0;
        goto PARSE_CAPS_END;
    }
    if (!cJSON_GetU32(npdm_json, "version", &kip_hdr->Version) && !cJSON_GetU32(npdm_json, "process_category", &kip_hdr->Version)) { // optional
        kip_hdr->Version = 1;
    }

    /* Parse capabilities. */
    capabilities = cJSON_GetObjectItemCaseSensitive(npdm_json, "kernel_capabilities");
    if (!(cJSON_IsArray(capabilities) || cJSON_IsObject(capabilities))) {
        fprintf(stderr, "Kernel Capabilities must be an array!\n");
        status = 0;
        goto PARSE_CAPS_END;
    }

    int kac_obj = 0;
    if (cJSON_IsObject(capabilities)) {
        kac_obj = 1;
        fprintf(stderr, "Using deprecated kernel_capabilities format. Please turn it into an array.\n");
    }

    u32 cur_cap = 0;
    u32 desc;
    cJSON_ArrayForEach(capability, capabilities) {
        desc = 0;
        const char *type_str;
        const cJSON *value;

        if (kac_obj) {
            type_str = capability->string;
            value = capability;
        } else {
            if (!cJSON_GetString(capability, "type", &type_str)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            value = cJSON_GetObjectItemCaseSensitive(capability, "value");
        }


        if (!strcmp(type_str, "kernel_flags")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_IsObject(value)) {
                fprintf(stderr, "Kernel Flags Capability value must be object!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u8 highest_prio = 0, lowest_prio = 0, lowest_cpu = 0, highest_cpu = 0;
            if (!cJSON_GetU8(value, "highest_thread_priority", &highest_prio) ||
                !cJSON_GetU8(value, "lowest_thread_priority", &lowest_prio) ||
                !cJSON_GetU8(value, "highest_cpu_id", &highest_cpu) ||
                !cJSON_GetU8(value, "lowest_cpu_id", &lowest_cpu)) {
                status = 0;
                goto PARSE_CAPS_END;
            }

            u8 real_highest_prio = (lowest_prio < highest_prio) ? lowest_prio : highest_prio;
            u8 real_lowest_prio  = (lowest_prio > highest_prio) ? lowest_prio : highest_prio;

            desc = highest_cpu;
            desc <<= 8;
            desc |= lowest_cpu;
            desc <<= 6;
            desc |= (real_highest_prio & 0x3F);
            desc <<= 6;
            desc |= (real_lowest_prio & 0x3F);
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 4) | (0x0007));
        } else if (!strcmp(type_str, "syscalls")) {
            if (!cJSON_IsObject(value)) {
                fprintf(stderr, "Syscalls Capability value must be object!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u32 num_descriptors;
            u32 descriptors[8] = {0}; /* alignup(0xC0/0x18); */
            char field_name[8] = {0};
            const cJSON *cur_syscall = NULL;
            u64 syscall_value = 0;
            cJSON_ArrayForEach(cur_syscall, value) {
                if (cJSON_IsNumber(cur_syscall)) {
                    syscall_value = (u64)cur_syscall->valueint;
                } else if (!cJSON_IsString(cur_syscall) || !cJSON_GetU64(value, cur_syscall->string, &syscall_value)) {
                    fprintf(stderr, "Error: Syscall entries must be integers or hex strings.\n");
                    status = 0;
                    goto PARSE_CAPS_END;
                }

                if (syscall_value >= 0xC0) {
                    fprintf(stderr, "Error: All syscall entries must be numbers in [0, 0xBF]\n");
                    status = 0;
                    goto PARSE_CAPS_END;
                }
                descriptors[syscall_value / 0x18] |= (1UL << (syscall_value % 0x18));
            }
            for (unsigned int i = 0; i < 8; i++) {
                if (descriptors[i]) {
                    if (cur_cap + 1 > 0x20) {
                        fprintf(stderr, "Error: Too many capabilities!\n");
                        status = 0;
                        goto PARSE_CAPS_END;
                    }
                    desc = descriptors[i] | (i << 24);
                    kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 5) | (0x000F));
                }
            }
        } else if (!strcmp(type_str, "map")) {
            if (cur_cap + 2 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_IsObject(value)) {
                fprintf(stderr, "Map Capability value must be object!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u64 map_address = 0;
            u64 map_size = 0;
            int is_ro;
            int is_io;
            if (!cJSON_GetU64(value, "address", &map_address) ||
                !cJSON_GetU64(value, "size", &map_size) ||
                !cJSON_GetBoolean(value, "is_ro", &is_ro) ||
                !cJSON_GetBoolean(value, "is_io", &is_io)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            desc = (u32)((map_address >> 12) & 0x00FFFFFFULL);
            desc |= is_ro << 24;
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));

            desc = (u32)((map_size >> 12) & 0x000FFFFFULL);
            desc |= (u32)(((map_address >> 36) & 0xFULL) << 20);
            is_io ^= 1;
            desc |= is_io << 24;
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 7) | (0x003F));
        } else if (!strcmp(type_str, "map_page")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u64 page_address = 0;
            if (!cJSON_GetU64FromObjectValue(value, &page_address)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            desc = (u32)((page_address >> 12) & 0x00FFFFFFULL);
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 8) | (0x007F));
        } else if (!strcmp(type_str, "map_region")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_IsArray(value)) {
                fprintf(stderr, "Map Region capability value must be array!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u8 regions[3] = {0};
            int is_ro[3] = {0};
            const cJSON *cur_region = NULL;
            int index = 0;
            cJSON_ArrayForEach(cur_region, value) {
                if (index >= 3) {
                    fprintf(stderr, "Too many region descriptors!\n");
                    status = 0;
                    goto PARSE_CAPS_END;
                }
                if (!cJSON_IsObject(cur_region)) {
                    fprintf(stderr, "Region descriptor value must be object!\n");
                    status = 0;
                    goto PARSE_CAPS_END;
                }

                if (!cJSON_GetU8(cur_region, "region_type", &regions[index]) ||
                    !cJSON_GetBoolean(cur_region, "is_ro", &is_ro[index])) {
                    status = 0;
                    goto PARSE_CAPS_END;
                }

                index++;
            }

            u32 capability = 0x3FF;
            for (int i = 0; i < 3; ++i) {
                capability |= ((regions[i] & 0x3F) | ((is_ro[i] & 1) << 6)) << (11 + 7 * i);
            }
            kip_hdr->Capabilities[cur_cap++] = capability;
        } else if (!strcmp(type_str, "irq_pair")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) != 2) {
                fprintf(stderr, "Error: IRQ Pairs must have size 2 array value.\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            const cJSON *irq = NULL;
            int desc_idx = 0;
            cJSON_ArrayForEach(irq, value) {
                if (cJSON_IsNull(irq)) {
                    desc |= 0x3FF << desc_idx;
                } else if (cJSON_IsNumber(irq)) {
                    desc |= (((u16)(irq->valueint)) & 0x3FF) << desc_idx;
                } else {
                    fprintf(stderr, "Failed to parse IRQ value.\n");
                    status = 0;
                    goto PARSE_CAPS_END;
                }
                desc_idx += 10;
            }
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 12) | (0x07FF));
        } else if (!strcmp(type_str, "application_type")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            desc &= 7;
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 14) | (0x1FFF));
        } else if (!strcmp(type_str, "min_kernel_version")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            u64 kern_ver = 0;
            if (cJSON_IsNumber(value)) {
                kern_ver = (u64)value->valueint;
            } else if (!cJSON_IsString(value) || !cJSON_GetU64FromObjectValue(value, &kern_ver)) {
                fprintf(stderr, "Error: Kernel version must be integer or hex strings.\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            desc = (kern_ver) & 0xFFFF;
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 15) | (0x3FFF));
        } else if (!strcmp(type_str, "handle_table_size")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_GetU16FromObjectValue(value, (u16 *)&desc)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 16) | (0x7FFF));
        } else if (!strcmp(type_str, "debug_flags")) {
            if (cur_cap + 1 > 0x20) {
                fprintf(stderr, "Error: Too many capabilities!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_IsObject(value)) {
                fprintf(stderr, "Debug Flag Capability value must be object!\n");
                status = 0;
                goto PARSE_CAPS_END;
            }
            int allow_debug = 0;
            int force_debug = 0;
            int force_debug_prod = 0;
            if (!cJSON_GetBoolean(value, "allow_debug", &allow_debug)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_GetBoolean(value, "force_debug", &force_debug)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            if (!cJSON_GetBoolean(value, "force_debug_prod", &force_debug_prod)) {
                status = 0;
                goto PARSE_CAPS_END;
            }
            desc = (allow_debug & 1) | ((force_debug_prod & 1) << 1) | ((force_debug & 1) << 2);
            kip_hdr->Capabilities[cur_cap++] = (u32)((desc << 17) | (0xFFFF));
        } else {
            fprintf(stderr, "Error: unknown capability %s\n", type_str);
            status = 0;
            goto PARSE_CAPS_END;
        }
    }

    for (u32 i = cur_cap; i < 0x20; i++) {
        kip_hdr->Capabilities[i] = 0xFFFFFFFF;
    }

    status = 1;
    PARSE_CAPS_END:
    cJSON_Delete(npdm_json);
    return status;
}

int main(int argc, char* argv[]) {
    if (argc != 4) {
        fprintf(stderr, "%s <elf-file> <json-file> <kip-file>\n", argv[0]);
        return EXIT_FAILURE;
    }

    KipHeader kip_hdr = {0};
    memcpy(kip_hdr.Magic, "KIP1", 4);
    kip_hdr.Flags = 0x7F;

    if (sizeof(KipHeader) != 0x100) {
        fprintf(stderr, "Bad compile environment!\n");
        return EXIT_FAILURE;
    }

    size_t json_len;
    uint8_t* json = ReadEntireFile(argv[2], &json_len);
    if (json == NULL) {
        fprintf(stderr, "Failed to read descriptor json!\n");
        return EXIT_FAILURE;
    }

    if (!ParseKipConfiguration(json, &kip_hdr)) {
        fprintf(stderr, "Failed to parse kip configuration!\n");
        return EXIT_FAILURE;
    }

    size_t elf_len;
    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
    if (elf == NULL) {
        fprintf(stderr, "Failed to open input!\n");
        return EXIT_FAILURE;
    }

    if (elf_len < sizeof(Elf64_Ehdr)) {
        fprintf(stderr, "Input file doesn't fit ELF header!\n");
        return EXIT_FAILURE;
    }

    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
    if (hdr->e_machine != EM_AARCH64) {
        fprintf(stderr, "Invalid ELF: expected AArch64!\n");
        return EXIT_FAILURE;
    }

    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);

    if (ph_end < hdr->e_phoff || ph_end > elf_len) {
        fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
        return EXIT_FAILURE;
    }

    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
    size_t i, j = 0;
    size_t file_off = 0;
    size_t dst_off = 0;
    size_t tmpsize;

    uint8_t* buf[3];
    uint8_t* cmp[3];
    size_t FileOffsets[3];

    for (i=0; i<4; i++) {
        Elf64_Phdr* phdr = NULL;
        while (j < hdr->e_phnum) {
            Elf64_Phdr* cur = &phdrs[j];
            if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
            if (cur->p_type == PT_LOAD || i == 3) {
                phdr = cur;
                break;
            }
        }

        if (phdr == NULL) {
            fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
            return EXIT_FAILURE;
        }


        kip_hdr.Segments[i].DstOff = dst_off;

        // .bss is special
        if (i == 3) {
            tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
            if ( phdr->p_memsz > tmpsize) {
                kip_hdr.Segments[i].DecompSz = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
            } else {
                kip_hdr.Segments[i].DecompSz = 0;
            }
            kip_hdr.Segments[i].CompSz = 0;
            break;
        }

        FileOffsets[i] = file_off;
        kip_hdr.Segments[i].DecompSz = phdr->p_filesz;
        buf[i] = malloc(kip_hdr.Segments[i].DecompSz);

        if (buf[i] == NULL) {
            fprintf(stderr, "Out of memory!\n");
            return EXIT_FAILURE;
        }

        memset(buf[i], 0, kip_hdr.Segments[i].DecompSz);

        memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);
        cmp[i] = BLZ_Code(buf[i], phdr->p_filesz, &kip_hdr.Segments[i].CompSz, BLZ_BEST);

        file_off += kip_hdr.Segments[i].CompSz;
        dst_off += kip_hdr.Segments[i].DecompSz;
        dst_off = (dst_off + 0xFFF) & ~0xFFF;
    }

    FILE* out = fopen(argv[3], "wb");

    if (out == NULL) {
        fprintf(stderr, "Failed to open output file!\n");
        return EXIT_FAILURE;
    }

    // TODO check retvals

    for (i=0; i<3; i++)
    {
        fseek(out, sizeof(kip_hdr) + FileOffsets[i], SEEK_SET);
        fwrite(cmp[i], kip_hdr.Segments[i].CompSz, 1, out);
    }

    fseek(out, 0, SEEK_SET);
    fwrite(&kip_hdr, sizeof(kip_hdr), 1, out);

    fclose(out);
    return EXIT_SUCCESS;
}


================================================
FILE: src/elf2nro.c
================================================
// Copyright 2017 plutoo
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <lz4.h>
#include "sha256.h"
#include "elf64.h"
#include "romfs.h"

typedef struct {
    u32 FileOff;
    u32 Size;
} NsoSegment;

typedef struct {
    u32 unused;
    u32 modOffset;
    u8 Padding[8];
} NroStart;

typedef struct {
    u8  Magic[4];
    u32 version;
    u32 size;
    u32 flags;
    NsoSegment Segments[3];
    u32 bssSize;
    u32 Unk3;
    u8  BuildId[0x20];
    u8  Padding[0x20];
} NroHeader;

typedef struct {
    u64 offset;
    u64 size;
} AssetSection;

typedef struct {
    u8  magic[4];
    u32 version;
    AssetSection icon;
    AssetSection nacp;
    AssetSection romfs;
} AssetHeader;

uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
    FILE* fd = fopen(fn, "rb");
    if (fd == NULL)
        return NULL;

    fseek(fd, 0, SEEK_END);
    size_t len = ftell(fd);
    fseek(fd, 0, SEEK_SET);

    uint8_t* buf = malloc(len);
    if (buf == NULL) {
        fclose(fd);
        return NULL;
    }

    size_t rc = fread(buf, 1, len, fd);
    if (rc != len) {
        fclose(fd);
        free(buf);
        return NULL;
    }

    *len_out = len;
    return buf;
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        fprintf(stderr, "%s <elf-file> <nro-file> [options]\n\n", argv[0]);
        fprintf(stderr, "Options:\n");
        fprintf(stderr, "--icon=<iconpath> Embeds icon into the output file.\n");
        fprintf(stderr, "--nacp=<control.nacp> Embeds control.nacp into the output file.\n");
        fprintf(stderr, "--romfs=<image> Embeds RomFS into the output file.\n");
        fprintf(stderr, "--romfsdir=<directory> Builds and embeds RomFS into the output file.\n");
        fprintf(stderr, "--alignedheader Sets the \"AlignedHeader\" flag in the output file.\n");
        return EXIT_FAILURE;
    }

    NroStart nro_start;
    memset(&nro_start, 0, sizeof(nro_start));

    NroHeader nro_hdr;
    memset(&nro_hdr, 0, sizeof(nro_hdr));
    memcpy(nro_hdr.Magic, "NRO0", 4);

    if (sizeof(NroHeader) != 0x70) {
        fprintf(stderr, "Bad compile environment!\n");
        return EXIT_FAILURE;
    }

    size_t elf_len;
    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
    if (elf == NULL) {
        fprintf(stderr, "Failed to open input!\n");
        return EXIT_FAILURE;
    }

    int argi;
    char* icon_path = NULL, *nacp_path = NULL, *romfs_path = NULL, *romfs_dir_path = NULL;
    u32 aligned_header = 0;
    for (argi=3; argi<argc; argi++) {
        if (strncmp(argv[argi], "--icon=", 7)==0) icon_path = &argv[argi][7];
        if (strncmp(argv[argi], "--nacp=", 7)==0) nacp_path = &argv[argi][7];
        if (strncmp(argv[argi], "--romfs=", 8)==0) romfs_path = &argv[argi][8];
        if (strncmp(argv[argi], "--romfsdir=", 11)==0) romfs_dir_path = &argv[argi][11];
        if (strncmp(argv[argi], "--alignedheader", 15)==0) aligned_header = 1;
    }

    if (romfs_dir_path != NULL && romfs_path != NULL) {
        fprintf(stderr, "Cannot have a RomFS and a RomFS Directory at the same time!\n");
        return EXIT_FAILURE;
    }

    if (elf_len < sizeof(Elf64_Ehdr)) {
        fprintf(stderr, "Input file doesn't fit ELF header!\n");
        return EXIT_FAILURE;
    }

    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
    if (hdr->e_machine != EM_AARCH64) {
        fprintf(stderr, "Invalid ELF: expected AArch64!\n");
        return EXIT_FAILURE;
    }

    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);

    if (ph_end < hdr->e_phoff || ph_end > elf_len) {
        fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
        return EXIT_FAILURE;
    }

    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
    size_t i, j = 0;
    size_t file_off = 0;
    size_t tmpsize;

    uint8_t* buf[3];

    for (i=0; i<4; i++) {
        Elf64_Phdr* phdr = NULL;
        while (j < hdr->e_phnum) {
            Elf64_Phdr* cur = &phdrs[j];
            if (i < 2 || (i==2 && cur->p_type != PT_LOAD)) j++;
            if (cur->p_type == PT_LOAD || i == 3) {
                phdr = cur;
                break;
            }
        }

        if (phdr == NULL) {
            fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs and a bss!\n");
            return EXIT_FAILURE;
        }

        // .bss is special
        if (i == 3) {
            tmpsize = (phdr->p_filesz + 0xFFF) & ~0xFFF;
            if ( phdr->p_memsz > tmpsize)
                nro_hdr.bssSize = ((phdr->p_memsz - tmpsize) + 0xFFF) & ~0xFFF;
            else
                nro_hdr.bssSize = 0;
            break;
        }

        nro_hdr.Segments[i].FileOff = phdr->p_vaddr;
        nro_hdr.Segments[i].Size = (phdr->p_filesz + 0xFFF) & ~0xFFF;
        buf[i] = malloc(nro_hdr.Segments[i].Size);
        memset(buf[i], 0, nro_hdr.Segments[i].Size);

        if (buf[i] == NULL) {
            fprintf(stderr, "Out of memory!\n");
            return EXIT_FAILURE;
        }

        memcpy(buf[i], &elf[phdr->p_offset], phdr->p_filesz);

        file_off += nro_hdr.Segments[i].Size;
        file_off = (file_off + 0xFFF) & ~0xFFF;
    }

    /* Iterate over sections to find build id. */
    size_t cur_sect_hdr_ofs = hdr->e_shoff;
    for (unsigned int i = 0; i < hdr->e_shnum; i++) {
        Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
        if (cur_shdr->sh_type == SHT_NOTE) {
            Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
            u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
            u8 *note_desc = note_name + note_hdr->n_namesz;
            if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
                size_t build_id_size = note_hdr->n_descsz;
                if (build_id_size > 0x20) {
                    build_id_size = 0x20;
                }
                memcpy(nro_hdr.BuildId, note_desc, build_id_size);
            }
        }
        cur_sect_hdr_ofs += hdr->e_shentsize;
    }

    FILE* out = fopen(argv[2], "wb");

    if (out == NULL) {
        fprintf(stderr, "Failed to open output file!\n");
        return EXIT_FAILURE;
    }

    nro_hdr.size = file_off;

    nro_hdr.version = 0;
    nro_hdr.flags   = (aligned_header << 0);

    // TODO check retvals

    for (i=0; i<3; i++)
    {
        fseek(out, nro_hdr.Segments[i].FileOff, SEEK_SET);
        fwrite(buf[i], nro_hdr.Segments[i].Size, 1, out);
    }

    fseek(out, sizeof(nro_start), SEEK_SET);
    fwrite(&nro_hdr, sizeof(nro_hdr), 1, out);

    if (icon_path==NULL && nacp_path==NULL && romfs_path==NULL) {
        fclose(out);
        return EXIT_SUCCESS;
    }

    AssetHeader asset_hdr;
    memset(&asset_hdr, 0, sizeof(asset_hdr));
    memcpy(asset_hdr.magic, "ASET", 4);
    asset_hdr.version = 0;

    fseek(out, file_off, SEEK_SET);

    uint8_t* icon = NULL, *nacp = NULL, *romfs = NULL;
    size_t icon_len = 0, nacp_len = 0, romfs_len = 0;
    size_t tmp_off = sizeof(asset_hdr);

    if (icon_path) {
        icon = ReadEntireFile(icon_path, &icon_len);
        if (icon == NULL) {
            fprintf(stderr, "Failed to open input icon!\n");
            return EXIT_FAILURE;
        }

        asset_hdr.icon.offset = tmp_off;
        asset_hdr.icon.size = icon_len;
        tmp_off+= icon_len;
    }

    if (nacp_path) {
        nacp = ReadEntireFile(nacp_path, &nacp_len);
        if (nacp == NULL) {
            fprintf(stderr, "Failed to open input nacp!\n");
            return EXIT_FAILURE;
        }

        asset_hdr.nacp.offset = tmp_off;
        asset_hdr.nacp.size = nacp_len;
        tmp_off+= nacp_len;
    }

    if (romfs_path) {
        romfs = ReadEntireFile(romfs_path, &romfs_len);
        if (romfs == NULL) {
            fprintf(stderr, "Failed to open input romfs!\n");
            return EXIT_FAILURE;
        }

        asset_hdr.romfs.offset = tmp_off;
        asset_hdr.romfs.size = romfs_len;
        tmp_off+= romfs_len;

    } else if (romfs_dir_path) {
        asset_hdr.romfs.offset = tmp_off;
        asset_hdr.romfs.size = build_romfs_by_path_into_file(romfs_dir_path, out, file_off + tmp_off);
        tmp_off+= asset_hdr.romfs.size;
        fseek(out, file_off, SEEK_SET);
    }

    fwrite(&asset_hdr, sizeof(asset_hdr), 1, out);

    if (icon_path) {
        fseek(out, file_off + asset_hdr.icon.offset, SEEK_SET);
        fwrite(icon, icon_len, 1, out);
    }

    if (nacp_path) {
        fseek(out, file_off + asset_hdr.nacp.offset, SEEK_SET);
        fwrite(nacp, nacp_len, 1, out);
    }

    if (romfs_path) {
        fseek(out, file_off + asset_hdr.romfs.offset, SEEK_SET);
        fwrite(romfs, romfs_len, 1, out);
    }

    fclose(out);

    return EXIT_SUCCESS;
}


================================================
FILE: src/elf2nso.c
================================================
// Copyright 2017 plutoo
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <lz4.h>
#include "sha256.h"
#include "elf64.h"

typedef uint64_t u64;
typedef uint32_t u32;
typedef uint8_t u8;

typedef struct {
    u32 FileOff;
    u32 DstOff;
    u32 DecompSz;
    u32 AlignOrTotalSz;
} NsoSegment;

typedef u8 Sha2Hash[0x20];

typedef struct {
    u8  Magic[4];
    u32 Unk1;
    u32 Unk2;
    u32 Unk3;
    NsoSegment Segments[3];
    u8  BuildId[0x20];
    u32 CompSz[3];
    u8  Padding[0x24];
    u64 Unk4;
    u64 Unk5;
    Sha2Hash Hashes[3];    
} NsoHeader;

uint8_t* ReadEntireFile(const char* fn, size_t* len_out) {
    FILE* fd = fopen(fn, "rb");
    if (fd == NULL)
        return NULL;

    fseek(fd, 0, SEEK_END);
    size_t len = ftell(fd);
    fseek(fd, 0, SEEK_SET);

    uint8_t* buf = malloc(len);
    if (buf == NULL) {
        fclose(fd);
        return NULL;
    }

    size_t rc = fread(buf, 1, len, fd);
    if (rc != len) {
        fclose(fd);
        free(buf);
        return NULL;
    }

    *len_out = len;
    return buf;
}

int main(int argc, char* argv[]) {
    if (argc != 3) {
        fprintf(stderr, "%s <elf-file> <nso-file>\n", argv[0]);
        return EXIT_FAILURE;
    }

    NsoHeader nso_hdr;
    memset(&nso_hdr, 0, sizeof(nso_hdr));
    memcpy(nso_hdr.Magic, "NSO0", 4);
    nso_hdr.Unk3 = 0x3f;

    if (sizeof(NsoHeader) != 0x100) {
        fprintf(stderr, "Bad compile environment!\n");
        return EXIT_FAILURE;
    }

    size_t elf_len;
    uint8_t* elf = ReadEntireFile(argv[1], &elf_len);
    if (elf == NULL) {
        fprintf(stderr, "Failed to open input!\n");
        return EXIT_FAILURE;
    }

    if (elf_len < sizeof(Elf64_Ehdr)) {
        fprintf(stderr, "Input file doesn't fit ELF header!\n");
        return EXIT_FAILURE;
    }

    Elf64_Ehdr* hdr = (Elf64_Ehdr*) elf;
    if (hdr->e_machine != EM_AARCH64) {
        fprintf(stderr, "Invalid ELF: expected AArch64!\n");
        return EXIT_FAILURE;
    }

    Elf64_Off ph_end = hdr->e_phoff + hdr->e_phnum * sizeof(Elf64_Phdr);

    if (ph_end < hdr->e_phoff || ph_end > elf_len) {
        fprintf(stderr, "Invalid ELF: phdrs outside file!\n");
        return EXIT_FAILURE;
    }

    Elf64_Phdr* phdrs = (Elf64_Phdr*) &elf[hdr->e_phoff];
    size_t i, j = 0;
    size_t file_off = sizeof(NsoHeader);

    uint8_t* comp_buf[3];
    int comp_sz[3];

    for (i=0; i<3; i++) {
        Elf64_Phdr* phdr = NULL;
        while (j < hdr->e_phnum) {
            Elf64_Phdr* cur = &phdrs[j++];
            if (cur->p_type == PT_LOAD) {
                phdr = cur;
                break;
            }
        }

        if (phdr == NULL) {
            fprintf(stderr, "Invalid ELF: expected 3 loadable phdrs!\n");
            return EXIT_FAILURE;
        }

        nso_hdr.Segments[i].FileOff = file_off;
        nso_hdr.Segments[i].DstOff = phdr->p_vaddr;
        nso_hdr.Segments[i].DecompSz = phdr->p_filesz;

        // for .data segment this field contains bss size
        if (i == 2)
            nso_hdr.Segments[i].AlignOrTotalSz = phdr->p_memsz - phdr->p_filesz;
        else
            nso_hdr.Segments[i].AlignOrTotalSz = 1;

        SHA256_CTX ctx;
        sha256_init(&ctx);
        sha256_update(&ctx, &elf[phdr->p_offset], phdr->p_filesz);
        sha256_final(&ctx, (u8*) &nso_hdr.Hashes[i]);

        size_t comp_max = LZ4_compressBound(phdr->p_filesz);
        comp_buf[i] = malloc(comp_max);

        if (comp_buf[i] == NULL) {
            fprintf(stderr, "Compressing: Out of memory!\n");
            return EXIT_FAILURE;
        }

        // TODO check p_offset
        comp_sz[i] = LZ4_compress_default(&elf[phdr->p_offset], comp_buf[i], phdr->p_filesz, comp_max);

        if (comp_sz[i] < 0) {
            fprintf(stderr, "Failed to compress!\n");
            return EXIT_FAILURE;
        }

        nso_hdr.CompSz[i] = comp_sz[i];
        file_off += comp_sz[i];
    }
    
    /* Iterate over sections to find build id. */
    size_t cur_sect_hdr_ofs = hdr->e_shoff;
    for (unsigned int i = 0; i < hdr->e_shnum; i++) {
        Elf64_Shdr *cur_shdr = (Elf64_Shdr *)(elf + cur_sect_hdr_ofs);
        if (cur_shdr->sh_type == SHT_NOTE) {
            Elf64_Nhdr *note_hdr = (Elf64_Nhdr *)(elf + cur_shdr->sh_offset);
            u8 *note_name = (u8 *)((uintptr_t)note_hdr + sizeof(Elf64_Nhdr));
            u8 *note_desc = note_name + note_hdr->n_namesz;
            if (note_hdr->n_type == NT_GNU_BUILD_ID && note_hdr->n_namesz == 4 && memcmp(note_name, "GNU\x00", 4) == 0) {
                size_t build_id_size = note_hdr->n_descsz;
                if (build_id_size > 0x20) {
                    build_id_size = 0x20;
                }
                memcpy(nso_hdr.BuildId, note_desc, build_id_size);
            }
        }
        cur_sect_hdr_ofs += hdr->e_shentsize;
    }

    FILE* out = fopen(argv[2], "wb");

    if (out == NULL) {
        fprintf(stderr, "Failed to open output file!\n");
        return EXIT_FAILURE;
    }

    // TODO check retvals
    fwrite(&nso_hdr, sizeof(nso_hdr), 1, out);

    for (i=0; i<3; i++)
        fwrite(comp_buf[i], comp_sz[i], 1, out);

    return EXIT_SUCCESS;
}


================================================
FILE: src/elf64.h
================================================
/*-
 * Copyright (c) 1996-1998 John D. Polstra.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: head/sys/sys/elf64.h 186667 2009-01-01 02:08:56Z obrien $
 */

#ifndef _SYS_ELF64_H_
#define _SYS_ELF64_H_ 1

#include "elf_common.h"

/*
 * ELF definitions common to all 64-bit architectures.
 */

typedef uint64_t	Elf64_Addr;
typedef uint16_t	Elf64_Half;
typedef uint64_t	Elf64_Off;
typedef int32_t		Elf64_Sword;
typedef int64_t		Elf64_Sxword;
typedef uint32_t	Elf64_Word;
typedef uint64_t	Elf64_Lword;
typedef uint64_t	Elf64_Xword;

/*
 * Types of dynamic symbol hash table bucket and chain elements.
 *
 * This is inconsistent among 64 bit architectures, so a machine dependent
 * typedef is required.
 */

typedef Elf64_Word	Elf64_Hashelt;

/* Non-standard class-dependent datatype used for abstraction. */
typedef Elf64_Xword	Elf64_Size;
typedef Elf64_Sxword	Elf64_Ssize;

/*
 * ELF header.
 */

typedef struct {
	unsigned char	e_ident[EI_NIDENT];	/* File identification. */
	Elf64_Half	e_type;		/* File type. */
	Elf64_Half	e_machine;	/* Machine architecture. */
	Elf64_Word	e_version;	/* ELF format version. */
	Elf64_Addr	e_entry;	/* Entry point. */
	Elf64_Off	e_phoff;	/* Program header file offset. */
	Elf64_Off	e_shoff;	/* Section header file offset. */
	Elf64_Word	e_flags;	/* Architecture-specific flags. */
	Elf64_Half	e_ehsize;	/* Size of ELF header in bytes. */
	Elf64_Half	e_phentsize;	/* Size of program header entry. */
	Elf64_Half	e_phnum;	/* Number of program header entries. */
	Elf64_Half	e_shentsize;	/* Size of section header entry. */
	Elf64_Half	e_shnum;	/* Number of section header entries. */
	Elf64_Half	e_shstrndx;	/* Section name strings section. */
} Elf64_Ehdr;

/*
 * Section header.
 */

typedef struct {
	Elf64_Word	sh_name;	/* Section name (index into the
					   section header string table). */
	Elf64_Word	sh_type;	/* Section type. */
	Elf64_Xword	sh_flags;	/* Section flags. */
	Elf64_Addr	sh_addr;	/* Address in memory image. */
	Elf64_Off	sh_offset;	/* Offset in file. */
	Elf64_Xword	sh_size;	/* Size in bytes. */
	Elf64_Word	sh_link;	/* Index of a related section. */
	Elf64_Word	sh_info;	/* Depends on section type. */
	Elf64_Xword	sh_addralign;	/* Alignment in bytes. */
	Elf64_Xword	sh_entsize;	/* Size of each entry in section. */
} Elf64_Shdr;

/*
 * Program header.
 */

typedef struct {
	Elf64_Word	p_type;		/* Entry type. */
	Elf64_Word	p_flags;	/* Access permission flags. */
	Elf64_Off	p_offset;	/* File offset of contents. */
	Elf64_Addr	p_vaddr;	/* Virtual address in memory image. */
	Elf64_Addr	p_paddr;	/* Physical address (not used). */
	Elf64_Xword	p_filesz;	/* Size of contents in file. */
	Elf64_Xword	p_memsz;	/* Size of contents in memory. */
	Elf64_Xword	p_align;	/* Alignment in memory and file. */
} Elf64_Phdr;

/*
 * Dynamic structure.  The ".dynamic" section contains an array of them.
 */

typedef struct {
	Elf64_Sxword	d_tag;		/* Entry type. */
	union {
		Elf64_Xword	d_val;	/* Integer value. */
		Elf64_Addr	d_ptr;	/* Address value. */
	} d_un;
} Elf64_Dyn;

/*
 * Relocation entries.
 */

/* Relocations that don't need an addend field. */
typedef struct {
	Elf64_Addr	r_offset;	/* Location to be relocated. */
	Elf64_Xword	r_info;		/* Relocation type and symbol index. */
} Elf64_Rel;

/* Relocations that need an addend field. */
typedef struct {
	Elf64_Addr	r_offset;	/* Location to be relocated. */
	Elf64_Xword	r_info;		/* Relocation type and symbol index. */
	Elf64_Sxword	r_addend;	/* Addend. */
} Elf64_Rela;

/* Macros for accessing the fields of r_info. */
#define	ELF64_R_SYM(info)	((info) >> 32)
#define	ELF64_R_TYPE(info)	((info) & 0xffffffffL)

/* Macro for constructing r_info from field values. */
#define	ELF64_R_INFO(sym, type)	(((sym) << 32) + ((type) & 0xffffffffL))

#define	ELF64_R_TYPE_DATA(info)	(((Elf64_Xword)(info)<<32)>>40)
#define	ELF64_R_TYPE_ID(info)	(((Elf64_Xword)(info)<<56)>>56)
#define	ELF64_R_TYPE_INFO(data, type)	\
				(((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))

/*
 *	Note entry header
 */
typedef Elf_Note Elf64_Nhdr;

/*
 *	Move entry
 */
typedef struct {
	Elf64_Lword	m_value;	/* symbol value */
	Elf64_Xword 	m_info;		/* size + index */
	Elf64_Xword	m_poffset;	/* symbol offset */
	Elf64_Half	m_repeat;	/* repeat count */
	Elf64_Half	m_stride;	/* stride info */
} Elf64_Move;

#define	ELF64_M_SYM(info)	((info)>>8)
#define	ELF64_M_SIZE(info)	((unsigned char)(info))
#define	ELF64_M_INFO(sym, size)	(((sym)<<8)+(unsigned char)(size))

/*
 *	Hardware/Software capabilities entry
 */
typedef struct {
	Elf64_Xword	c_tag;		/* how to interpret value */
	union {
		Elf64_Xword	c_val;
		Elf64_Addr	c_ptr;
	} c_un;
} Elf64_Cap;

/*
 * Symbol table entries.
 */

typedef struct {
	Elf64_Word	st_name;	/* String table index of name. */
	unsigned char	st_info;	/* Type and binding information. */
	unsigned char	st_other;	/* Reserved (not used). */
	Elf64_Half	st_shndx;	/* Section index of symbol. */
	Elf64_Addr	st_value;	/* Symbol value. */
	Elf64_Xword	st_size;	/* Size of associated object. */
} Elf64_Sym;

/* Macros for accessing the fields of st_info. */
#define	ELF64_ST_BIND(info)		((info) >> 4)
#define	ELF64_ST_TYPE(info)		((info) & 0xf)

/* Macro for constructing st_info from field values. */
#define	ELF64_ST_INFO(bind, type)	(((bind) << 4) + ((type) & 0xf))

/* Macro for accessing the fields of st_other. */
#define	ELF64_ST_VISIBILITY(oth)	((oth) & 0x3)

/* Structures used by Sun & GNU-style symbol versioning. */
typedef struct {
	Elf64_Half	vd_version;
	Elf64_Half	vd_flags;
	Elf64_Half	vd_ndx;
	Elf64_Half	vd_cnt;
	Elf64_Word	vd_hash;
	Elf64_Word	vd_aux;
	Elf64_Word	vd_next;
} Elf64_Verdef;

typedef struct {
	Elf64_Word	vda_name;
	Elf64_Word	vda_next;
} Elf64_Verdaux;

typedef struct {
	Elf64_Half	vn_version;
	Elf64_Half	vn_cnt;
	Elf64_Word	vn_file;
	Elf64_Word	vn_aux;
	Elf64_Word	vn_next;
} Elf64_Verneed;

typedef struct {
	Elf64_Word	vna_hash;
	Elf64_Half	vna_flags;
	Elf64_Half	vna_other;
	Elf64_Word	vna_name;
	Elf64_Word	vna_next;
} Elf64_Vernaux;

typedef Elf64_Half Elf64_Versym;

typedef struct {
	Elf64_Half	si_boundto;	/* direct bindings - symbol bound to */
	Elf64_Half	si_flags;	/* per symbol flags */
} Elf64_Syminfo;

#endif /* !_SYS_ELF64_H_ */


================================================
FILE: src/elf_common.h
================================================
/*-
 * Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien
 * Copyright (c) 1998 John D. Polstra.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: head/sys/sys/elf_common.h 273284 2014-10-19 20:23:31Z andrew $
 */

#ifndef _SYS_ELF_COMMON_H_
#define	_SYS_ELF_COMMON_H_ 1

/*
 * ELF definitions that are independent of architecture or word size.
 */

/*
 * Note header.  The ".note" section contains an array of notes.  Each
 * begins with this header, aligned to a word boundary.  Immediately
 * following the note header is n_namesz bytes of name, padded to the
 * next word boundary.  Then comes n_descsz bytes of descriptor, again
 * padded to a word boundary.  The values of n_namesz and n_descsz do
 * not include the padding.
 */

typedef struct {
	uint32_t	n_namesz;	/* Length of name. */
	uint32_t	n_descsz;	/* Length of descriptor. */
	uint32_t	n_type;		/* Type of this note. */
} Elf_Note;

/*
 * The header for GNU-style hash sections.
 */

typedef struct {
	uint32_t	gh_nbuckets;	/* Number of hash buckets. */
	uint32_t	gh_symndx;	/* First visible symbol in .dynsym. */
	uint32_t	gh_maskwords;	/* #maskwords used in bloom filter. */
	uint32_t	gh_shift2;	/* Bloom filter shift count. */
} Elf_GNU_Hash_Header;

/* Indexes into the e_ident array.  Keep synced with
   http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
#define	EI_MAG0		0	/* Magic number, byte 0. */
#define	EI_MAG1		1	/* Magic number, byte 1. */
#define	EI_MAG2		2	/* Magic number, byte 2. */
#define	EI_MAG3		3	/* Magic number, byte 3. */
#define	EI_CLASS	4	/* Class of machine. */
#define	EI_DATA		5	/* Data format. */
#define	EI_VERSION	6	/* ELF format version. */
#define	EI_OSABI	7	/* Operating system / ABI identification */
#define	EI_ABIVERSION	8	/* ABI version */
#define	OLD_EI_BRAND	8	/* Start of architecture identification. */
#define	EI_PAD		9	/* Start of padding (per SVR4 ABI). */
#define	EI_NIDENT	16	/* Size of e_ident array. */

/* Values for the magic number bytes. */
#define	ELFMAG0		0x7f
#define	ELFMAG1		'E'
#define	ELFMAG2		'L'
#define	ELFMAG3		'F'
#define	ELFMAG		"\177ELF"	/* magic string */
#define	SELFMAG		4		/* magic string size */

/* Values for e_ident[EI_VERSION] and e_version. */
#define	EV_NONE		0
#define	EV_CURRENT	1

/* Values for e_ident[EI_CLASS]. */
#define	ELFCLASSNONE	0	/* Unknown class. */
#define	ELFCLASS32	1	/* 32-bit architecture. */
#define	ELFCLASS64	2	/* 64-bit architecture. */

/* Values for e_ident[EI_DATA]. */
#define	ELFDATANONE	0	/* Unknown data format. */
#define	ELFDATA2LSB	1	/* 2's complement little-endian. */
#define	ELFDATA2MSB	2	/* 2's complement big-endian. */

/* Values for e_ident[EI_OSABI]. */
#define	ELFOSABI_NONE		0	/* UNIX System V ABI */
#define	ELFOSABI_HPUX		1	/* HP-UX operating system */
#define	ELFOSABI_NETBSD		2	/* NetBSD */
#define	ELFOSABI_LINUX		3	/* GNU/Linux */
#define	ELFOSABI_HURD		4	/* GNU/Hurd */
#define	ELFOSABI_86OPEN		5	/* 86Open common IA32 ABI */
#define	ELFOSABI_SOLARIS	6	/* Solaris */
#define	ELFOSABI_AIX		7	/* AIX */
#define	ELFOSABI_IRIX		8	/* IRIX */
#define	ELFOSABI_FREEBSD	9	/* FreeBSD */
#define	ELFOSABI_TRU64		10	/* TRU64 UNIX */
#define	ELFOSABI_MODESTO	11	/* Novell Modesto */
#define	ELFOSABI_OPENBSD	12	/* OpenBSD */
#define	ELFOSABI_OPENVMS	13	/* Open VMS */
#define	ELFOSABI_NSK		14	/* HP Non-Stop Kernel */
#define	ELFOSABI_AROS		15	/* Amiga Research OS */
#define	ELFOSABI_ARM		97	/* ARM */
#define	ELFOSABI_STANDALONE	255	/* Standalone (embedded) application */

#define	ELFOSABI_SYSV		ELFOSABI_NONE	/* symbol used in old spec */
#define	ELFOSABI_MONTEREY	ELFOSABI_AIX	/* Monterey */

/* e_ident */
#define	IS_ELF(ehdr)	((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
			 (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
			 (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
			 (ehdr).e_ident[EI_MAG3] == ELFMAG3)

/* Values for e_type. */
#define	ET_NONE		0	/* Unknown type. */
#define	ET_REL		1	/* Relocatable. */
#define	ET_EXEC		2	/* Executable. */
#define	ET_DYN		3	/* Shared object. */
#define	ET_CORE		4	/* Core file. */
#define	ET_LOOS		0xfe00	/* First operating system specific. */
#define	ET_HIOS		0xfeff	/* Last operating system-specific. */
#define	ET_LOPROC	0xff00	/* First processor-specific. */
#define	ET_HIPROC	0xffff	/* Last processor-specific. */

/* Values for e_machine. */
#define	EM_NONE		0	/* Unknown machine. */
#define	EM_M32		1	/* AT&T WE32100. */
#define	EM_SPARC	2	/* Sun SPARC. */
#define	EM_386		3	/* Intel i386. */
#define	EM_68K		4	/* Motorola 68000. */
#define	EM_88K		5	/* Motorola 88000. */
#define	EM_860		7	/* Intel i860. */
#define	EM_MIPS		8	/* MIPS R3000 Big-Endian only. */
#define	EM_S370		9	/* IBM System/370. */
#define	EM_MIPS_RS3_LE	10	/* MIPS R3000 Little-Endian. */
#define	EM_PARISC	15	/* HP PA-RISC. */
#define	EM_VPP500	17	/* Fujitsu VPP500. */
#define	EM_SPARC32PLUS	18	/* SPARC v8plus. */
#define	EM_960		19	/* Intel 80960. */
#define	EM_PPC		20	/* PowerPC 32-bit. */
#define	EM_PPC64	21	/* PowerPC 64-bit. */
#define	EM_S390		22	/* IBM System/390. */
#define	EM_V800		36	/* NEC V800. */
#define	EM_FR20		37	/* Fujitsu FR20. */
#define	EM_RH32		38	/* TRW RH-32. */
#define	EM_RCE		39	/* Motorola RCE. */
#define	EM_ARM		40	/* ARM. */
#define	EM_SH		42	/* Hitachi SH. */
#define	EM_SPARCV9	43	/* SPARC v9 64-bit. */
#define	EM_TRICORE	44	/* Siemens TriCore embedded processor. */
#define	EM_ARC		45	/* Argonaut RISC Core. */
#define	EM_H8_300	46	/* Hitachi H8/300. */
#define	EM_H8_300H	47	/* Hitachi H8/300H. */
#define	EM_H8S		48	/* Hitachi H8S. */
#define	EM_H8_500	49	/* Hitachi H8/500. */
#define	EM_IA_64	50	/* Intel IA-64 Processor. */
#define	EM_MIPS_X	51	/* Stanford MIPS-X. */
#define	EM_COLDFIRE	52	/* Motorola ColdFire. */
#define	EM_68HC12	53	/* Motorola M68HC12. */
#define	EM_MMA		54	/* Fujitsu MMA. */
#define	EM_PCP		55	/* Siemens PCP. */
#define	EM_NCPU		56	/* Sony nCPU. */
#define	EM_NDR1		57	/* Denso NDR1 microprocessor. */
#define	EM_STARCORE	58	/* Motorola Star*Core processor. */
#define	EM_ME16		59	/* Toyota ME16 processor. */
#define	EM_ST100	60	/* STMicroelectronics ST100 processor. */
#define	EM_TINYJ	61	/* Advanced Logic Corp. TinyJ processor. */
#define	EM_X86_64	62	/* Advanced Micro Devices x86-64 */
#define	EM_AMD64	EM_X86_64	/* Advanced Micro Devices x86-64 (compat) */
#define	EM_PDSP		63	/* Sony DSP Processor. */
#define	EM_FX66		66	/* Siemens FX66 microcontroller. */
#define	EM_ST9PLUS	67	/* STMicroelectronics ST9+ 8/16
				   microcontroller. */
#define	EM_ST7		68	/* STmicroelectronics ST7 8-bit
				   microcontroller. */
#define	EM_68HC16	69	/* Motorola MC68HC16 microcontroller. */
#define	EM_68HC11	70	/* Motorola MC68HC11 microcontroller. */
#define	EM_68HC08	71	/* Motorola MC68HC08 microcontroller. */
#define	EM_68HC05	72	/* Motorola MC68HC05 microcontroller. */
#define	EM_SVX		73	/* Silicon Graphics SVx. */
#define	EM_ST19		74	/* STMicroelectronics ST19 8-bit mc. */
#define	EM_VAX		75	/* Digital VAX. */
#define	EM_CRIS		76	/* Axis Communications 32-bit embedded
				   processor. */
#define	EM_JAVELIN	77	/* Infineon Technologies 32-bit embedded
				   processor. */
#define	EM_FIREPATH	78	/* Element 14 64-bit DSP Processor. */
#define	EM_ZSP		79	/* LSI Logic 16-bit DSP Processor. */
#define	EM_MMIX		80	/* Donald Knuth's educational 64-bit proc. */
#define	EM_HUANY	81	/* Harvard University machine-independent
				   object files. */
#define	EM_PRISM	82	/* SiTera Prism. */
#define	EM_AVR		83	/* Atmel AVR 8-bit microcontroller. */
#define	EM_FR30		84	/* Fujitsu FR30. */
#define	EM_D10V		85	/* Mitsubishi D10V. */
#define	EM_D30V		86	/* Mitsubishi D30V. */
#define	EM_V850		87	/* NEC v850. */
#define	EM_M32R		88	/* Mitsubishi M32R. */
#define	EM_MN10300	89	/* Matsushita MN10300. */
#define	EM_MN10200	90	/* Matsushita MN10200. */
#define	EM_PJ		91	/* picoJava. */
#define	EM_OPENRISC	92	/* OpenRISC 32-bit embedded processor. */
#define	EM_ARC_A5	93	/* ARC Cores Tangent-A5. */
#define	EM_XTENSA	94	/* Tensilica Xtensa Architecture. */
#define	EM_VIDEOCORE	95	/* Alphamosaic VideoCore processor. */
#define	EM_TMM_GPP	96	/* Thompson Multimedia General Purpose
				   Processor. */
#define	EM_NS32K	97	/* National Semiconductor 32000 series. */
#define	EM_TPC		98	/* Tenor Network TPC processor. */
#define	EM_SNP1K	99	/* Trebia SNP 1000 processor. */
#define	EM_ST200	100	/* STMicroelectronics ST200 microcontroller. */
#define	EM_IP2K		101	/* Ubicom IP2xxx microcontroller family. */
#define	EM_MAX		102	/* MAX Processor. */
#define	EM_CR		103	/* National Semiconductor CompactRISC
				   microprocessor. */
#define	EM_F2MC16	104	/* Fujitsu F2MC16. */
#define	EM_MSP430	105	/* Texas Instruments embedded microcontroller
				   msp430. */
#define	EM_BLACKFIN	106	/* Analog Devices Blackfin (DSP) processor. */
#define	EM_SE_C33	107	/* S1C33 Family of Seiko Epson processors. */
#define	EM_SEP		108	/* Sharp embedded microprocessor. */
#define	EM_ARCA		109	/* Arca RISC Microprocessor. */
#define	EM_UNICORE	110	/* Microprocessor series from PKU-Unity Ltd.
				   and MPRC of Peking University */
#define	EM_AARCH64	183	/* AArch64 (64-bit ARM) */

/* Non-standard or deprecated. */
#define	EM_486		6	/* Intel i486. */
#define	EM_MIPS_RS4_BE	10	/* MIPS R4000 Big-Endian */
#define	EM_ALPHA_STD	41	/* Digital Alpha (standard value). */
#define	EM_ALPHA	0x9026	/* Alpha (written in the absence of an ABI) */

/* Special section indexes. */
#define	SHN_UNDEF	     0		/* Undefined, missing, irrelevant. */
#define	SHN_LORESERVE	0xff00		/* First of reserved range. */
#define	SHN_LOPROC	0xff00		/* First processor-specific. */
#define	SHN_HIPROC	0xff1f		/* Last processor-specific. */
#define	SHN_LOOS	0xff20		/* First operating system-specific. */
#define	SHN_HIOS	0xff3f		/* Last operating system-specific. */
#define	SHN_ABS		0xfff1		/* Absolute values. */
#define	SHN_COMMON	0xfff2		/* Common data. */
#define	SHN_XINDEX	0xffff		/* Escape -- index stored elsewhere. */
#define	SHN_HIRESERVE	0xffff		/* Last of reserved range. */

/* sh_type */
#define	SHT_NULL		0	/* inactive */
#define	SHT_PROGBITS		1	/* program defined information */
#define	SHT_SYMTAB		2	/* symbol table section */
#define	SHT_STRTAB		3	/* string table section */
#define	SHT_RELA		4	/* relocation section with addends */
#define	SHT_HASH		5	/* symbol hash table section */
#define	SHT_DYNAMIC		6	/* dynamic section */
#define	SHT_NOTE		7	/* note section */
#define	SHT_NOBITS		8	/* no space section */
#define	SHT_REL			9	/* relocation section - no addends */
#define	SHT_SHLIB		10	/* reserved - purpose unknown */
#define	SHT_DYNSYM		11	/* dynamic symbol table section */
#define	SHT_INIT_ARRAY		14	/* Initialization function pointers. */
#define	SHT_FINI_ARRAY		15	/* Termination function pointers. */
#define	SHT_PREINIT_ARRAY	16	/* Pre-initialization function ptrs. */
#define	SHT_GROUP		17	/* Section group. */
#define	SHT_SYMTAB_SHNDX	18	/* Section indexes (see SHN_XINDEX). */
#define	SHT_LOOS		0x60000000	/* First of OS specific semantics */
#define	SHT_LOSUNW		0x6ffffff4
#define	SHT_SUNW_dof		0x6ffffff4
#define	SHT_SUNW_cap		0x6ffffff5
#define	SHT_SUNW_SIGNATURE	0x6ffffff6
#define	SHT_GNU_HASH		0x6ffffff6
#define	SHT_GNU_LIBLIST		0x6ffffff7
#define	SHT_SUNW_ANNOTATE	0x6ffffff7
#define	SHT_SUNW_DEBUGSTR	0x6ffffff8
#define	SHT_SUNW_DEBUG		0x6ffffff9
#define	SHT_SUNW_move		0x6ffffffa
#define	SHT_SUNW_COMDAT		0x6ffffffb
#define	SHT_SUNW_syminfo	0x6ffffffc
#define	SHT_SUNW_verdef		0x6ffffffd
#define	SHT_GNU_verdef		0x6ffffffd	/* Symbol versions provided */
#define	SHT_SUNW_verneed	0x6ffffffe
#define	SHT_GNU_verneed		0x6ffffffe	/* Symbol versions required */
#define	SHT_SUNW_versym		0x6fffffff
#define	SHT_GNU_versym		0x6fffffff	/* Symbol version table */
#define	SHT_HISUNW		0x6fffffff
#define	SHT_HIOS		0x6fffffff	/* Last of OS specific semantics */
#define	SHT_LOPROC		0x70000000	/* reserved range for processor */
#define	SHT_AMD64_UNWIND	0x70000001	/* unwind information */
#define	SHT_ARM_EXIDX		0x70000001	/* Exception index table. */
#define	SHT_ARM_PREEMPTMAP	0x70000002	/* BPABI DLL dynamic linking 
						   pre-emption map. */
#define	SHT_ARM_ATTRIBUTES	0x70000003	/* Object file compatibility 
						   attributes. */
#define	SHT_ARM_DEBUGOVERLAY	0x70000004	/* See DBGOVL for details. */
#define	SHT_ARM_OVERLAYSECTION	0x70000005	/* See DBGOVL for details. */
#define	SHT_MIPS_REGINFO	0x70000006
#define	SHT_MIPS_OPTIONS	0x7000000d
#define	SHT_MIPS_DWARF		0x7000001e	/* MIPS gcc uses MIPS_DWARF */
#define	SHT_HIPROC		0x7fffffff	/* specific section header types */
#define	SHT_LOUSER		0x80000000	/* reserved range for application */
#define	SHT_HIUSER		0xffffffff	/* specific indexes */

/* Flags for sh_flags. */
#define	SHF_WRITE		0x1	/* Section contains writable data. */
#define	SHF_ALLOC		0x2	/* Section occupies memory. */
#define	SHF_EXECINSTR		0x4	/* Section contains instructions. */
#define	SHF_MERGE		0x10	/* Section may be merged. */
#define	SHF_STRINGS		0x20	/* Section contains strings. */
#define	SHF_INFO_LINK		0x40	/* sh_info holds section index. */
#define	SHF_LINK_ORDER		0x80	/* Special ordering requirements. */
#define	SHF_OS_NONCONFORMING	0x100	/* OS-specific processing required. */
#define	SHF_GROUP		0x200	/* Member of section group. */
#define	SHF_TLS			0x400	/* Section contains TLS data. */
#define	SHF_MASKOS	0x0ff00000	/* OS-specific semantics. */
#define	SHF_MASKPROC	0xf0000000	/* Processor-specific semantics. */

/* Values for p_type. */
#define	PT_NULL		0	/* Unused entry. */
#define	PT_LOAD		1	/* Loadable segment. */
#define	PT_DYNAMIC	2	/* Dynamic linking information segment. */
#define	PT_INTERP	3	/* Pathname of interpreter. */
#define	PT_NOTE		4	/* Auxiliary information. */
#define	PT_SHLIB	5	/* Reserved (not used). */
#define	PT_PHDR		6	/* Location of program header itself. */
#define	PT_TLS		7	/* Thread local storage segment */
#define	PT_LOOS		0x60000000	/* First OS-specific. */
#define	PT_SUNW_UNWIND	0x6464e550	/* amd64 UNWIND program header */
#define	PT_GNU_EH_FRAME	0x6474e550
#define	PT_GNU_STACK	0x6474e551
#define	PT_GNU_RELRO	0x6474e552
#define	PT_DUMP_DELTA	0x6fb5d000	/* va->pa map for kernel dumps
					   (currently arm). */
#define	PT_LOSUNW	0x6ffffffa
#define	PT_SUNWBSS	0x6ffffffa	/* Sun Specific segment */
#define	PT_SUNWSTACK	0x6ffffffb	/* describes the stack segment */
#define	PT_SUNWDTRACE	0x6ffffffc	/* private */
#define	PT_SUNWCAP	0x6ffffffd	/* hard/soft capabilities segment */
#define	PT_HISUNW	0x6fffffff
#define	PT_HIOS		0x6fffffff	/* Last OS-specific. */
#define	PT_LOPROC	0x70000000	/* First processor-specific type. */
#define	PT_HIPROC	0x7fffffff	/* Last processor-specific type. */

/* Values for p_flags. */
#define	PF_X		0x1		/* Executable. */
#define	PF_W		0x2		/* Writable. */
#define	PF_R		0x4		/* Readable. */
#define	PF_MASKOS	0x0ff00000	/* Operating system-specific. */
#define	PF_MASKPROC	0xf0000000	/* Processor-specific. */

/* Extended program header index. */
#define	PN_XNUM		0xffff

/* Values for d_tag. */
#define	DT_NULL		0	/* Terminating entry. */
#define	DT_NEEDED	1	/* String table offset of a needed shared
				   library. */
#define	DT_PLTRELSZ	2	/* Total size in bytes of PLT relocations. */
#define	DT_PLTGOT	3	/* Processor-dependent address. */
#define	DT_HASH		4	/* Address of symbol hash table. */
#define	DT_STRTAB	5	/* Address of string table. */
#define	DT_SYMTAB	6	/* Address of symbol table. */
#define	DT_RELA		7	/* Address of ElfNN_Rela relocations. */
#define	DT_RELASZ	8	/* Total size of ElfNN_Rela relocations. */
#define	DT_RELAENT	9	/* Size of each ElfNN_Rela relocation entry. */
#define	DT_STRSZ	10	/* Size of string table. */
#define	DT_SYMENT	11	/* Size of each symbol table entry. */
#define	DT_INIT		12	/* Address of initialization function. */
#define	DT_FINI		13	/* Address of finalization function. */
#define	DT_SONAME	14	/* String table offset of shared object
				   name. */
#define	DT_RPATH	15	/* String table offset of library path. [sup] */
#define	DT_SYMBOLIC	16	/* Indicates "symbolic" linking. [sup] */
#define	DT_REL		17	/* Address of ElfNN_Rel relocations. */
#define	DT_RELSZ	18	/* Total size of ElfNN_Rel relocations. */
#define	DT_RELENT	19	/* Size of each ElfNN_Rel relocation. */
#define	DT_PLTREL	20	/* Type of relocation used for PLT. */
#define	DT_DEBUG	21	/* Reserved (not used). */
#define	DT_TEXTREL	22	/* Indicates there may be relocations in
				   non-writable segments. [sup] */
#define	DT_JMPREL	23	/* Address of PLT relocations. */
#define	DT_BIND_NOW	24	/* [sup] */
#define	DT_INIT_ARRAY	25	/* Address of the array of pointers to
				   initialization functions */
#define	DT_FINI_ARRAY	26	/* Address of the array of pointers to
				   termination functions */
#define	DT_INIT_ARRAYSZ	27	/* Size in bytes of the array of
				   initialization functions. */
#define	DT_FINI_ARRAYSZ	28	/* Size in bytes of the array of
				   termination functions. */
#define	DT_RUNPATH	29	/* String table offset of a null-terminated
				   library search path string. */
#define	DT_FLAGS	30	/* Object specific flag values. */
#define	DT_ENCODING	32	/* Values greater than or equal to DT_ENCODING
				   and less than DT_LOOS follow the rules for
				   the interpretation of the d_un union
				   as follows: even == 'd_ptr', odd == 'd_val'
				   or none */
#define	DT_PREINIT_ARRAY 32	/* Address of the array of pointers to
				   pre-initialization functions. */
#define	DT_PREINIT_ARRAYSZ 33	/* Size in bytes of the array of
				   pre-initialization functions. */
#define	DT_MAXPOSTAGS	34	/* number of positive tags */
#define	DT_LOOS		0x6000000d	/* First OS-specific */
#define	DT_SUNW_AUXILIARY	0x6000000d	/* symbol auxiliary name */
#define	DT_SUNW_RTLDINF		0x6000000e	/* ld.so.1 info (private) */
#define	DT_SUNW_FILTER		0x6000000f	/* symbol filter name */
#define	DT_SUNW_CAP		0x60000010	/* hardware/software */
#define	DT_HIOS		0x6ffff000	/* Last OS-specific */

/*
 * DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
 * Dyn.d_un.d_val field of the Elf*_Dyn structure.
 */
#define	DT_VALRNGLO	0x6ffffd00
#define	DT_CHECKSUM	0x6ffffdf8	/* elf checksum */
#define	DT_PLTPADSZ	0x6ffffdf9	/* pltpadding size */
#define	DT_MOVEENT	0x6ffffdfa	/* move table entry size */
#define	DT_MOVESZ	0x6ffffdfb	/* move table size */
#define	DT_FEATURE	0x6ffffdfc	/* feature holder */
#define	DT_POSFLAG_1	0x6ffffdfd	/* flags for DT_* entries, effecting */
					/*	the following DT_* entry. */
					/*	See DF_P1_* definitions */
#define	DT_SYMINSZ	0x6ffffdfe	/* syminfo table size (in bytes) */
#define	DT_SYMINENT	0x6ffffdff	/* syminfo entry size (in bytes) */
#define	DT_VALRNGHI	0x6ffffdff

/*
 * DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
 * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
 *
 * If any adjustment is made to the ELF object after it has been
 * built, these entries will need to be adjusted.
 */
#define	DT_ADDRRNGLO	0x6ffffe00
#define	DT_GNU_HASH	0x6ffffef5	/* GNU-style hash table */
#define	DT_CONFIG	0x6ffffefa	/* configuration information */
#define	DT_DEPAUDIT	0x6ffffefb	/* dependency auditing */
#define	DT_AUDIT	0x6ffffefc	/* object auditing */
#define	DT_PLTPAD	0x6ffffefd	/* pltpadding (sparcv9) */
#define	DT_MOVETAB	0x6ffffefe	/* move table */
#define	DT_SYMINFO	0x6ffffeff	/* syminfo table */
#define	DT_ADDRRNGHI	0x6ffffeff

#define	DT_VERSYM	0x6ffffff0	/* Address of versym section. */
#define	DT_RELACOUNT	0x6ffffff9	/* number of RELATIVE relocations */
#define	DT_RELCOUNT	0x6ffffffa	/* number of RELATIVE relocations */
#define	DT_FLAGS_1	0x6ffffffb	/* state flags - see DF_1_* defs */
#define	DT_VERDEF	0x6ffffffc	/* Address of verdef section. */
#define	DT_VERDEFNUM	0x6ffffffd	/* Number of elems in verdef section */
#define	DT_VERNEED	0x6ffffffe	/* Address of verneed section. */
#define	DT_VERNEEDNUM	0x6fffffff	/* Number of elems in verneed section */

#define	DT_LOPROC	0x70000000	/* First processor-specific type. */
#define	DT_DEPRECATED_SPARC_REGISTER	0x7000001
#define	DT_AUXILIARY	0x7ffffffd	/* shared library auxiliary name */
#define	DT_USED		0x7ffffffe	/* ignored - same as needed */
#define	DT_FILTER	0x7fffffff	/* shared library filter name */
#define	DT_HIPROC	0x7fffffff	/* Last processor-specific type. */

/* Values for DT_FLAGS */
#define	DF_ORIGIN	0x0001	/* Indicates that the object being loaded may
				   make reference to the $ORIGIN substitution
				   string */
#define	DF_SYMBOLIC	0x0002	/* Indicates "symbolic" linking. */
#define	DF_TEXTREL	0x0004	/* Indicates there may be relocations in
				   non-writable segments. */
#define	DF_BIND_NOW	0x0008	/* Indicates that the dynamic linker should
				   process all relocations for the object
				   containing this entry before transferring
				   control to the program. */
#define	DF_STATIC_TLS	0x0010	/* Indicates that the shared object or
				   executable contains code using a static
				   thread-local storage scheme. */

/* Values for DT_FLAGS_1 */
#define	DF_1_BIND_NOW	0x00000001	/* Same as DF_BIND_NOW */
#define	DF_1_GLOBAL	0x00000002	/* Set the RTLD_GLOBAL for object */
#define	DF_1_NODELETE	0x00000008	/* Set the RTLD_NODELETE for object */
#define	DF_1_LOADFLTR	0x00000010	/* Immediate loading of filtees */
#define	DF_1_NOOPEN     0x00000040	/* Do not allow loading on dlopen() */
#define	DF_1_ORIGIN	0x00000080	/* Process $ORIGIN */
#define	DF_1_INTERPOSE	0x00000400	/* Interpose all objects but main */
#define	DF_1_NODEFLIB	0x00000800	/* Do not search default paths */

/* Values for n_type.  Used in core files. */
#define	NT_PRSTATUS	1	/* Process status. */
#define	NT_FPREGSET	2	/* Floating point registers. */
#define	NT_PRPSINFO	3	/* Process state info. */
#define	NT_THRMISC	7	/* Thread miscellaneous info. */
#define	NT_PROCSTAT_PROC	8	/* Procstat proc data. */
#define	NT_PROCSTAT_FILES	9	/* Procstat files data. */
#define	NT_PROCSTAT_VMMAP	10	/* Procstat vmmap data. */
#define	NT_PROCSTAT_GROUPS	11	/* Procstat groups data. */
#define	NT_PROCSTAT_UMASK	12	/* Procstat umask data. */
#define	NT_PROCSTAT_RLIMIT	13	/* Procstat rlimit data. */
#define	NT_PROCSTAT_OSREL	14	/* Procstat osreldate data. */
#define	NT_PROCSTAT_PSSTRINGS	15	/* Procstat ps_strings data. */
#define	NT_PROCSTAT_AUXV	16	/* Procstat auxv data. */

/* Symbol Binding - ELFNN_ST_BIND - st_info */
#define	STB_LOCAL	0	/* Local symbol */
#define	STB_GLOBAL	1	/* Global symbol */
#define	STB_WEAK	2	/* like global - lower precedence */
#define	STB_LOOS	10	/* Reserved range for operating system */
#define	STB_HIOS	12	/*   specific semantics. */
#define	STB_LOPROC	13	/* reserved range for processor */
#define	STB_HIPROC	15	/*   specific semantics. */

/* Symbol type - ELFNN_ST_TYPE - st_info */
#define	STT_NOTYPE	0	/* Unspecified type. */
#define	STT_OBJECT	1	/* Data object. */
#define	STT_FUNC	2	/* Function. */
#define	STT_SECTION	3	/* Section. */
#define	STT_FILE	4	/* Source file. */
#define	STT_COMMON	5	/* Uninitialized common block. */
#define	STT_TLS		6	/* TLS object. */
#define	STT_NUM		7
#define	STT_LOOS	10	/* Reserved range for operating system */
#define	STT_GNU_IFUNC	10
#define	STT_HIOS	12	/*   specific semantics. */
#define	STT_LOPROC	13	/* reserved range for processor */
#define	STT_HIPROC	15	/*   specific semantics. */

/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
#define	STV_DEFAULT	0x0	/* Default visibility (see binding). */
#define	STV_INTERNAL	0x1	/* Special meaning in relocatable objects. */
#define	STV_HIDDEN	0x2	/* Not visible. */
#define	STV_PROTECTED	0x3	/* Visible but not preemptible. */
#define	STV_EXPORTED	0x4
#define	STV_SINGLETON	0x5
#define	STV_ELIMINATE	0x6

/* Special symbol table indexes. */
#define	STN_UNDEF	0	/* Undefined symbol index. */

/* Symbol versioning flags. */
#define	VER_DEF_CURRENT	1
#define	VER_DEF_IDX(x)	VER_NDX(x)

#define	VER_FLG_BASE	0x01
#define	VER_FLG_WEAK	0x02

#define	VER_NEED_CURRENT	1
#define	VER_NEED_WEAK	(1u << 15)
#define	VER_NEED_HIDDEN	VER_NDX_HIDDEN
#define	VER_NEED_IDX(x)	VER_NDX(x)

#define	VER_NDX_LOCAL	0
#define	VER_NDX_GLOBAL	1
#define	VER_NDX_GIVEN	2

#define	VER_NDX_HIDDEN	(1u << 15)
#define	VER_NDX(x)	((x) & ~(1u << 15))

#define	CA_SUNW_NULL	0
#define	CA_SUNW_HW_1	1		/* first hardware capabilities entry */
#define	CA_SUNW_SF_1	2		/* first software capabilities entry */

/*
 * Syminfo flag values
 */
#define	SYMINFO_FLG_DIRECT	0x0001	/* symbol ref has direct association */
					/*	to object containing defn. */
#define	SYMINFO_FLG_PASSTHRU	0x0002	/* ignored - see SYMINFO_FLG_FILTER */
#define	SYMINFO_FLG_COPY	0x0004	/* symbol is a copy-reloc */
#define	SYMINFO_FLG_LAZYLOAD	0x0008	/* object containing defn should be */
					/*	lazily-loaded */
#define	SYMINFO_FLG_DIRECTBIND	0x0010	/* ref should be bound directly to */
					/*	object containing defn. */
#define	SYMINFO_FLG_NOEXTDIRECT	0x0020	/* don't let an external reference */
					/*	directly bind to this symbol */
#define	SYMINFO_FLG_FILTER	0x0002	/* symbol ref is associated to a */
#define	SYMINFO_FLG_AUXILIARY	0x0040	/* 	standard or auxiliary filter */

/*
 * Syminfo.si_boundto values.
 */
#define	SYMINFO_BT_SELF		0xffff	/* symbol bound to self */
#define	SYMINFO_BT_PARENT	0xfffe	/* symbol bound to parent */
#define	SYMINFO_BT_NONE		0xfffd	/* no special symbol binding */
#define	SYMINFO_BT_EXTERN	0xfffc	/* symbol defined as external */
#define	SYMINFO_BT_LOWRESERVE	0xff00	/* beginning of reserved entries */

/*
 * Syminfo version values.
 */
#define	SYMINFO_NONE		0	/* Syminfo version */
#define	SYMINFO_CURRENT		1
#define	SYMINFO_NUM		2

/*
 * Relocation types.
 *
 * All machine architectures are defined here to allow tools on one to
 * handle others.
 */

#define	R_386_NONE		0	/* No relocation. */
#define	R_386_32		1	/* Add symbol value. */
#define	R_386_PC32		2	/* Add PC-relative symbol value. */
#define	R_386_GOT32		3	/* Add PC-relative GOT offset. */
#define	R_386_PLT32		4	/* Add PC-relative PLT offset. */
#define	R_386_COPY		5	/* Copy data from shared object. */
#define	R_386_GLOB_DAT		6	/* Set GOT entry to data address. */
#define	R_386_JMP_SLOT		7	/* Set GOT entry to code address. */
#define	R_386_RELATIVE		8	/* Add load address of shared object. */
#define	R_386_GOTOFF		9	/* Add GOT-relative symbol address. */
#define	R_386_GOTPC		10	/* Add PC-relative GOT table address. */
#define	R_386_TLS_TPOFF		14	/* Negative offset in static TLS block */
#define	R_386_TLS_IE		15	/* Absolute address of GOT for -ve static TLS */
#define	R_386_TLS_GOTIE		16	/* GOT entry for negative static TLS block */
#define	R_386_TLS_LE		17	/* Negative offset relative to static TLS */
#define	R_386_TLS_GD		18	/* 32 bit offset to GOT (index,off) pair */
#define	R_386_TLS_LDM		19	/* 32 bit offset to GOT (index,zero) pair */
#define	R_386_TLS_GD_32		24	/* 32 bit offset to GOT (index,off) pair */
#define	R_386_TLS_GD_PUSH	25	/* pushl instruction for Sun ABI GD sequence */
#define	R_386_TLS_GD_CALL	26	/* call instruction for Sun ABI GD sequence */
#define	R_386_TLS_GD_POP	27	/* popl instruction for Sun ABI GD sequence */
#define	R_386_TLS_LDM_32	28	/* 32 bit offset to GOT (index,zero) pair */
#define	R_386_TLS_LDM_PUSH	29	/* pushl instruction for Sun ABI LD sequence */
#define	R_386_TLS_LDM_CALL	30	/* call instruction for Sun ABI LD sequence */
#define	R_386_TLS_LDM_POP	31	/* popl instruction for Sun ABI LD sequence */
#define	R_386_TLS_LDO_32	32	/* 32 bit offset from start of TLS block */
#define	R_386_TLS_IE_32		33	/* 32 bit offset to GOT static TLS offset entry */
#define	R_386_TLS_LE_32		34	/* 32 bit offset within static TLS block */
#define	R_386_TLS_DTPMOD32	35	/* GOT entry containing TLS index */
#define	R_386_TLS_DTPOFF32	36	/* GOT entry containing TLS offset */
#define	R_386_TLS_TPOFF32	37	/* GOT entry of -ve static TLS offset */
#define	R_386_IRELATIVE		42	/* PLT entry resolved indirectly at runtime */

#define	R_ARM_NONE		0	/* No relocation. */
#define	R_ARM_PC24		1
#define	R_ARM_ABS32		2
#define	R_ARM_REL32		3
#define	R_ARM_PC13		4
#define	R_ARM_ABS16		5
#define	R_ARM_ABS12		6
#define	R_ARM_THM_ABS5		7
#define	R_ARM_ABS8		8
#define	R_ARM_SBREL32		9
#define	R_ARM_THM_PC22		10
#define	R_ARM_THM_PC8		11
#define	R_ARM_AMP_VCALL9	12
#define	R_ARM_SWI24		13
#define	R_ARM_THM_SWI8		14
#define	R_ARM_XPC25		15
#define	R_ARM_THM_XPC22		16
/* TLS relocations */
#define	R_ARM_TLS_DTPMOD32	17	/* ID of module containing symbol */
#define	R_ARM_TLS_DTPOFF32	18	/* Offset in TLS block */
#define	R_ARM_TLS_TPOFF32	19	/* Offset in static TLS block */
#define	R_ARM_COPY		20	/* Copy data from shared object. */
#define	R_ARM_GLOB_DAT		21	/* Set GOT entry to data address. */
#define	R_ARM_JUMP_SLOT		22	/* Set GOT entry to code address. */
#define	R_ARM_RELATIVE		23	/* Add load address of shared object. */
#define	R_ARM_GOTOFF		24	/* Add GOT-relative symbol address. */
#define	R_ARM_GOTPC		25	/* Add PC-relative GOT table address. */
#define	R_ARM_GOT32		26	/* Add PC-relative GOT offset. */
#define	R_ARM_PLT32		27	/* Add PC-relative PLT offset. */
#define	R_ARM_GNU_VTENTRY	100
#define	R_ARM_GNU_VTINHERIT	101
#define	R_ARM_RSBREL32		250
#define	R_ARM_THM_RPC22		251
#define	R_ARM_RREL32		252
#define	R_ARM_RABS32		253
#define	R_ARM_RPC24		254
#define	R_ARM_RBASE		255

/*	Name			Value	   Field	Calculation */
#define	R_IA_64_NONE		0	/* None */
#define	R_IA_64_IMM14		0x21	/* immediate14	S + A */
#define	R_IA_64_IMM22		0x22	/* immediate22	S + A */
#define	R_IA_64_IMM64		0x23	/* immediate64	S + A */
#define	R_IA_64_DIR32MSB	0x24	/* word32 MSB	S + A */
#define	R_IA_64_DIR32LSB	0x25	/* word32 LSB	S + A */
#define	R_IA_64_DIR64MSB	0x26	/* word64 MSB	S + A */
#define	R_IA_64_DIR64LSB	0x27	/* word64 LSB	S + A */
#define	R_IA_64_GPREL22		0x2a	/* immediate22	@gprel(S + A) */
#define	R_IA_64_GPREL64I	0x2b	/* immediate64	@gprel(S + A) */
#define	R_IA_64_GPREL32MSB	0x2c	/* word32 MSB	@gprel(S + A) */
#define	R_IA_64_GPREL32LSB	0x2d	/* word32 LSB	@gprel(S + A) */
#define	R_IA_64_GPREL64MSB	0x2e	/* word64 MSB	@gprel(S + A) */
#define	R_IA_64_GPREL64LSB	0x2f	/* word64 LSB	@gprel(S + A) */
#define	R_IA_64_LTOFF22		0x32	/* immediate22	@ltoff(S + A) */
#define	R_IA_64_LTOFF64I	0x33	/* immediate64	@ltoff(S + A) */
#define	R_IA_64_PLTOFF22	0x3a	/* immediate22	@pltoff(S + A) */
#define	R_IA_64_PLTOFF64I	0x3b	/* immediate64	@pltoff(S + A) */
#define	R_IA_64_PLTOFF64MSB	0x3e	/* word64 MSB	@pltoff(S + A) */
#define	R_IA_64_PLTOFF64LSB	0x3f	/* word64 LSB	@pltoff(S + A) */
#define	R_IA_64_FPTR64I		0x43	/* immediate64	@fptr(S + A) */
#define	R_IA_64_FPTR32MSB	0x44	/* word32 MSB	@fptr(S + A) */
#define	R_IA_64_FPTR32LSB	0x45	/* word32 LSB	@fptr(S + A) */
#define	R_IA_64_FPTR64MSB	0x46	/* word64 MSB	@fptr(S + A) */
#define	R_IA_64_FPTR64LSB	0x47	/* word64 LSB	@fptr(S + A) */
#define	R_IA_64_PCREL60B	0x48	/* immediate60 form1 S + A - P */
#define	R_IA_64_PCREL21B	0x49	/* immediate21 form1 S + A - P */
#define	R_IA_64_PCREL21M	0x4a	/* immediate21 form2 S + A - P */
#define	R_IA_64_PCREL21F	0x4b	/* immediate21 form3 S + A - P */
#define	R_IA_64_PCREL32MSB	0x4c	/* word32 MSB	S + A - P */
#define	R_IA_64_PCREL32LSB	0x4d	/* word32 LSB	S + A - P */
#define	R_IA_64_PCREL64MSB	0x4e	/* word64 MSB	S + A - P */
#define	R_IA_64_PCREL64LSB	0x4f	/* word64 LSB	S + A - P */
#define	R_IA_64_LTOFF_FPTR22	0x52	/* immediate22	@ltoff(@fptr(S + A)) */
#define	R_IA_64_LTOFF_FPTR64I	0x53	/* immediate64	@ltoff(@fptr(S + A)) */
#define	R_IA_64_LTOFF_FPTR32MSB	0x54	/* word32 MSB	@ltoff(@fptr(S + A)) */
#define	R_IA_64_LTOFF_FPTR32LSB	0x55	/* word32 LSB	@ltoff(@fptr(S + A)) */
#define	R_IA_64_LTOFF_FPTR64MSB	0x56	/* word64 MSB	@ltoff(@fptr(S + A)) */
#define	R_IA_64_LTOFF_FPTR64LSB	0x57	/* word64 LSB	@ltoff(@fptr(S + A)) */
#define	R_IA_64_SEGREL32MSB	0x5c	/* word32 MSB	@segrel(S + A) */
#define	R_IA_64_SEGREL32LSB	0x5d	/* word32 LSB	@segrel(S + A) */
#define	R_IA_64_SEGREL64MSB	0x5e	/* word64 MSB	@segrel(S + A) */
#define	R_IA_64_SEGREL64LSB	0x5f	/* word64 LSB	@segrel(S + A) */
#define	R_IA_64_SECREL32MSB	0x64	/* word32 MSB	@secrel(S + A) */
#define	R_IA_64_SECREL32LSB	0x65	/* word32 LSB	@secrel(S + A) */
#define	R_IA_64_SECREL64MSB	0x66	/* word64 MSB	@secrel(S + A) */
#define	R_IA_64_SECREL64LSB	0x67	/* word64 LSB	@secrel(S + A) */
#define	R_IA_64_REL32MSB	0x6c	/* word32 MSB	BD + A */
#define	R_IA_64_REL32LSB	0x6d	/* word32 LSB	BD + A */
#define	R_IA_64_REL64MSB	0x6e	/* word64 MSB	BD + A */
#define	R_IA_64_REL64LSB	0x6f	/* word64 LSB	BD + A */
#define	R_IA_64_LTV32MSB	0x74	/* word32 MSB	S + A */
#define	R_IA_64_LTV32LSB	0x75	/* word32 LSB	S + A */
#define	R_IA_64_LTV64MSB	0x76	/* word64 MSB	S + A */
#define	R_IA_64_LTV64LSB	0x77	/* word64 LSB	S + A */
#define	R_IA_64_PCREL21BI	0x79	/* immediate21 form1 S + A - P */
#define	R_IA_64_PCREL22		0x7a	/* immediate22	S + A - P */
#define	R_IA_64_PCREL64I	0x7b	/* immediate64	S + A - P */
#define	R_IA_64_IPLTMSB		0x80	/* function descriptor MSB special */
#define	R_IA_64_IPLTLSB		0x81	/* function descriptor LSB speciaal */
#define	R_IA_64_SUB		0x85	/* immediate64	A - S */
#define	R_IA_64_LTOFF22X	0x86	/* immediate22	special */
#define	R_IA_64_LDXMOV		0x87	/* immediate22	special */
#define	R_IA_64_TPREL14		0x91	/* imm14	@tprel(S + A) */
#define	R_IA_64_TPREL22		0x92	/* imm22	@tprel(S + A) */
#define	R_IA_64_TPREL64I	0x93	/* imm64	@tprel(S + A) */
#define	R_IA_64_TPREL64MSB	0x96	/* word64 MSB	@tprel(S + A) */
#define	R_IA_64_TPREL64LSB	0x97	/* word64 LSB	@tprel(S + A) */
#define	R_IA_64_LTOFF_TPREL22	0x9a	/* imm22	@ltoff(@tprel(S+A)) */
#define	R_IA_64_DTPMOD64MSB	0xa6	/* word64 MSB	@dtpmod(S + A) */
#define	R_IA_64_DTPMOD64LSB	0xa7	/* word64 LSB	@dtpmod(S + A) */
#define	R_IA_64_LTOFF_DTPMOD22	0xaa	/* imm22	@ltoff(@dtpmod(S+A)) */
#define	R_IA_64_DTPREL14	0xb1	/* imm14	@dtprel(S + A) */
#define	R_IA_64_DTPREL22	0xb2	/* imm22	@dtprel(S + A) */
#define	R_IA_64_DTPREL64I	0xb3	/* imm64	@dtprel(S + A) */
#define	R_IA_64_DTPREL32MSB	0xb4	/* word32 MSB	@dtprel(S + A) */
#define	R_IA_64_DTPREL32LSB	0xb5	/* word32 LSB	@dtprel(S + A) */
#define	R_IA_64_DTPREL64MSB	0xb6	/* word64 MSB	@dtprel(S + A) */
#define	R_IA_64_DTPREL64LSB	0xb7	/* word64 LSB	@dtprel(S + A) */
#define	R_IA_64_LTOFF_DTPREL22	0xba	/* imm22	@ltoff(@dtprel(S+A)) */

#define	R_MIPS_NONE	0	/* No reloc */
#define	R_MIPS_16	1	/* Direct 16 bit */
#define	R_MIPS_32	2	/* Direct 32 bit */
#define	R_MIPS_REL32	3	/* PC relative 32 bit */
#define	R_MIPS_26	4	/* Direct 26 bit shifted */
#define	R_MIPS_HI16	5	/* High 16 bit */
#define	R_MIPS_LO16	6	/* Low 16 bit */
#define	R_MIPS_GPREL16	7	/* GP relative 16 bit */
#define	R_MIPS_LITERAL	8	/* 16 bit literal entry */
#define	R_MIPS_GOT16	9	/* 16 bit GOT entry */
#define	R_MIPS_PC16	10	/* PC relative 16 bit */
#define	R_MIPS_CALL16	11	/* 16 bit GOT entry for function */
#define	R_MIPS_GPREL32	12	/* GP relative 32 bit */
#define	R_MIPS_64	18	/* Direct 64 bit */
#define	R_MIPS_GOTHI16	21	/* GOT HI 16 bit */
#define	R_MIPS_GOTLO16	22	/* GOT LO 16 bit */
#define	R_MIPS_CALLHI16 30	/* upper 16 bit GOT entry for function */
#define	R_MIPS_CALLLO16 31	/* lower 16 bit GOT entry for function */

#define	R_PPC_NONE		0	/* No relocation. */
#define	R_PPC_ADDR32		1
#define	R_PPC_ADDR24		2
#define	R_PPC_ADDR16		3
#define	R_PPC_ADDR16_LO		4
#define	R_PPC_ADDR16_HI		5
#define	R_PPC_ADDR16_HA		6
#define	R_PPC_ADDR14		7
#define	R_PPC_ADDR14_BRTAKEN	8
#define	R_PPC_ADDR14_BRNTAKEN	9
#define	R_PPC_REL24		10
#define	R_PPC_REL14		11
#define	R_PPC_REL14_BRTAKEN	12
#define	R_PPC_REL14_BRNTAKEN	13
#define	R_PPC_GOT16		14
#define	R_PPC_GOT16_LO		15
#define	R_PPC_GOT16_HI		16
#define	R_PPC_GOT16_HA		17
#define	R_PPC_PLTREL24		18
#define	R_PPC_COPY		19
#define	R_PPC_GLOB_DAT		20
#define	R_PPC_JMP_SLOT		21
#define	R_PPC_RELATIVE		22
#define	R_PPC_LOCAL24PC		23
#define	R_PPC_UADDR32		24
#define	R_PPC_UADDR16		25
#define	R_PPC_REL32		26
#define	R_PPC_PLT32		27
#define	R_PPC_PLTREL32		28
#define	R_PPC_PLT16_LO		29
#define	R_PPC_PLT16_HI		30
#define	R_PPC_PLT16_HA		31
#define	R_PPC_SDAREL16		32
#define	R_PPC_SECTOFF		33
#define	R_PPC_SECTOFF_LO	34
#define	R_PPC_SECTOFF_HI	35
#define	R_PPC_SECTOFF_HA	36

/*
 * 64-bit relocations
 */
#define	R_PPC64_ADDR64		38
#define	R_PPC64_ADDR16_HIGHER	39
#define	R_PPC64_ADDR16_HIGHERA	40
#define	R_PPC64_ADDR16_HIGHEST	41
#define	R_PPC64_ADDR16_HIGHESTA	42
#define	R_PPC64_UADDR64		43
#define	R_PPC64_REL64		44
#define	R_PPC64_PLT64		45
#define	R_PPC64_PLTREL64	46
#define	R_PPC64_TOC16		47
#define	R_PPC64_TOC16_LO	48
#define	R_PPC64_TOC16_HI	49
#define	R_PPC64_TOC16_HA	50
#define	R_PPC64_TOC		51
#define	R_PPC64_DTPMOD64	68
#define	R_PPC64_TPREL64		73
#define	R_PPC64_DTPREL64	78

/*
 * TLS relocations
 */
#define	R_PPC_TLS		67
#define	R_PPC_DTPMOD32		68
#define	R_PPC_TPREL16		69
#define	R_PPC_TPREL16_LO	70
#define	R_PPC_TPREL16_HI	71
#define	R_PPC_TPREL16_HA	72
#define	R_PPC_TPREL32		73
#define	R_PPC_DTPREL16		74
#define	R_PPC_DTPREL16_LO	75
#define	R_PPC_DTPREL16_HI	76
#define	R_PPC_DTPREL16_HA	77
#define	R_PPC_DTPREL32		78
#define	R_PPC_GOT_TLSGD16	79
#define	R_PPC_GOT_TLSGD16_LO	80
#define	R_PPC_GOT_TLSGD16_HI	81
#define	R_PPC_GOT_TLSGD16_HA	82
#define	R_PPC_GOT_TLSLD16	83
#define	R_PPC_GOT_TLSLD16_LO	84
#define	R_PPC_GOT_TLSLD16_HI	85
#define	R_PPC_GOT_TLSLD16_HA	86
#define	R_PPC_GOT_TPREL16	87
#define	R_PPC_GOT_TPREL16_LO	88
#define	R_PPC_GOT_TPREL16_HI	89
#define	R_PPC_GOT_TPREL16_HA	90

/*
 * The remaining relocs are from the Embedded ELF ABI, and are not in the
 *  SVR4 ELF ABI.
 */

#define	R_PPC_EMB_NADDR32	101
#define	R_PPC_EMB_NADDR16	102
#define	R_PPC_EMB_NADDR16_LO	103
#define	R_PPC_EMB_NADDR16_HI	104
#define	R_PPC_EMB_NADDR16_HA	105
#define	R_PPC_EMB_SDAI16	106
#define	R_PPC_EMB_SDA2I16	107
#define	R_PPC_EMB_SDA2REL	108
#define	R_PPC_EMB_SDA21		109
#define	R_PPC_EMB_MRKREF	110
#define	R_PPC_EMB_RELSEC16	111
#define	R_PPC_EMB_RELST_LO	112
#define	R_PPC_EMB_RELST_HI	113
#define	R_PPC_EMB_RELST_HA	114
#define	R_PPC_EMB_BIT_FLD	115
#define	R_PPC_EMB_RELSDA	116

#define	R_SPARC_NONE		0
#define	R_SPARC_8		1
#define	R_SPARC_16		2
#define	R_SPARC_32		3
#define	R_SPARC_DISP8		4
#define	R_SPARC_DISP16		5
#define	R_SPARC_DISP32		6
#define	R_SPARC_WDISP30		7
#define	R_SPARC_WDISP22		8
#define	R_SPARC_HI22		9
#define	R_SPARC_22		10
#define	R_SPARC_13		11
#define	R_SPARC_LO10		12
#define	R_SPARC_GOT10		13
#define	R_SPARC_GOT13		14
#define	R_SPARC_GOT22		15
#define	R_SPARC_PC10		16
#define	R_SPARC_PC22		17
#define	R_SPARC_WPLT30		18
#define	R_SPARC_COPY		19
#define	R_SPARC_GLOB_DAT	20
#define	R_SPARC_JMP_SLOT	21
#define	R_SPARC_RELATIVE	22
#define	R_SPARC_UA32		23
#define	R_SPARC_PLT32		24
#define	R_SPARC_HIPLT22		25
#define	R_SPARC_LOPLT10		26
#define	R_SPARC_PCPLT32		27
#define	R_SPARC_PCPLT22		28
#define	R_SPARC_PCPLT10		29
#define	R_SPARC_10		30
#define	R_SPARC_11		31
#define	R_SPARC_64		32
#define	R_SPARC_OLO10		33
#define	R_SPARC_HH22		34
#define	R_SPARC_HM10		35
#define	R_SPARC_LM22		36
#define	R_SPARC_PC_HH22		37
#define	R_SPARC_PC_HM10		38
#define	R_SPARC_PC_LM22		39
#define	R_SPARC_WDISP16		40
#define	R_SPARC_WDISP19		41
#define	R_SPARC_GLOB_JMP	42
#define	R_SPARC_7		43
#define	R_SPARC_5		44
#define	R_SPARC_6		45
#define	R_SPARC_DISP64		46
#define	R_SPARC_PLT64		47
#define	R_SPARC_HIX22		48
#define	R_SPARC_LOX10		49
#define	R_SPARC_H44		50
#define	R_SPARC_M44		51
#define	R_SPARC_L44		52
#define	R_SPARC_REGISTER	53
#define	R_SPARC_UA64		54
#define	R_SPARC_UA16		55
#define	R_SPARC_TLS_GD_HI22	56
#define	R_SPARC_TLS_GD_LO10	57
#define	R_SPARC_TLS_GD_ADD	58
#define	R_SPARC_TLS_GD_CALL	59
#define	R_SPARC_TLS_LDM_HI22	60
#define	R_SPARC_TLS_LDM_LO10	61
#define	R_SPARC_TLS_LDM_ADD	62
#define	R_SPARC_TLS_LDM_CALL	63
#define	R_SPARC_TLS_LDO_HIX22	64
#define	R_SPARC_TLS_LDO_LOX10	65
#define	R_SPARC_TLS_LDO_ADD	66
#define	R_SPARC_TLS_IE_HI22	67
#define	R_SPARC_TLS_IE_LO10	68
#define	R_SPARC_TLS_IE_LD	69
#define	R_SPARC_TLS_IE_LDX	70
#define	R_SPARC_TLS_IE_ADD	71
#define	R_SPARC_TLS_LE_HIX22	72
#define	R_SPARC_TLS_LE_LOX10	73
#define	R_SPARC_TLS_DTPMOD32	74
#define	R_SPARC_TLS_DTPMOD64	75
#define	R_SPARC_TLS_DTPOFF32	76
#define	R_SPARC_TLS_DTPOFF64	77
#define	R_SPARC_TLS_TPOFF32	78
#define	R_SPARC_TLS_TPOFF64	79

#define	R_X86_64_NONE		0	/* No relocation. */
#define	R_X86_64_64		1	/* Add 64 bit symbol value. */
#define	R_X86_64_PC32		2	/* PC-relative 32 bit signed sym value. */
#define	R_X86_64_GOT32		3	/* PC-relative 32 bit GOT offset. */
#define	R_X86_64_PLT32		4	/* PC-relative 32 bit PLT offset. */
#define	R_X86_64_COPY		5	/* Copy data from shared object. */
#define	R_X86_64_GLOB_DAT	6	/* Set GOT entry to data address. */
#define	R_X86_64_JMP_SLOT	7	/* Set GOT entry to code address. */
#define	R_X86_64_RELATIVE	8	/* Add load address of shared object. */
#define	R_X86_64_GOTPCREL	9	/* Add 32 bit signed pcrel offset to GOT. */
#define	R_X86_64_32		10	/* Add 32 bit zero extended symbol value */
#define	R_X86_64_32S		11	/* Add 32 bit sign extended symbol value */
#define	R_X86_64_16		12	/* Add 16 bit zero extended symbol value */
#define	R_X86_64_PC16		13	/* Add 16 bit signed extended pc relative symbol value */
#define	R_X86_64_8		14	/* Add 8 bit zero extended symbol value */
#define	R_X86_64_PC8		15	/* Add 8 bit signed extended pc relative symbol value */
#define	R_X86_64_DTPMOD64	16	/* ID of module containing symbol */
#define	R_X86_64_DTPOFF64	17	/* Offset in TLS block */
#define	R_X86_64_TPOFF64	18	/* Offset in static TLS block */
#define	R_X86_64_TLSGD		19	/* PC relative offset to GD GOT entry */
#define	R_X86_64_TLSLD		20	/* PC relative offset to LD GOT entry */
#define	R_X86_64_DTPOFF32	21	/* Offset in TLS block */
#define	R_X86_64_GOTTPOFF	22	/* PC relative offset to IE GOT entry */
#define	R_X86_64_TPOFF32	23	/* Offset in static TLS block */
#define	R_X86_64_IRELATIVE	37

#define NT_GNU_BUILD_ID     3   /* Note type for .note.gnu.build-id */

#endif /* !_SYS_ELF_COMMON_H_ */


================================================
FILE: src/filepath.c
================================================
#include <sys/stat.h>

#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#include "types.h"
#include "filepath.h"

void os_strncpy(oschar_t *dst, const char *src, size_t size) {
#ifdef _WIN32
    MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size);
#else
    strncpy(dst, src, size);
#endif
}

void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size) {
#ifdef _WIN32
    WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, size, NULL, NULL);
#else
    strncpy(dst, src, size);
#endif
}

int os_makedir(const oschar_t *dir) {
#ifdef _WIN32
    return _wmkdir(dir);
#else
    return mkdir(dir, 0777);
#endif
}

int os_rmdir(const oschar_t *dir) {
#ifdef _WIN32
    return _wrmdir(dir);
#else
    return remove(dir);
#endif
}

void filepath_update(filepath_t *fpath) {
    memset(fpath->os_path, 0, MAX_SWITCHPATH * sizeof(oschar_t));
    os_strncpy(fpath->os_path, fpath->char_path, MAX_SWITCHPATH);
}

void filepath_init(filepath_t *fpath) {
    fpath->valid = VALIDITY_INVALID;
}

void filepath_copy(filepath_t *fpath, filepath_t *copy) {
    if (copy != NULL && copy->valid == VALIDITY_VALID)
        memcpy(fpath, copy, sizeof(filepath_t));
    else
        memset(fpath, 0, sizeof(filepath_t));
}

void filepath_os_append(filepath_t *fpath, oschar_t *path) {
    char tmppath[MAX_SWITCHPATH];
    if (fpath->valid == VALIDITY_INVALID)
        return;
    
    memset(tmppath, 0, MAX_SWITCHPATH);
    
    os_strncpy_to_char(tmppath, path, MAX_SWITCHPATH);
    strcat(fpath->char_path, OS_PATH_SEPARATOR);
    strcat(fpath->char_path, tmppath);
    filepath_update(fpath);
}

void filepath_append(filepath_t *fpath, const char *format, ...) {
    char tmppath[MAX_SWITCHPATH];
    va_list args;

    if (fpath->valid == VALIDITY_INVALID)
        return;

    memset(tmppath, 0, MAX_SWITCHPATH);

    va_start(args, format);
    vsnprintf(tmppath, sizeof(tmppath), format, args);
    va_end(args);

    strcat(fpath->char_path, OS_PATH_SEPARATOR);
    strcat(fpath->char_path, tmppath);
    filepath_update(fpath);
}

void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...) {
    char tmppath[MAX_SWITCHPATH];
    va_list args;

    if (fpath->valid == VALIDITY_INVALID || n > MAX_SWITCHPATH)
        return;

    memset(tmppath, 0, MAX_SWITCHPATH);

    va_start(args, format);
    vsnprintf(tmppath, sizeof(tmppath), format, args);
    va_end(args);

    strcat(fpath->char_path, OS_PATH_SEPARATOR);
    strncat(fpath->char_path, tmppath, n);
    filepath_update(fpath);
}

void filepath_set(filepath_t *fpath, const char *path) {
    if (strlen(path) < MAX_SWITCHPATH) {
        fpath->valid = VALIDITY_VALID;
        memset(fpath->char_path, 0, MAX_SWITCHPATH);
        strncpy(fpath->char_path, path, MAX_SWITCHPATH);
        filepath_update(fpath);
    } else {
        fpath->valid = VALIDITY_INVALID;
    }
}

oschar_t *filepath_get(filepath_t *fpath) {
    if (fpath->valid == VALIDITY_INVALID)
        return NULL;
    else
        return fpath->os_path;
}


================================================
FILE: src/filepath.h
================================================
#pragma once

#include "types.h"
#include <dirent.h>
#ifdef _WIN32
#include <direct.h>
#include <wchar.h>
#endif

#define MAX_SWITCHPATH 0x300

typedef enum {
    VALIDITY_UNCHECKED = 0,
    VALIDITY_INVALID,
    VALIDITY_VALID
} validity_t;

#ifdef _MSC_VER
inline int fseeko64(FILE *__stream, long long __off, int __whence)
{
    return _fseeki64(__stream, __off, __whence);
}
#else
    /* off_t is 64-bit with large file support */
    #define fseeko64 fseek
#endif

#ifdef _WIN32
typedef wchar_t oschar_t; /* utf-16 */
typedef _WDIR osdir_t;
typedef struct _wdirent osdirent_t;
typedef struct _stati64 os_stat64_t;

#define os_fopen _wfopen
#define os_opendir _wopendir
#define os_closedir _wclosedir
#define os_readdir _wreaddir
#define os_stat _wstati64
#define os_fclose fclose

#define OS_MODE_READ L"rb"
#define OS_MODE_WRITE L"wb"
#define OS_MODE_EDIT L"rb+"
#else
typedef char oschar_t; /* utf-8 */
typedef DIR osdir_t;
typedef struct dirent osdirent_t;
typedef struct stat os_stat64_t;

#define os_fopen fopen
#define os_opendir opendir
#define os_closedir closedir
#define os_readdir readdir
#define os_stat stat
#define os_fclose fclose

#define OS_MODE_READ "rb"
#define OS_MODE_WRITE "wb"
#define OS_MODE_EDIT "rb+"
#endif

#define OS_PATH_SEPARATOR "/"

typedef struct filepath {
    char char_path[MAX_SWITCHPATH];
    oschar_t os_path[MAX_SWITCHPATH];
    validity_t valid;
} filepath_t;

void os_strncpy(oschar_t *dst, const char *src, size_t size);
void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size);
int os_makedir(const oschar_t *dir);
int os_rmdir(const oschar_t *dir);

void filepath_init(filepath_t *fpath);
void filepath_copy(filepath_t *fpath, filepath_t *copy);
void filepath_os_append(filepath_t *fpath, oschar_t *path);
void filepath_append(filepath_t *fpath, const char *format, ...);
void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format, ...);
void filepath_set(filepath_t *fpath, const char *path);
oschar_t *filepath_get(filepath_t *fpath);


================================================
FILE: src/nacptool.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>

typedef uint64_t u64;
typedef uint32_t u32;
typedef uint8_t u8;

typedef struct {
    char name[0x200];
    char author[0x100];
} NacpLanguageEntry;

typedef struct {
    NacpLanguageEntry lang[12];
    NacpLanguageEntry lang_unk[4];//?

    u8  x3000_unk[0x24];////Normally all-zero?
    u32 x3024_unk;
    u32 x3028_unk;
    u32 x302C_unk;
    u32 x3030_unk;
    u32 x3034_unk;
    u64 titleid0;

    u8 x3040_unk[0x20];
    char version[0x10];

    u64 titleid_dlcbase;
    u64 titleid1;

    u32 x3080_unk;
    u32 x3084_unk;
    u32 x3088_unk;
    u8 x308C_unk[0x24];//zeros?

    u64 titleid2;
    u64 titleids[7];//"Array of application titleIDs, normally the same as the above app-titleIDs. Only set for game-updates?"

    u32 x30F0_unk;
    u32 x30F4_unk;

    u64 titleid3;//"Application titleID. Only set for game-updates?"

    char bcat_passphrase[0x40];
    u8 x3140_unk[0xEC0];//Normally all-zero?
} NacpStruct;

int main(int argc, char* argv[]) {
    if (argc < 6 || strncmp(argv[1], "--create", 8)!=0) {
        fprintf(stderr, "%s --create <name> <author> <version> <outfile> [options]\n\n", argv[0]);
        fprintf(stderr, "FLAGS:\n");
        fprintf(stderr, "--create : Create control.nacp for use with Switch homebre
Download .txt
gitextract_cljm8jeo/

├── .gitignore
├── AUTHORS
├── COPYING
├── ChangeLog
├── Makefile.am
├── NEWS
├── README
├── autogen.sh
├── configure.ac
└── src/
    ├── blz.c
    ├── blz.h
    ├── cJSON.c
    ├── cJSON.h
    ├── elf2kip.c
    ├── elf2nro.c
    ├── elf2nso.c
    ├── elf64.h
    ├── elf_common.h
    ├── filepath.c
    ├── filepath.h
    ├── nacptool.c
    ├── npdmtool.c
    ├── nxlink.c
    ├── romfs.c
    ├── romfs.h
    ├── sha256.c
    ├── sha256.h
    └── types.h
Download .txt
SYMBOL INDEX (278 symbols across 18 files)

FILE: src/blz.c
  function u8 (line 58) | u8 *Memory(int length, int size) {
  function BLZ_Decode (line 68) | void BLZ_Decode(char *filename) {
  function u8 (line 146) | u8 *Load(char *filename, u32 *length, int min, int max) {
  function u8 (line 166) | u8* BLZ_Encode(char *filename, u32* pak_len, int mode) {
  function u8 (line 186) | u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best) {
  function BLZ_Invert (line 324) | void BLZ_Invert(u8 *buffer, int length) {

FILE: src/blz.h
  type u64 (line 5) | typedef uint64_t u64;
  type u32 (line 6) | typedef uint32_t u32;
  type u16 (line 7) | typedef uint16_t u16;
  type u8 (line 8) | typedef uint8_t u8;

FILE: src/cJSON.c
  type error (line 65) | typedef struct {
  function cJSON_GetErrorPtr (line 71) | CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
  function cJSON_GetStringValue (line 76) | CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) {
  function cJSON_Version (line 89) | CJSON_PUBLIC(const char*) cJSON_Version(void)
  function case_insensitive_strcmp (line 98) | static int case_insensitive_strcmp(const unsigned char *string1, const u...
  type internal_hooks (line 121) | typedef struct internal_hooks
  function internal_free (line 134) | static void internal_free(void *pointer)
  function cJSON_InitHooks (line 171) | CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
  function cJSON (line 203) | static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
  function cJSON_Delete (line 215) | CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
  function get_decimal_point (line 239) | static unsigned char get_decimal_point(void)
  type parse_buffer (line 249) | typedef struct
  function cJSON_bool (line 267) | static cJSON_bool parse_number(cJSON * const item, parse_buffer * const ...
  function cJSON_SetNumberHelper (line 344) | CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
  type printbuffer (line 362) | typedef struct
  function update_offset (line 462) | static void update_offset(printbuffer * const buffer)
  function cJSON_bool (line 475) | static cJSON_bool print_number(const cJSON * const item, printbuffer * c...
  function parse_hex4 (line 541) | static unsigned parse_hex4(const unsigned char * const input)
  function utf16_literal_to_utf8 (line 578) | static unsigned char utf16_literal_to_utf8(const unsigned char * const i...
  function cJSON_bool (line 699) | static cJSON_bool parse_string(cJSON * const item, parse_buffer * const ...
  function cJSON_bool (line 828) | static cJSON_bool print_string_ptr(const unsigned char * const input, pr...
  function cJSON_bool (line 950) | static cJSON_bool print_string(const cJSON * const item, printbuffer * c...
  function parse_buffer (line 964) | static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
  function parse_buffer (line 985) | static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
  function cJSON_ParseWithOpts (line 1001) | CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char ...
  function cJSON_Parse (line 1081) | CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
  function cJSON_Print (line 1153) | CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
  function cJSON_PrintUnformatted (line 1158) | CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
  function cJSON_PrintBuffered (line 1163) | CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffe...
  function cJSON_PrintPreallocated (line 1193) | CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf,...
  function cJSON_bool (line 1213) | static cJSON_bool parse_value(cJSON * const item, parse_buffer * const i...
  function cJSON_bool (line 1268) | static cJSON_bool print_value(const cJSON * const item, printbuffer * co...
  function cJSON_bool (line 1342) | static cJSON_bool parse_array(cJSON * const item, parse_buffer * const i...
  function cJSON_bool (line 1436) | static cJSON_bool print_array(const cJSON * const item, printbuffer * co...
  function cJSON_bool (line 1498) | static cJSON_bool parse_object(cJSON * const item, parse_buffer * const ...
  function cJSON_bool (line 1607) | static cJSON_bool print_object(const cJSON * const item, printbuffer * c...
  function cJSON_GetArraySize (line 1721) | CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
  function cJSON (line 1744) | static cJSON* get_array_item(const cJSON *array, size_t index)
  function cJSON_GetArrayItem (line 1763) | CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
  function cJSON (line 1773) | static cJSON *get_object_item(const cJSON * const object, const char * c...
  function cJSON_GetObjectItem (line 1801) | CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, co...
  function cJSON_GetObjectItemCaseSensitive (line 1806) | CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * con...
  function cJSON_HasObjectItem (line 1811) | CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const ...
  function suffix_object (line 1817) | static void suffix_object(cJSON *prev, cJSON *item)
  function cJSON (line 1824) | static cJSON *create_reference(const cJSON *item, const internal_hooks *...
  function cJSON_bool (line 1845) | static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
  function cJSON_AddItemToArray (line 1875) | CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item)
  function cJSON_bool (line 1896) | static cJSON_bool add_item_to_object(cJSON * const object, const char * ...
  function cJSON_AddItemToObject (line 1933) | CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *stri...
  function cJSON_AddItemToObjectCS (line 1939) | CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *st...
  function cJSON_AddItemReferenceToArray (line 1944) | CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
  function cJSON_AddItemReferenceToObject (line 1954) | CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const c...
  function cJSON_AddNullToObject (line 1964) | CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const c...
  function cJSON_AddTrueToObject (line 1976) | CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const c...
  function cJSON_AddFalseToObject (line 1988) | CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const ...
  function cJSON_AddBoolToObject (line 2000) | CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const c...
  function cJSON_AddNumberToObject (line 2012) | CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const...
  function cJSON_AddStringToObject (line 2024) | CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const...
  function cJSON_AddRawToObject (line 2036) | CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const ch...
  function cJSON_AddObjectToObject (line 2048) | CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const...
  function cJSON_AddArrayToObject (line 2060) | CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const ...
  function cJSON_DetachItemViaPointer (line 2072) | CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * ...
  function cJSON_DetachItemFromArray (line 2102) | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
  function cJSON_DeleteItemFromArray (line 2112) | CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
  function cJSON_DetachItemFromObject (line 2117) | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const ch...
  function cJSON_DetachItemFromObjectCaseSensitive (line 2124) | CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *obj...
  function cJSON_DeleteItemFromObject (line 2131) | CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char ...
  function cJSON_DeleteItemFromObjectCaseSensitive (line 2136) | CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object...
  function cJSON_InsertItemInArray (line 2142) | CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSO...
  function cJSON_ReplaceItemViaPointer (line 2171) | CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const paren...
  function cJSON_ReplaceItemInArray (line 2206) | CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJS...
  function cJSON_bool (line 2216) | static cJSON_bool replace_item_in_object(cJSON *object, const char *stri...
  function cJSON_ReplaceItemInObject (line 2236) | CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *...
  function cJSON_ReplaceItemInObjectCaseSensitive (line 2241) | CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,...
  function cJSON_CreateNull (line 2247) | CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
  function cJSON_CreateTrue (line 2258) | CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
  function cJSON_CreateFalse (line 2269) | CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
  function cJSON_CreateBool (line 2280) | CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b)
  function cJSON_CreateNumber (line 2291) | CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
  function cJSON_CreateString (line 2317) | CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
  function cJSON_CreateStringReference (line 2334) | CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
  function cJSON_CreateObjectReference (line 2346) | CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
  function cJSON_CreateArrayReference (line 2357) | CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
  function cJSON_CreateRaw (line 2367) | CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
  function cJSON_CreateArray (line 2384) | CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
  function cJSON_CreateObject (line 2395) | CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
  function cJSON_CreateIntArray (line 2407) | CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
  function cJSON_CreateFloatArray (line 2442) | CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int c...
  function cJSON_CreateDoubleArray (line 2478) | CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int...
  function cJSON_CreateStringArray (line 2514) | CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int ...
  function cJSON_Duplicate (line 2551) | CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recu...
  function cJSON_Minify (line 2630) | CJSON_PUBLIC(void) cJSON_Minify(char *json)
  function cJSON_IsInvalid (line 2700) | CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
  function cJSON_IsFalse (line 2710) | CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
  function cJSON_IsTrue (line 2720) | CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
  function cJSON_IsBool (line 2731) | CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
  function cJSON_IsNull (line 2740) | CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
  function cJSON_IsNumber (line 2750) | CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
  function cJSON_IsString (line 2760) | CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
  function cJSON_IsArray (line 2770) | CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
  function cJSON_IsObject (line 2780) | CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
  function cJSON_IsRaw (line 2790) | CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
  function cJSON_Compare (line 2800) | CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSO...
  function cJSON_malloc (line 2925) | CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
  function cJSON_free (line 2930) | CJSON_PUBLIC(void) cJSON_free(void *object)

FILE: src/cJSON.h
  type cJSON (line 53) | typedef struct cJSON
  type cJSON_Hooks (line 75) | typedef struct cJSON_Hooks
  type cJSON_bool (line 81) | typedef int cJSON_bool;

FILE: src/elf2kip.c
  type KipSegment (line 12) | typedef struct {
  type KipHeader (line 19) | typedef struct {
  function cJSON_GetString (line 58) | int cJSON_GetString(const cJSON *obj, const char *field, const char **ou...
  function cJSON_GetU8 (line 69) | int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
  function cJSON_GetU16 (line 80) | int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
  function cJSON_GetU16FromObjectValue (line 91) | int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
  function cJSON_GetBoolean (line 101) | int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
  function cJSON_GetBooleanOptional (line 119) | int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *o...
  function cJSON_GetU64 (line 137) | int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
  function cJSON_GetU64FromObjectValue (line 163) | int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
  function cJSON_GetU32 (line 188) | int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
  function ParseKipConfiguration (line 214) | int ParseKipConfiguration(const char *json, KipHeader *kip_hdr) {
  function main (line 589) | int main(int argc, char* argv[]) {

FILE: src/elf2nro.c
  type NsoSegment (line 11) | typedef struct {
  type NroStart (line 16) | typedef struct {
  type NroHeader (line 22) | typedef struct {
  type AssetSection (line 34) | typedef struct {
  type AssetHeader (line 39) | typedef struct {
  function main (line 73) | int main(int argc, char* argv[]) {

FILE: src/elf2nso.c
  type u64 (line 10) | typedef uint64_t u64;
  type u32 (line 11) | typedef uint32_t u32;
  type u8 (line 12) | typedef uint8_t u8;
  type NsoSegment (line 14) | typedef struct {
  type u8 (line 21) | typedef u8 Sha2Hash[0x20];
  type NsoHeader (line 23) | typedef struct {
  function main (line 63) | int main(int argc, char* argv[]) {

FILE: src/elf64.h
  type Elf64_Addr (line 38) | typedef uint64_t	Elf64_Addr;
  type Elf64_Half (line 39) | typedef uint16_t	Elf64_Half;
  type Elf64_Off (line 40) | typedef uint64_t	Elf64_Off;
  type Elf64_Sword (line 41) | typedef int32_t		Elf64_Sword;
  type Elf64_Sxword (line 42) | typedef int64_t		Elf64_Sxword;
  type Elf64_Word (line 43) | typedef uint32_t	Elf64_Word;
  type Elf64_Lword (line 44) | typedef uint64_t	Elf64_Lword;
  type Elf64_Xword (line 45) | typedef uint64_t	Elf64_Xword;
  type Elf64_Word (line 54) | typedef Elf64_Word	Elf64_Hashelt;
  type Elf64_Xword (line 57) | typedef Elf64_Xword	Elf64_Size;
  type Elf64_Sxword (line 58) | typedef Elf64_Sxword	Elf64_Ssize;
  type Elf64_Ehdr (line 64) | typedef struct {
  type Elf64_Shdr (line 85) | typedef struct {
  type Elf64_Phdr (line 103) | typedef struct {
  type Elf64_Dyn (line 118) | typedef struct {
  type Elf64_Rel (line 131) | typedef struct {
  type Elf64_Rela (line 137) | typedef struct {
  type Elf_Note (line 158) | typedef Elf_Note Elf64_Nhdr;
  type Elf64_Move (line 163) | typedef struct {
  type Elf64_Cap (line 178) | typedef struct {
  type Elf64_Sym (line 190) | typedef struct {
  type Elf64_Verdef (line 210) | typedef struct {
  type Elf64_Verdaux (line 220) | typedef struct {
  type Elf64_Verneed (line 225) | typedef struct {
  type Elf64_Vernaux (line 233) | typedef struct {
  type Elf64_Half (line 241) | typedef Elf64_Half Elf64_Versym;
  type Elf64_Syminfo (line 243) | typedef struct {

FILE: src/elf_common.h
  type Elf_Note (line 46) | typedef struct {
  type Elf_GNU_Hash_Header (line 56) | typedef struct {

FILE: src/filepath.c
  function os_strncpy (line 15) | void os_strncpy(oschar_t *dst, const char *src, size_t size) {
  function os_strncpy_to_char (line 23) | void os_strncpy_to_char(char *dst, const oschar_t *src, size_t size) {
  function os_makedir (line 31) | int os_makedir(const oschar_t *dir) {
  function os_rmdir (line 39) | int os_rmdir(const oschar_t *dir) {
  function filepath_update (line 47) | void filepath_update(filepath_t *fpath) {
  function filepath_init (line 52) | void filepath_init(filepath_t *fpath) {
  function filepath_copy (line 56) | void filepath_copy(filepath_t *fpath, filepath_t *copy) {
  function filepath_os_append (line 63) | void filepath_os_append(filepath_t *fpath, oschar_t *path) {
  function filepath_append (line 76) | void filepath_append(filepath_t *fpath, const char *format, ...) {
  function filepath_append_n (line 94) | void filepath_append_n(filepath_t *fpath, uint32_t n, const char *format...
  function filepath_set (line 112) | void filepath_set(filepath_t *fpath, const char *path) {
  function oschar_t (line 123) | oschar_t *filepath_get(filepath_t *fpath) {

FILE: src/filepath.h
  type validity_t (line 12) | typedef enum {
  function fseeko64 (line 19) | inline int fseeko64(FILE *__stream, long long __off, int __whence)
  type wchar_t (line 29) | typedef wchar_t oschar_t;
  type _WDIR (line 30) | typedef _WDIR osdir_t;
  type osdirent_t (line 31) | typedef struct _wdirent osdirent_t;
  type os_stat64_t (line 32) | typedef struct _stati64 os_stat64_t;
  type oschar_t (line 45) | typedef char oschar_t;
  type DIR (line 46) | typedef DIR osdir_t;
  type osdirent_t (line 47) | typedef struct dirent osdirent_t;
  type os_stat64_t (line 48) | typedef struct stat os_stat64_t;
  type filepath_t (line 64) | typedef struct filepath {

FILE: src/nacptool.c
  type u64 (line 7) | typedef uint64_t u64;
  type u32 (line 8) | typedef uint32_t u32;
  type u8 (line 9) | typedef uint8_t u8;
  type NacpLanguageEntry (line 11) | typedef struct {
  type NacpStruct (line 16) | typedef struct {
  function main (line 51) | int main(int argc, char* argv[]) {

FILE: src/npdmtool.c
  type u64 (line 10) | typedef uint64_t u64;
  type u32 (line 11) | typedef uint32_t u32;
  type u16 (line 12) | typedef uint16_t u16;
  type u8 (line 13) | typedef uint8_t u8;
  type FilesystemAccessControl (line 21) | typedef struct {
  type FilesystemAccessHeader (line 35) | typedef struct {
  type NpdmAci0 (line 45) | typedef struct {
  type NpdmAcid (line 59) | typedef struct {
  type NpdmHeader (line 77) | typedef struct {
  function cJSON_GetString (line 125) | int cJSON_GetString(const cJSON *obj, const char *field, const char **ou...
  function cJSON_GetU8 (line 136) | int cJSON_GetU8(const cJSON *obj, const char *field, u8 *out) {
  function cJSON_GetU16 (line 147) | int cJSON_GetU16(const cJSON *obj, const char *field, u16 *out) {
  function cJSON_GetU16FromObjectValue (line 158) | int cJSON_GetU16FromObjectValue(const cJSON *config, u16 *out) {
  function cJSON_GetBoolean (line 168) | int cJSON_GetBoolean(const cJSON *obj, const char *field, int *out) {
  function cJSON_GetBooleanOptional (line 186) | int cJSON_GetBooleanOptional(const cJSON *obj, const char *field, int *o...
  function cJSON_GetU64 (line 203) | int cJSON_GetU64(const cJSON *obj, const char *field, u64 *out) {
  function cJSON_GetU32 (line 229) | int cJSON_GetU32(const cJSON *obj, const char *field, u32 *out) {
  function cJSON_GetU64FromObjectValue (line 255) | int cJSON_GetU64FromObjectValue(const cJSON *config, u64 *out) {
  function CreateNpdm (line 280) | int CreateNpdm(const char *json, void **dst, u32 *dst_size) {
  function main (line 874) | int main(int argc, char* argv[]) {

FILE: src/nxlink.c
  type socklen_t (line 22) | typedef int socklen_t;
  type in_addr_t (line 23) | typedef uint32_t in_addr_t;
  function shutdownSocket (line 47) | static void shutdownSocket(int socket, int flags) {
  function setSocketNonblocking (line 55) | static int setSocketNonblocking(int sock) {
  function socketError (line 78) | static int socketError(const char *msg) {
  function pollSocket (line 102) | int pollSocket(int fd, int events, int timeout) {
  function findSwitch (line 135) | static struct in_addr findSwitch(int retries) {
  function sendData (line 194) | static int sendData(int sock, int sendsize, void *buffer) {
  function recvData (line 218) | static int recvData(int sock, void *buffer, int size, int flags) {
  function sendInt32LE (line 244) | static int sendInt32LE(int socket, uint32_t size) {
  function recvInt32LE (line 256) | static int recvInt32LE(int socket, int32_t *data) {
  function sendNROFile (line 273) | static int sendNROFile(in_addr_t nxaddr, char *name, size_t filesize, FI...
  function showHelp (line 420) | static void showHelp() {
  function addExtraArgs (line 434) | static int addExtraArgs(int len, char *buf, char *extra_args) {
  function win32_socket_cleanup (line 480) | static void win32_socket_cleanup(void) {
  function main (line 486) | int main(int argc, char **argv) {

FILE: src/romfs.c
  type romfs_fent_ctx (line 14) | struct romfs_fent_ctx
  type romfs_dirent_ctx_t (line 16) | typedef struct romfs_dirent_ctx {
  type romfs_fent_ctx_t (line 27) | typedef struct romfs_fent_ctx {
  type romfs_ctx_t (line 38) | typedef struct {
  type romfs_header_t (line 49) | typedef struct {
  type romfs_direntry_t (line 62) | typedef struct {
  type romfs_fentry_t (line 72) | typedef struct {
  function romfs_direntry_t (line 85) | romfs_direntry_t *romfs_get_direntry(romfs_direntry_t *directories, uint...
  function romfs_fentry_t (line 89) | romfs_fentry_t *romfs_get_fentry(romfs_fentry_t *files, uint32_t offset) {
  function calc_path_hash (line 93) | uint32_t calc_path_hash(uint32_t parent, const unsigned char *path, uint...
  function align (line 103) | uint32_t align(uint32_t offset, uint32_t alignment) {
  function align64 (line 109) | uint64_t align64(uint64_t offset, uint64_t alignment) {
  function romfs_get_hash_table_count (line 115) | uint32_t romfs_get_hash_table_count(uint32_t num_entries) {
  function romfs_visit_dir (line 128) | void romfs_visit_dir(romfs_dirent_ctx_t *parent, romfs_ctx_t *romfs_ctx) {
  function build_romfs_into_file (line 285) | size_t build_romfs_into_file(filepath_t *in_dirpath, FILE *f_out, off_t ...
  function build_romfs (line 525) | size_t build_romfs(filepath_t *in_dirpath, filepath_t *out_romfspath) {
  function build_romfs_by_paths (line 539) | size_t build_romfs_by_paths(char *dir, char *out_fn) {
  function build_romfs_by_path_into_file (line 552) | size_t build_romfs_by_path_into_file(char *dir, FILE *f_out, off_t offse...

FILE: src/sha256.c
  function sha256_transform (line 44) | void sha256_transform(SHA256_CTX *ctx, const BYTE data[])
  function sha256_init (line 85) | void sha256_init(SHA256_CTX *ctx)
  function sha256_update (line 99) | void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len)
  function sha256_final (line 114) | void sha256_final(SHA256_CTX *ctx, BYTE hash[])

FILE: src/sha256.h
  type BYTE (line 19) | typedef unsigned char BYTE;
  type WORD (line 20) | typedef unsigned int  WORD;
  type SHA256_CTX (line 22) | typedef struct {

FILE: src/types.h
  type dword_t (line 4) | typedef uint64_t dword_t;
  type word_t (line 5) | typedef uint32_t word_t;
  type hword_t (line 6) | typedef uint16_t hword_t;
  type byte_t (line 7) | typedef uint8_t byte_t;
  type dlong_t (line 8) | typedef int64_t dlong_t;
  type long_t (line 9) | typedef int32_t long_t;
  type short_t (line 10) | typedef int16_t short_t;
  type char_t (line 11) | typedef int8_t char_t;
  type u64 (line 12) | typedef uint64_t u64;
  type u32 (line 13) | typedef uint32_t u32;
  type u16 (line 14) | typedef uint16_t u16;
  type u8 (line 15) | typedef uint8_t u8;
  function __local_bswap16 (line 19) | static inline uint16_t __local_bswap16(uint16_t x) {
  function __local_bswap32 (line 24) | static inline uint32_t __local_bswap32(uint32_t x) {
  function __local_bswap64 (line 31) | static inline uint64_t __local_bswap64(uint64_t x)
Condensed preview — 28 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (290K chars).
[
  {
    "path": ".gitignore",
    "chars": 263,
    "preview": "build*\nINSTALL\nMakefile.in\naclocal.m4\nautom4te.cache\nconfig.guess\nconfig.sub\nconfigure\ndepcomp\ninstall-sh\nmissing\ncompil"
  },
  {
    "path": "AUTHORS",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "COPYING",
    "chars": 726,
    "preview": "Copyright 2017 libnx Authors\n\nPermission to use, copy, modify, and/or distribute this software for any purpose with or w"
  },
  {
    "path": "ChangeLog",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Makefile.am",
    "chars": 969,
    "preview": "# Makefile.am -- Process this file with automake to produce Makefile.in\nbin_PROGRAMS = elf2nso elf2nro elf2kip build_pfs"
  },
  {
    "path": "NEWS",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "README",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "autogen.sh",
    "chars": 43,
    "preview": "aclocal\nautoconf\nautomake --add-missing -c\n"
  },
  {
    "path": "configure.ac",
    "chars": 942,
    "preview": "#                                               -*- Autoconf -*-\n# Process this file with autoconf to produce a configur"
  },
  {
    "path": "src/blz.c",
    "chars": 10965,
    "preview": "/*----------------------------------------------------------------------------*/\n/*--  blz.c - Bottom LZ coding for Nint"
  },
  {
    "path": "src/blz.h",
    "chars": 283,
    "preview": "#pragma once\n\n#include <stdint.h>\n\ntypedef uint64_t u64;\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;"
  },
  {
    "path": "src/cJSON.c",
    "chars": 73211,
    "preview": "/*\n  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors\n\n  Permission is hereby granted, free of charge, to any "
  },
  {
    "path": "src/cJSON.h",
    "chars": 14566,
    "preview": "/*\n  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors\n\n  Permission is hereby granted, free of charge, to any "
  },
  {
    "path": "src/elf2kip.c",
    "chars": 24798,
    "preview": "// Copyright 2018 SciresM\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <errno"
  },
  {
    "path": "src/elf2nro.c",
    "chars": 8757,
    "preview": "// Copyright 2017 plutoo\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <lz4.h>"
  },
  {
    "path": "src/elf2nso.c",
    "chars": 5186,
    "preview": "// Copyright 2017 plutoo\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <lz4.h>"
  },
  {
    "path": "src/elf64.h",
    "chars": 7479,
    "preview": "/*-\n * Copyright (c) 1996-1998 John D. Polstra.\n * All rights reserved.\n *\n * Redistribution and use in source and binar"
  },
  {
    "path": "src/elf_common.h",
    "chars": 42908,
    "preview": "/*-\n * Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien\n * Copyright (c) 1998 John D. Polstra.\n * All rights reser"
  },
  {
    "path": "src/filepath.c",
    "chars": 3078,
    "preview": "#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_"
  },
  {
    "path": "src/filepath.h",
    "chars": 2014,
    "preview": "#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#defin"
  },
  {
    "path": "src/nacptool.c",
    "chars": 3226,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <inttypes.h>\n\ntypedef uint64_t u"
  },
  {
    "path": "src/npdmtool.c",
    "chars": 30653,
    "preview": "// Copyright 2018 SciresM\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <errno"
  },
  {
    "path": "src/nxlink.c",
    "chars": 17018,
    "preview": "#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"
  },
  {
    "path": "src/romfs.c",
    "chars": 19465,
    "preview": "#include <string.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <dirent.h>\n\n#include \"types.h\""
  },
  {
    "path": "src/romfs.h",
    "chars": 172,
    "preview": "#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_i"
  },
  {
    "path": "src/sha256.c",
    "chars": 5263,
    "preview": "/*********************************************************************\n* Filename:   sha256.c\n* Author:     Brad Conte ("
  },
  {
    "path": "src/sha256.h",
    "chars": 1215,
    "preview": "/*********************************************************************\n* Filename:   sha256.h\n* Author:     Brad Conte ("
  },
  {
    "path": "src/types.h",
    "chars": 1342,
    "preview": "#pragma once\n#include <stdint.h>\n\ntypedef uint64_t dword_t;\ntypedef uint32_t word_t;\ntypedef uint16_t hword_t;\ntypedef u"
  }
]

About this extraction

This page contains the full source code of the switchbrew/switch-tools GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 28 files (268.1 KB), approximately 77.9k tokens, and a symbol index with 278 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!