ASR_BASE
Change-Id: Icf3719cc0afe3eeb3edc7fa80a2eb5199ca9dda1
diff --git a/tools/7z/Makefile b/tools/7z/Makefile
new file mode 100644
index 0000000..962fd57
--- /dev/null
+++ b/tools/7z/Makefile
@@ -0,0 +1,31 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=7z
+PKG_VERSION:=24.05
+
+PKG_SOURCE:=$(PKG_NAME)$(subst .,,$(PKG_VERSION))-src.tar.xz
+PKG_SOURCE_URL:=https://7-zip.org/a/
+PKG_HASH:=63f341cf80b8d287c6e945519b3da0fa75553c85572a471b7fa6e68f9a90b790
+
+PKG_CPE_ID:=cpe:/a:7-zip:7-zip
+
+# This builds the 7zr variant which supports only 7z, so no non-LGPL code should be included
+PKG_LICENSE:=LGPL-2.1-or-later
+PKG_LICENSE_FILES:=DOC/License.txt DOC/copying.txt
+
+HOST_MAKE_PATH:=CPP/7zip/Bundles/Alone7z
+
+include $(INCLUDE_DIR)/host-build.mk
+
+TAR_OPTIONS := -C $(HOST_BUILD_DIR) $(TAR_OPTIONS)
+HOST_MAKE_FLAGS += -f makefile.gcc
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/$(HOST_MAKE_PATH)/_o/7zr $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/7zr
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/7z/patches/7-zip-flags.patch b/tools/7z/patches/7-zip-flags.patch
new file mode 100644
index 0000000..5c684b0
--- /dev/null
+++ b/tools/7z/patches/7-zip-flags.patch
@@ -0,0 +1,20 @@
+--- a/CPP/7zip/7zip_gcc.mak
++++ b/CPP/7zip/7zip_gcc.mak
+@@ -24,7 +24,7 @@ PROGPATH_STATIC = $(O)/$(PROG)s
+
+
+ ifneq ($(CC), xlc)
+-CFLAGS_WARN_WALL = -Werror -Wall -Wextra
++CFLAGS_WARN_WALL = -Wall -Wextra
+ endif
+
+ # for object file
+@@ -50,7 +50,7 @@ endif
+ endif
+
+ # CFLAGS_BASE_LIST = -S
+-CFLAGS_BASE = -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \
++CFLAGS_BASE = $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) -D_GNU_SOURCE \
+ $(CFLAGS_DEBUG) -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE \
+ -fPIC
+
diff --git a/tools/7z/patches/7-zip-musl.patch b/tools/7z/patches/7-zip-musl.patch
new file mode 100644
index 0000000..a08520a
--- /dev/null
+++ b/tools/7z/patches/7-zip-musl.patch
@@ -0,0 +1,36 @@
+--- a/C/Threads.c
++++ b/C/Threads.c
+@@ -265,7 +265,7 @@ WRes Thread_Create_With_CpuSet(CThread *
+ */
+
+ // ret2 =
+- pthread_attr_setaffinity_np(&attr, sizeof(*cpuSet), cpuSet);
++ //pthread_attr_setaffinity_np(&attr, sizeof(*cpuSet), cpuSet);
+ // if (ret2) ret = ret2;
+ #endif
+ }
+@@ -275,14 +275,12 @@ WRes Thread_Create_With_CpuSet(CThread *
+ if (!ret)
+ {
+ p->_created = 1;
+- /*
+ if (cpuSet)
+ {
+ // ret2 =
+ pthread_setaffinity_np(p->_tid, sizeof(*cpuSet), cpuSet);
+ // if (ret2) ret = ret2;
+ }
+- */
+ }
+ }
+ // ret2 =
+--- a/C/Threads.h
++++ b/C/Threads.h
+@@ -29,6 +29,7 @@ Z7_DIAGNOSTIC_IGNORE_END_RESERVED_MACRO_
+ #endif
+
+ #include <pthread.h>
++#include <sched.h>
+
+ #endif
+
diff --git a/tools/Makefile b/tools/Makefile
new file mode 100644
index 0000000..009a776
--- /dev/null
+++ b/tools/Makefile
@@ -0,0 +1,231 @@
+#
+# Copyright (C) 2006-2011 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+# Main makefile for the host tools
+#
+curdir:=tools
+
+# subdirectories to descend into
+tools-y :=
+
+ifeq ($(CONFIG_EXTERNAL_TOOLCHAIN),)
+ BUILD_TOOLCHAIN := y
+ ifdef CONFIG_GCC_USE_GRAPHITE
+ BUILD_ISL = y
+ endif
+endif
+ifneq ($(CONFIG_SDK)$(CONFIG_PACKAGE_kmod-b43)$(CONFIG_BRCMSMAC_USE_FW_FROM_WL),)
+ BUILD_B43_TOOLS = y
+endif
+ifneq ($(CONFIG_SDK)$(CONFIG_TARGET_INITRAMFS_COMPRESSION_BZIP2),)
+ BUILD_BZIP2_TOOLS = y
+endif
+ifneq ($(CONFIG_SDK)$(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZ4),)
+ BUILD_LZ4_TOOLS = y
+endif
+ifneq ($(CONFIG_SDK)$(CONFIG_TARGET_INITRAMFS_COMPRESSION_LZO),)
+ BUILD_LZO_TOOLS = y
+endif
+
+tools-y += autoconf
+tools-y += autoconf-archive
+tools-y += automake
+tools-y += bc
+tools-y += bison
+tools-y += cmake
+tools-y += cpio
+tools-y += dosfstools
+tools-y += e2fsprogs
+tools-y += elfutils
+tools-y += expat
+tools-y += fakeroot
+tools-y += findutils
+tools-y += firmware-utils
+tools-y += flex
+tools-y += gengetopt
+tools-y += gnulib
+tools-y += libressl
+tools-y += libtool
+tools-y += lzma
+tools-y += m4
+tools-y += make-ext4fs
+tools-y += meson
+tools-y += missing-macros
+tools-y += mkimage
+tools-y += mklibs
+tools-y += mtd-utils
+tools-y += mtools
+tools-y += ninja
+tools-y += padjffs2
+tools-y += patch-image
+tools-y += patchelf
+tools-y += pkgconf
+tools-y += quilt
+tools-y += squashfs4
+tools-y += sstrip
+tools-y += util-linux
+tools-y += xz
+tools-y += zip
+tools-y += zlib
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS),y) += liblzo
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_B43_TOOLS),y) += b43-tools
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_BZIP2_TOOLS),y) += bzip2
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_ISL),y) += isl
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_LZ4_TOOLS),y) += lz4
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_LZO_TOOLS),y) += lzop
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(BUILD_TOOLCHAIN),y) += gmp mpc mpfr
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_TARGET_apm821xx)$(CONFIG_TARGET_gemini),y) += genext2fs
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_TARGET_ath79),y) += lzma-old squashfs3-lzma
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_TARGET_mxs),y) += elftosb sdimage
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_TARGET_realtek),y) += 7z
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_TARGET_tegra),y) += cbootimage cbootimage-configs
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_USES_MINOR),y) += yafut
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_USE_SPARSE),y) += sparse
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_USE_LLVM_BUILD),y) += llvm-bpf
+tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_USE_MOLD),y) += mold
+
+# builddir dependencies
+$(curdir)/autoconf/compile := $(curdir)/m4/compile
+$(curdir)/automake/compile := $(curdir)/autoconf/compile $(curdir)/pkgconf/compile $(curdir)/xz/compile
+$(curdir)/b43-tools/compile := $(curdir)/bison/compile
+$(curdir)/bc/compile := $(curdir)/bison/compile $(curdir)/libtool/compile
+$(curdir)/bison/compile := $(curdir)/flex/compile
+$(curdir)/cbootimage/compile += $(curdir)/automake/compile
+$(curdir)/cmake/compile += $(curdir)/libressl/compile $(curdir)/ninja/compile $(curdir)/expat/compile $(curdir)/xz/compile $(curdir)/zlib/compile $(curdir)/zstd/compile
+$(curdir)/dosfstools/compile := $(curdir)/automake/compile
+$(curdir)/e2fsprogs/compile := $(curdir)/libtool/compile $(curdir)/util-linux/compile
+$(curdir)/elfutils/compile := $(curdir)/m4/compile $(curdir)/zlib/compile $(curdir)/gnulib/compile $(curdir)/libtool/compile
+$(curdir)/fakeroot/compile := $(curdir)/libtool/compile
+$(curdir)/findutils/compile := $(curdir)/bison/compile
+$(curdir)/firmware-utils/compile += $(curdir)/cmake/compile
+$(curdir)/flex/compile := $(curdir)/libtool/compile
+$(curdir)/genext2fs/compile := $(curdir)/libtool/compile
+$(curdir)/gengetopt/compile := $(curdir)/libtool/compile
+$(curdir)/gmp/compile := $(curdir)/libtool/compile
+$(curdir)/isl/compile := $(curdir)/gmp/compile
+$(curdir)/liblzo/compile := $(curdir)/cmake/compile
+$(curdir)/libressl/compile := $(curdir)/pkgconf/compile
+$(curdir)/libtool/compile := $(curdir)/automake/compile $(curdir)/gnulib/compile $(curdir)/missing-macros/compile
+$(curdir)/lz4/compile := $(curdir)/meson/compile
+$(curdir)/lzma-old/compile := $(curdir)/zlib/compile
+$(curdir)/lzop/compile := $(curdir)/cmake/compile $(curdir)/liblzo/compile
+$(curdir)/llvm-bpf/compile := $(curdir)/cmake/compile
+$(curdir)/make-ext4fs/compile := $(curdir)/zlib/compile
+$(curdir)/meson/compile := $(curdir)/ninja/compile
+$(curdir)/missing-macros/compile := $(curdir)/autoconf/compile
+$(curdir)/mkimage/compile += $(curdir)/bison/compile $(curdir)/libressl/compile
+$(curdir)/mklibs/compile := $(curdir)/libtool/compile
+$(curdir)/mold/compile := $(curdir)/cmake/compile $(curdir)/zlib/compile $(curdir)/zstd/compile
+$(curdir)/mpc/compile := $(curdir)/mpfr/compile $(curdir)/gmp/compile
+$(curdir)/mpfr/compile := $(curdir)/gmp/compile
+$(curdir)/mtd-utils/compile := $(curdir)/libtool/compile $(curdir)/zlib/compile $(curdir)/util-linux/compile
+$(curdir)/padjffs2/compile := $(curdir)/findutils/compile
+$(curdir)/patchelf/compile := $(curdir)/libtool/compile
+$(curdir)/pkgconf/compile := $(curdir)/meson/compile
+$(curdir)/quilt/compile := $(curdir)/autoconf/compile $(curdir)/findutils/compile
+$(curdir)/sdcc/compile := $(curdir)/bison/compile
+$(curdir)/squashfs3-lzma/compile := $(curdir)/lzma-old/compile
+$(curdir)/squashfs4/compile := $(curdir)/xz/compile $(curdir)/zlib/compile
+$(curdir)/util-linux/compile := $(curdir)/bison/compile $(curdir)/automake/compile
+$(curdir)/yafut/compile := $(curdir)/cmake/compile
+
+ifneq ($(HOST_OS),Linux)
+ $(curdir)/coreutils/compile += $(curdir)/automake/compile $(curdir)/bison/compile $(curdir)/gnulib/compile
+ $(curdir)/squashfs4/compile += $(curdir)/coreutils/compile
+ tools-y += coreutils
+endif
+ifeq ($(HOST_OS),Darwin)
+ tools-y += bash
+else
+ $(curdir)/dwarves/compile += $(curdir)/elfutils/compile
+ tools-$(if $(CONFIG_BUILD_ALL_HOST_TOOLS)$(CONFIG_DWARVES),y) += dwarves
+endif
+
+ifneq ($(CONFIG_CCACHE)$(CONFIG_SDK),)
+$(foreach tool, $(filter-out zstd zlib xz pkgconf patch ninja meson libressl expat cmake,$(tools-y)), $(eval $(curdir)/$(tool)/compile += $(curdir)/ccache/compile))
+tools-y += ccache
+$(curdir)/ccache/compile := $(curdir)/cmake/compile
+endif
+
+# in case there is no patch tool on the host we need to make patch tool a
+# dependency for tools which have patches directory
+$(foreach tool, $(tools-y), $(if $(wildcard $(curdir)/$(tool)/patches),$(eval $(curdir)/$(tool)/compile += $(curdir)/patch/compile)))
+
+$(foreach tool, $(filter-out zstd,$(tools-y)), $(eval $(curdir)/$(tool)/compile += $(curdir)/zstd/compile))
+
+# make any tool depend on the following to ensure that archives can be unpacked and patched properly
+tools-core += libdeflate
+tools-core += patch
+tools-core += tar
+tools-core += zstd
+
+$(foreach tool, $(tools-y), $(eval $(curdir)/$(tool)/compile += $(patsubst %,$(curdir)/%/compile,$(tools-core))))
+tools-y += $(tools-core)
+
+# make some core tools depend on sed and flock
+$(curdir)/patch/compile += $(curdir)/sed/compile
+$(curdir)/tar/compile += $(curdir)/sed/compile
+$(curdir)/zstd/compile += $(curdir)/libdeflate/compile
+
+$(curdir)/sed/compile := $(curdir)/flock/compile $(curdir)/zstd/compile
+tools-y += flock sed
+
+$(curdir)/autoremove := 1
+$(curdir)/builddirs := $(tools-y) $(tools-dep) $(tools-)
+$(curdir)/builddirs-default := $(tools-y)
+
+ifdef CHECK_ALL
+$(curdir)/builddirs-check:=$($(curdir)/builddirs)
+$(curdir)/builddirs-download:=$($(curdir)/builddirs)
+endif
+
+ifndef DUMP_TARGET_DB
+define PrepareStaging
+ @for dir in $(1); do ( \
+ $(if $(QUIET),,set -x;) \
+ mkdir -p "$$dir"; \
+ cd "$$dir"; \
+ mkdir -p bin lib stamp usr/include usr/lib; \
+ ); done
+endef
+
+$(BIN_DIR):
+ mkdir -p $@
+
+# preparatory work
+$(STAGING_DIR)/.prepared: $(TMP_DIR)/.build
+ $(call PrepareStaging,$(STAGING_DIR))
+ mkdir -p $(BUILD_DIR)/stamp
+ touch $@
+
+$(STAGING_DIR_HOST)/.prepared: $(TMP_DIR)/.build
+ $(call PrepareStaging,$(STAGING_DIR_HOST))
+ mkdir -p $(BUILD_DIR_HOST)/stamp $(STAGING_DIR_HOST)/include/sys
+ $(INSTALL_DATA) $(TOPDIR)/tools/include/*.h $(STAGING_DIR_HOST)/include/
+ $(INSTALL_DATA) $(TOPDIR)/tools/include/sys/*.h $(STAGING_DIR_HOST)/include/sys/
+ifneq ($(HOST_OS),Linux)
+ mkdir -p $(STAGING_DIR_HOST)/include/asm
+ $(INSTALL_DATA) $(TOPDIR)/tools/include/asm/*.h $(STAGING_DIR_HOST)/include/asm/
+endif
+ ln -snf lib $(STAGING_DIR_HOST)/lib64
+ touch $@
+
+endif
+
+$(curdir)//prepare = $(STAGING_DIR)/.prepared $(STAGING_DIR_HOST)/.prepared $(BIN_DIR)
+$(curdir)//compile = $(STAGING_DIR)/.prepared $(STAGING_DIR_HOST)/.prepared $(BIN_DIR)
+
+# prerequisites for the individual targets
+$(curdir)/ := .config prereq
+
+$(curdir)/install: $(curdir)/compile
+
+ifeq ($(TOOLS_REFRESH),1)
+tools_enabled = $(foreach tool,$(sort $(tools-y) $(tools-)),$(if $(filter $(tool),$(tools-y)),y,n))
+$(eval $(call stampfile,$(curdir),tools,compile,,_$(subst $(space),,$(tools_enabled)),$(STAGING_DIR_HOST)))
+$(eval $(call stampfile,$(curdir),tools,check,$(TMP_DIR)/.build,,$(STAGING_DIR_HOST)))
+$(eval $(call subdir,$(curdir)))
+endif
diff --git a/tools/autoconf-archive/Makefile b/tools/autoconf-archive/Makefile
new file mode 100644
index 0000000..a4ab423
--- /dev/null
+++ b/tools/autoconf-archive/Makefile
@@ -0,0 +1,16 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=autoconf-archive
+PKG_VERSION:=2023.02.20
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@GNU/autoconf-archive
+PKG_HASH:=71d4048479ae28f1f5794619c3d72df9c01df49b1c628ef85fde37596dc31a33
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/autoconf/Makefile b/tools/autoconf/Makefile
new file mode 100644
index 0000000..d933c71
--- /dev/null
+++ b/tools/autoconf/Makefile
@@ -0,0 +1,31 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=autoconf
+PKG_VERSION:=2.71
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/autoconf
+PKG_HASH:=431075ad0bf529ef13cb41e9042c542381103e80015686222b8a9d4abef42a1c
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_VARS += \
+ EMACS="no" \
+ PERL="/usr/bin/env perl"
+
+define Host/Compile
+ -$(call Host/Compile/Default,--touch install-man1) # disable building of man pages
+ $(call Host/Compile/Default)
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/autoconf/patches/000-relocatable.patch b/tools/autoconf/patches/000-relocatable.patch
new file mode 100644
index 0000000..3961d22
--- /dev/null
+++ b/tools/autoconf/patches/000-relocatable.patch
@@ -0,0 +1,195 @@
+--- a/bin/autoheader.in
++++ b/bin/autoheader.in
+@@ -30,9 +30,12 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, "$pkgdatadir";
+
+ # Override SHELL. On DJGPP SHELL may not be set to a shell
+@@ -54,7 +57,7 @@ use Autom4te::XFile;
+ our ($config_h, %symbol, %verbatim);
+
+ # Lib files.
+-my $autom4te = $ENV{'AUTOM4TE'} || '@bindir@/@autom4te-name@';
++my $autom4te = $ENV{'AUTOM4TE'} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/@autom4te-name@' : '@bindir@/@autom4te-name@');
+ my $config_h_in;
+ my @prepend_include;
+ my @include;
+--- a/bin/autom4te.in
++++ b/bin/autom4te.in
+@@ -26,9 +26,12 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, $pkgdatadir;
+
+ # Override SHELL. On DJGPP SHELL may not be set to a shell
+@@ -48,7 +51,8 @@ use Autom4te::General;
+ use Autom4te::XFile;
+
+ # Data directory.
+-my $pkgdatadir = $ENV{'AC_MACRODIR'} || '@pkgdatadir@';
++my $pkgdatadir = $ENV{'AC_MACRODIR'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+
+ # $LANGUAGE{LANGUAGE} -- Automatic options for LANGUAGE.
+ my %language;
+@@ -91,7 +95,7 @@ my @include;
+ my $freeze = 0;
+
+ # $M4.
+-my $m4 = $ENV{"M4"} || '@M4@';
++my $m4 = $ENV{"M4"} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/m4' : '@M4@');
+ # Some non-GNU m4's don't reject the --help option, so give them /dev/null.
+ fatal "need GNU m4 1.4 or later: $m4"
+ if system "$m4 --help </dev/null 2>&1 | grep reload-state >/dev/null";
+@@ -272,6 +276,12 @@ sub load_configuration ($)
+
+ my @words = shellwords ($_);
+ my $type = shift @words;
++
++ if ($ENV{'STAGING_DIR_HOST'})
++ {
++ @words = map { s!^@pkgdatadir@!$ENV{'STAGING_DIR_HOST'}/share/autoconf!; $_ } @words;
++ }
++
+ if ($type eq 'begin-language:')
+ {
+ fatal "$file:$.: end-language missing for: $lang"
+--- a/bin/autoreconf.in
++++ b/bin/autoreconf.in
+@@ -29,10 +29,13 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ my $buildauxdir;
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, $pkgdatadir;
+
+ $buildauxdir = $ENV{'autom4te_buildauxdir'} || $pkgdatadir . '/build-aux';
+@@ -117,9 +120,9 @@ Written by David J. MacKenzie and Akim D
+ ";
+
+ # Lib files.
+-my $autoconf = $ENV{'AUTOCONF'} || '@bindir@/@autoconf-name@';
+-my $autoheader = $ENV{'AUTOHEADER'} || '@bindir@/@autoheader-name@';
+-my $autom4te = $ENV{'AUTOM4TE'} || '@bindir@/@autom4te-name@';
++my $autoconf = $ENV{'AUTOCONF'} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/@autoconf-name@' : '@bindir@/@autoconf-name@');
++my $autoheader = $ENV{'AUTOHEADER'} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/@autoheader-name@' : '@bindir@/@autoheader-name@');
++my $autom4te = $ENV{'AUTOM4TE'} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/@autom4te-name@' : '@bindir@/@autom4te-name@');
+ my $automake = $ENV{'AUTOMAKE'} || 'automake';
+ my $aclocal = $ENV{'ACLOCAL'} || 'aclocal';
+ my $libtoolize = $ENV{'LIBTOOLIZE'} || 'libtoolize';
+--- a/bin/autoscan.in
++++ b/bin/autoscan.in
+@@ -28,9 +28,12 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, $pkgdatadir;
+
+ # Override SHELL. On DJGPP SHELL may not be set to a shell
+@@ -95,10 +98,10 @@ my %needed_macros =
+ my $log;
+
+ # Autoconf and lib files.
+-my $autom4te = $ENV{'AUTOM4TE'} || '@bindir@/@autom4te-name@';
++my $autom4te = $ENV{'AUTOM4TE'} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/@autom4te-name@' : '@bindir@/@autom4te-name@');
+ my $autoconf = "$autom4te --language=autoconf";
+ my @prepend_include;
+-my @include = ('@pkgdatadir@');
++my @include = ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+
+ # $help
+ # -----
+--- a/bin/autoupdate.in
++++ b/bin/autoupdate.in
+@@ -29,9 +29,12 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, $pkgdatadir;
+
+ # Override SHELL. On DJGPP SHELL may not be set to a shell
+@@ -55,10 +58,10 @@ my $autom4te = $ENV{'AUTOM4TE'} || '@bin
+ my $autoconf = "$autom4te --language=autoconf";
+ # We need to find m4sugar.
+ my @prepend_include;
+-my @include = ('@pkgdatadir@');
++my @include = ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ my $force = 0;
+ # m4.
+-my $m4 = $ENV{"M4"} || '@M4@';
++my $m4 = $ENV{"M4"} || ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/bin/m4' : '@M4@');
+
+
+ # $HELP
+--- a/bin/ifnames.in
++++ b/bin/ifnames.in
+@@ -33,9 +33,12 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- my $pkgdatadir = $ENV{'autom4te_perllibdir'} || '@pkgdatadir@';
++ my $pkgdatadir = $ENV{'autom4te_perllibdir'} ||
++ ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/autoconf' : '@pkgdatadir@');
+ unshift @INC, $pkgdatadir;
+
+ # Override SHELL. On DJGPP SHELL may not be set to a shell
+--- a/bin/autoconf.as
++++ b/bin/autoconf.as
+@@ -89,8 +89,13 @@ exit_missing_arg='
+ # restore font-lock: '
+
+ # Variables.
+-: ${AUTOM4TE='@bindir@/@autom4te-name@'}
+-: ${trailer_m4='@pkgdatadir@/autoconf/trailer.m4'}
++if test -n "$STAGING_DIR_HOST"; then
++ : ${AUTOM4TE="$STAGING_DIR_HOST/bin/@autom4te-name@"}
++ : ${trailer_m4="$STAGING_DIR_HOST/share/autoconf/autoconf/trailer.m4"}
++else
++ : ${AUTOM4TE='@bindir@/@autom4te-name@'}
++ : ${trailer_m4='@pkgdatadir@/autoconf/trailer.m4'}
++fi
+ autom4te_options=
+ outfile=
+ verbose=false
diff --git a/tools/automake/Makefile b/tools/automake/Makefile
new file mode 100644
index 0000000..7f129c1
--- /dev/null
+++ b/tools/automake/Makefile
@@ -0,0 +1,53 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=automake
+PKG_CPE_ID:=cpe:/a:gnu:automake
+PKG_VERSION:=1.16.5
+PKG_API_VERSION:=$(word 2,$(subst ., ,$(PKG_VERSION)))
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/automake
+PKG_HASH:=07bd24ad08a64bc17250ce09ec56e921d6343903943e99ccf63bbf0705e34605
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += \
+ --disable-silent-rules
+
+HOST_CONFIGURE_VARS += \
+ PERL="/usr/bin/env perl" \
+ am_cv_prog_PERL_ithreads=no
+
+define Host/Configure
+ (cd $(HOST_BUILD_DIR); $(AM_TOOL_PATHS) STAGING_DIR_HOST="" ./bootstrap)
+ $(call Host/Configure/Default)
+endef
+
+define Host/Install
+ # remove old automake resources to avoid version conflicts
+ $(call Host/Uninstall)
+ $(call Host/Compile/Default,install)
+ mv $(STAGING_DIR_HOST)/bin/aclocal $(STAGING_DIR_HOST)/bin/aclocal.real
+ $(INSTALL_BIN) ./files/aclocal $(STAGING_DIR_HOST)/bin
+ ( \
+ api=$(PKG_API_VERSION); \
+ while [ "$$$$api" -ge 11 ]; do \
+ ln -sf aclocal "$(STAGING_DIR_HOST)/bin/aclocal-1.$$$$api"; \
+ api=$$$$(($$$$api - 1)); \
+ done; \
+ )
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+ rm -rf $(STAGING_DIR_HOST)/share/aclocal-[0-9]*
+ rm -rf $(STAGING_DIR_HOST)/share/automake-[0-9]*
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/automake/files/aclocal b/tools/automake/files/aclocal
new file mode 100755
index 0000000..689cb04
--- /dev/null
+++ b/tools/automake/files/aclocal
@@ -0,0 +1,2 @@
+#!/usr/bin/env sh
+${STAGING_DIR_HOST}/bin/aclocal.real $ACLOCAL_INCLUDE $@
diff --git a/tools/automake/patches/000-relocatable.patch b/tools/automake/patches/000-relocatable.patch
new file mode 100644
index 0000000..0b61eae
--- /dev/null
+++ b/tools/automake/patches/000-relocatable.patch
@@ -0,0 +1,52 @@
+--- a/lib/Automake/Config.in
++++ b/lib/Automake/Config.in
+@@ -34,7 +34,7 @@ our $PACKAGE = '@PACKAGE@';
+ our $PACKAGE_BUGREPORT = '@PACKAGE_BUGREPORT@';
+ our $VERSION = '@VERSION@';
+ our $RELEASE_YEAR = '@RELEASE_YEAR@';
+-our $libdir = $ENV{"AUTOMAKE_LIBDIR"} || '@datadir@/@PACKAGE@-@APIVERSION@';
++our $libdir = $ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/@PACKAGE@-@APIVERSION@' : '@datadir@/@PACKAGE@-@APIVERSION@';
+
+ our $perl_threads = 0;
+ # We need at least this version for CLONE support.
+--- a/bin/aclocal.in
++++ b/bin/aclocal.in
+@@ -23,9 +23,11 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- unshift (@INC, '@datadir@/@PACKAGE@-@APIVERSION@')
++ unshift (@INC, ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/@PACKAGE@-@APIVERSION@' : '@datadir@/@PACKAGE@-@APIVERSION@'))
+ unless $ENV{AUTOMAKE_UNINSTALLED};
+ }
+
+@@ -65,8 +67,8 @@ $perl_threads = 0;
+ # ACLOCAL_PATH environment variable, and reset with the '--system-acdir'
+ # option.
+ my @user_includes = ();
+-my @automake_includes = ('@datadir@/aclocal-' . $APIVERSION);
+-my @system_includes = ('@datadir@/aclocal');
++my @automake_includes = ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . "/share/aclocal-$APIVERSION" : "@datadir@/aclocal-$APIVERSION");
++my @system_includes = ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/aclocal' : '@datadir@/aclocal');
+
+ # Whether we should copy M4 file in $user_includes[0].
+ my $install = 0;
+--- a/bin/automake.in
++++ b/bin/automake.in
+@@ -26,9 +26,11 @@ use 5.006;
+ use strict;
+ use warnings FATAL => 'all';
+
++$^W = 1;
++
+ BEGIN
+ {
+- unshift (@INC, '@datadir@/@PACKAGE@-@APIVERSION@')
++ unshift (@INC, ($ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/@PACKAGE@-@APIVERSION@' : '@datadir@/@PACKAGE@-@APIVERSION@'))
+ unless $ENV{AUTOMAKE_UNINSTALLED};
+
+ # Override SHELL. This is required on DJGPP so that system() uses
diff --git a/tools/automake/patches/100-aclocal-skip-not-existing-directories.patch b/tools/automake/patches/100-aclocal-skip-not-existing-directories.patch
new file mode 100644
index 0000000..a0d04e2
--- /dev/null
+++ b/tools/automake/patches/100-aclocal-skip-not-existing-directories.patch
@@ -0,0 +1,15 @@
+--- a/bin/aclocal.in
++++ b/bin/aclocal.in
+@@ -371,6 +371,12 @@ sub scan_m4_dirs ($$@)
+
+ foreach my $m4dir (@dirlist)
+ {
++ if (! -d $m4dir)
++ {
++ msg ('override', "warning: skipping not existing directory `$m4dir'");
++ next;
++ }
++
+ if (! opendir (DIR, $m4dir))
+ {
+ # TODO: maybe avoid complaining only if errno == ENONENT?
diff --git a/tools/automake/patches/101-do-not-require-files.patch b/tools/automake/patches/101-do-not-require-files.patch
new file mode 100644
index 0000000..3a8c9fc
--- /dev/null
+++ b/tools/automake/patches/101-do-not-require-files.patch
@@ -0,0 +1,29 @@
+--- a/bin/automake.in
++++ b/bin/automake.in
+@@ -4513,7 +4513,7 @@ sub handle_gettext ()
+ && grep ($_ eq 'intl', @subdirs));
+ }
+
+- require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
++ require_file ($ac_gettext_location, GNITS, 'ABOUT-NLS');
+ }
+
+ # Emit makefile footer.
+@@ -5641,7 +5641,7 @@ sub check_gnu_standards ()
+ # otherwise require non-.md.
+ my $required
+ = (! -f $file && -f "$file.md") ? "$file.md" : $file;
+- require_file ("$am_file.am", GNU, $required);
++ require_file ("$am_file.am", GNITS, $required);
+ }
+
+ # Accept one of these three licenses; default to COPYING.
+@@ -5655,7 +5655,7 @@ sub check_gnu_standards ()
+ last;
+ }
+ }
+- require_file ("$am_file.am", GNU, 'COPYING')
++ require_file ("$am_file.am", GNITS, 'COPYING')
+ unless $license;
+ }
+
diff --git a/tools/automake/patches/200-other-V-values-for-verbosity.patch b/tools/automake/patches/200-other-V-values-for-verbosity.patch
new file mode 100644
index 0000000..1ea9d38
--- /dev/null
+++ b/tools/automake/patches/200-other-V-values-for-verbosity.patch
@@ -0,0 +1,59 @@
+From: Bogdan Drozdowski <bogdandr AT op.pl>
+Date: Sat, 31 Dec 2022 20:17:35 +0100
+Subject: [PATCH] Allow other V values for verbosity
+
+---
+ m4/silent.m4 | 2 +-
+ t/silent-gen.sh | 24 ++++++++++++++++++++++++
+ 2 files changed, 25 insertions(+), 1 deletion(-)
+
+--- a/m4/silent.m4
++++ b/m4/silent.m4
+@@ -43,7 +43,7 @@ else
+ fi])
+ if test $am_cv_make_support_nested_variables = yes; then
+ dnl Using '$V' instead of '$(V)' breaks IRIX make.
+- AM_V='$(V)'
++ AM_V='$(shell if ( test "x$(V)" = "x0" ); then echo 0; elif ( test "x$(V)" = "x" ); then echo $(AM_DEFAULT_VERBOSITY); else echo 1; fi)'
+ AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)'
+ else
+ AM_V=$AM_DEFAULT_VERBOSITY
+--- a/t/silent-gen.sh
++++ b/t/silent-gen.sh
+@@ -54,6 +54,18 @@ grep 'cp ' stdout
+ grep 'echo ' stdout
+
+ $MAKE clean
++run_make -O V=99
++grep 'GEN ' stdout && exit 1
++grep 'cp ' stdout
++grep 'echo ' stdout
++
++$MAKE clean
++run_make -O V=vvv
++grep 'GEN ' stdout && exit 1
++grep 'cp ' stdout
++grep 'echo ' stdout
++
++$MAKE clean
+ run_make -O V=0
+ grep 'GEN .*foo' stdout
+ grep 'cp ' stdout && exit 1
+@@ -78,5 +90,17 @@ run_make -O V=1
+ grep 'GEN ' stdout && exit 1
+ grep 'cp ' stdout
+ grep 'echo ' stdout
++
++$MAKE clean
++run_make -O V=99
++grep 'GEN ' stdout && exit 1
++grep 'cp ' stdout
++grep 'echo ' stdout
++
++$MAKE clean
++run_make -O V=v
++grep 'GEN ' stdout && exit 1
++grep 'cp ' stdout
++grep 'echo ' stdout
+
+ :
diff --git a/tools/b43-tools/Makefile b/tools/b43-tools/Makefile
new file mode 100644
index 0000000..8ec1330
--- /dev/null
+++ b/tools/b43-tools/Makefile
@@ -0,0 +1,47 @@
+#
+# Copyright (C) 2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=b43-tools
+PKG_DATE:=2022-07-05
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL:=https://github.com/mbuesch/b43-tools.git
+PKG_SOURCE_VERSION:=2fe10ea6690df9a068cb21cde537236bae784a14
+PKG_MIRROR_HASH:=4009d6c1f9ede43102897d6ebf4bd954331f3c4e2a94d4e61c0e5f303f929914
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/fwcutter \
+ CFLAGS="$(HOST_CFLAGS) -include endian.h" \
+ $(HOST_MAKE_FLAGS) \
+ $(1) QUIET_SPARSE=:
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/assembler \
+ CFLAGS="$(HOST_CFLAGS) -include endian.h -Wno-error=int-conversion" \
+ $(HOST_MAKE_FLAGS) \
+ LDFLAGS= \
+ $(1) QUIET_SPARSE=:
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/fwcutter/b43-fwcutter $(STAGING_DIR_HOST)/bin/
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/assembler/b43-asm $(STAGING_DIR_HOST)/bin/
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/assembler/b43-asm.bin $(STAGING_DIR_HOST)/bin/
+ $(INSTALL_BIN) ./files/b43-fwsquash.py $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/b43-fwcutter
+ rm -f $(STAGING_DIR_HOST)/bin/b43-asm
+ rm -f $(STAGING_DIR_HOST)/bin/b43-asm.bin
+ rm -f $(STAGING_DIR_HOST)/bin/b43-fwsquash.py
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/b43-tools/files/b43-fwsquash.py b/tools/b43-tools/files/b43-fwsquash.py
new file mode 100755
index 0000000..6b4952c
--- /dev/null
+++ b/tools/b43-tools/files/b43-fwsquash.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+#
+# b43 firmware file squasher
+# Removes unnecessary firmware files
+#
+# Copyright (c) 2009 Michael Buesch <mb@bu3sch.de>
+#
+# Licensed under the GNU/GPL version 2 or (at your option) any later version.
+#
+
+import sys
+import os
+
+def usage():
+ print("Usage: %s PHYTYPES COREREVS /path/to/extracted/firmware" % sys.argv[0])
+ print("")
+ print("PHYTYPES is a comma separated list of:")
+ print("A => A-PHY")
+ print("AG => Dual A-PHY G-PHY")
+ print("G => G-PHY")
+ print("LP => LP-PHY")
+ print("N => N-PHY")
+ print("HT => HT-PHY")
+ print("LCN => LCN-PHY")
+ print("LCN40 => LCN40-PHY")
+ print("AC => AC-PHY")
+ print("")
+ print("COREREVS is a comma separated list of core revision numbers.")
+
+if len(sys.argv) != 4:
+ usage()
+ sys.exit(1)
+
+phytypes = sys.argv[1]
+corerevs = sys.argv[2]
+fwpath = sys.argv[3]
+
+phytypes = phytypes.split(',')
+try:
+ corerevs = [int(r) for r in corerevs.split(',')]
+except ValueError:
+ print("ERROR: \"%s\" is not a valid COREREVS string\n" % corerevs)
+ usage()
+ sys.exit(1)
+
+
+fwfiles = os.listdir(fwpath)
+fwfiles = [str for str in fwfiles if str.endswith(".fw")]
+if not fwfiles:
+ print("ERROR: No firmware files found in %s" % fwpath)
+ sys.exit(1)
+
+required_fwfiles = []
+
+def revs_match(revs_a, revs_b):
+ for rev in revs_a:
+ if rev in revs_b:
+ return True
+ return False
+
+def phytypes_match(types_a, types_b):
+ for type in types_a:
+ type = type.strip().upper()
+ if type in types_b:
+ return True
+ return False
+
+revmapping = {
+ "ucode2.fw" : ( (2,3,), ("G",), ),
+ "ucode4.fw" : ( (4,), ("G",), ),
+ "ucode5.fw" : ( (5,6,7,8,9,10,), ("G","A","AG",), ),
+ "ucode11.fw" : ( (11,12,), ("N",), ),
+ "ucode13.fw" : ( (13,), ("LP","G",), ),
+ "ucode14.fw" : ( (14,), ("LP",), ),
+ "ucode15.fw" : ( (15,), ("LP",), ),
+ "ucode16_mimo.fw" : ( (16,17,18,19,23,), ("N",), ),
+# "ucode16_lp.fw" : ( (16,17,18,19,), ("LP",), ),
+ "ucode24_lcn.fw" : ( (24,), ("LCN",), ),
+ "ucode25_mimo.fw" : ( (25,28,), ("N",), ),
+ "ucode25_lcn.fw" : ( (25,28,), ("LCN",), ),
+ "ucode26_mimo.fw" : ( (26,), ("HT",), ),
+ "ucode29_mimo.fw" : ( (29,), ("HT",), ),
+ "ucode30_mimo.fw" : ( (30,), ("N",), ),
+ "ucode33_lcn40.fw" : ( (33,), ("LCN40",), ),
+ "ucode40.fw" : ( (40,), ("AC",), ),
+ "ucode42.fw" : ( (42,), ("AC",), ),
+ "pcm4.fw" : ( (1,2,3,4,), ("G",), ),
+ "pcm5.fw" : ( (5,6,7,8,9,10,), ("G","A","AG",), ),
+}
+
+initvalmapping = {
+ "a0g1initvals5.fw" : ( (5,6,7,8,9,10,), ("AG",), ),
+ "a0g0initvals5.fw" : ( (5,6,7,8,9,10,), ("A", "AG",), ),
+ "b0g0initvals2.fw" : ( (2,4,), ("G",), ),
+ "b0g0initvals5.fw" : ( (5,6,7,8,9,10,), ("G",), ),
+ "b0g0initvals13.fw" : ( (13,), ("G",), ),
+ "n0initvals11.fw" : ( (11,12,), ("N",), ),
+ "n0initvals16.fw" : ( (16,17,18,23,), ("N",), ),
+ "n0initvals24.fw" : ( (24,), ("N",), ),
+ "n0initvals25.fw" : ( (25,28,), ("N",), ),
+ "n16initvals30.fw" : ( (30,), ("N",), ),
+ "lp0initvals13.fw" : ( (13,), ("LP",), ),
+ "lp0initvals14.fw" : ( (14,), ("LP",), ),
+ "lp0initvals15.fw" : ( (15,), ("LP",), ),
+# "lp0initvals16.fw" : ( (16,17,18,), ("LP",), ),
+ "lcn0initvals24.fw" : ( (24,), ("LCN",), ),
+ "ht0initvals26.fw" : ( (26,), ("HT",), ),
+ "ht0initvals29.fw" : ( (29,), ("HT",), ),
+ "lcn400initvals33.fw" : ( (33,), ("LCN40",), ),
+ "ac0initvals40.fw" : ( (40,), ("AC",), ),
+ "ac1initvals42.fw" : ( (42,), ("AC",), ),
+ "a0g1bsinitvals5.fw" : ( (5,6,7,8,9,10,), ("AG",), ),
+ "a0g0bsinitvals5.fw" : ( (5,6,7,8,9,10,), ("A", "AG"), ),
+ "b0g0bsinitvals5.fw" : ( (5,6,7,8,9,10,), ("G",), ),
+ "n0bsinitvals11.fw" : ( (11,12,), ("N",), ),
+ "n0bsinitvals16.fw" : ( (16,17,18,23,), ("N",), ),
+ "n0bsinitvals24.fw" : ( (24,), ("N",), ),
+ "n0bsinitvals25.fw" : ( (25,28,), ("N",), ),
+ "n16bsinitvals30.fw" : ( (30,), ("N",), ),
+ "lp0bsinitvals13.fw" : ( (13,), ("LP",), ),
+ "lp0bsinitvals14.fw" : ( (14,), ("LP",), ),
+ "lp0bsinitvals15.fw" : ( (15,), ("LP",), ),
+# "lp0bsinitvals16.fw" : ( (16,17,18,), ("LP",), ),
+ "lcn0bsinitvals24.fw" : ( (24,), ("LCN",), ),
+ "ht0bsinitvals26.fw" : ( (26,), ("HT",), ),
+ "ht0bsinitvals29.fw" : ( (29,), ("HT",), ),
+ "lcn400bsinitvals33.fw" : ( (33,), ("LCN40",), ),
+ "ac0bsinitvals40.fw" : ( (40,), ("AC",), ),
+ "ac1bsinitvals42.fw" : ( (42,), ("AC",), ),
+}
+
+for f in fwfiles:
+ if f in revmapping:
+ if revs_match(corerevs, revmapping[f][0]) and\
+ phytypes_match(phytypes, revmapping[f][1]):
+ required_fwfiles += [f]
+ continue
+ if f in initvalmapping:
+ if revs_match(corerevs, initvalmapping[f][0]) and\
+ phytypes_match(phytypes, initvalmapping[f][1]):
+ required_fwfiles += [f]
+ continue
+ print("WARNING: Firmware file %s not found in the mapping lists" % f)
+
+for f in fwfiles:
+ if f not in required_fwfiles:
+ print("Deleting %s" % f)
+ os.unlink(fwpath + '/' + f)
+
diff --git a/tools/b43-tools/patches/001-fw-dirname.patch b/tools/b43-tools/patches/001-fw-dirname.patch
new file mode 100644
index 0000000..1fd4c66
--- /dev/null
+++ b/tools/b43-tools/patches/001-fw-dirname.patch
@@ -0,0 +1,16 @@
+--- a/fwcutter/fwcutter.c
++++ b/fwcutter/fwcutter.c
+@@ -50,13 +50,8 @@
+ #include "fwcutter.h"
+ #include "fwcutter_list.h"
+
+-#if defined(__DragonFly__) || defined(__FreeBSD__)
+-#define V3_FW_DIRNAME "v3"
+-#define V4_FW_DIRNAME "v4"
+-#else
+ #define V3_FW_DIRNAME "b43legacy"
+ #define V4_FW_DIRNAME "b43"
+-#endif
+
+ static struct cmdline_args cmdargs;
+
diff --git a/tools/b43-tools/patches/002-no_libfl.patch b/tools/b43-tools/patches/002-no_libfl.patch
new file mode 100644
index 0000000..2e55b08
--- /dev/null
+++ b/tools/b43-tools/patches/002-no_libfl.patch
@@ -0,0 +1,14 @@
+--- a/assembler/main.c
++++ b/assembler/main.c
+@@ -1268,6 +1268,11 @@ static void initialize(void)
+ #endif /* YYDEBUG */
+ }
+
++int yywrap(void)
++{
++ return 1;
++}
++
+ int main(int argc, char **argv)
+ {
+ int err, res = 1;
diff --git a/tools/bash/Makefile b/tools/bash/Makefile
new file mode 100644
index 0000000..f8262d1
--- /dev/null
+++ b/tools/bash/Makefile
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=bash
+PKG_CPE_ID:=cpe:/a:gnu:bash
+PKG_VERSION:=5.2.21
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/bash
+PKG_HASH:=c8e31bdc59b69aaffc5b36509905ba3e5cbb12747091d27b4b977f078560d5b8
+
+HOST_BUILD_PARALLEL := 1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/bc/Makefile b/tools/bc/Makefile
new file mode 100644
index 0000000..2c29e09
--- /dev/null
+++ b/tools/bc/Makefile
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2013-2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=bc
+PKG_VERSION:=1.07.1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/bc
+PKG_HASH:=62adfca89b0a1c0164c2cdca59ca210c1d44c3ffc46daf9931cf4942664cb02a
+
+PKG_FIXUP := autoreconf
+PKG_CPE_ID:=cpe:/a:gnu:bc
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/bc/patches/001-no_doc.patch b/tools/bc/patches/001-no_doc.patch
new file mode 100644
index 0000000..119f111
--- /dev/null
+++ b/tools/bc/patches/001-no_doc.patch
@@ -0,0 +1,21 @@
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -1,6 +1,6 @@
+ ## Process this file with automake to produce Makefile.in
+
+-SUBDIRS = lib bc dc doc
++SUBDIRS = lib bc dc
+
+ MAINTAINERCLEANFILES = aclocal.m4 config.h.in configure Makefile.in \
+ stamp-h $(distdir).tar.gz h/number.h depcomp missing \
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -288,7 +288,7 @@ target_alias = @target_alias@
+ top_build_prefix = @top_build_prefix@
+ top_builddir = @top_builddir@
+ top_srcdir = @top_srcdir@
+-SUBDIRS = lib bc dc doc
++SUBDIRS = lib bc dc
+ MAINTAINERCLEANFILES = aclocal.m4 config.h.in configure Makefile.in \
+ stamp-h $(distdir).tar.gz h/number.h depcomp missing \
+ bc/libmath.h
diff --git a/tools/bc/patches/002-fix-libmath.patch b/tools/bc/patches/002-fix-libmath.patch
new file mode 100644
index 0000000..f2212f0
--- /dev/null
+++ b/tools/bc/patches/002-fix-libmath.patch
@@ -0,0 +1,32 @@
+--- a/bc/fix-libmath_h
++++ b/bc/fix-libmath_h
+@@ -1,9 +1,9 @@
+-ed libmath.h <<EOS-EOS
+-1,1s/^/{"/
+-1,\$s/\$/",/
+-2,\$s/^/"/
+-\$,\$d
+-\$,\$s/,\$/,0}/
+-w
+-q
+-EOS-EOS
++#!/usr/bin/env bash
++sed -e '1 s/^/{"/' \
++ -e 's/$/",/' \
++ -e '2,$ s/^/"/' \
++ -e '$ d' \
++ -i libmath.h
++
++sed -e '$ s/$/0}/' \
++ -i libmath.h
+--- a/configure
++++ b/configure
+@@ -5288,7 +5288,7 @@ case $bcle-$bcrl-$LEX in
+ ?-?-flex)
+ LEX="flex -I -8" ;;
+ ?-y-*)
+- as_fn_error $? "readline works only with flex." "$LINENO" 5 ;;
++ : ;; # as_fn_error $? "readline works only with flex." "$LINENO" 5 ;;
+ esac
+
+ case $LEX-`uname -s` in
diff --git a/tools/bison/Makefile b/tools/bison/Makefile
new file mode 100644
index 0000000..97d34b5
--- /dev/null
+++ b/tools/bison/Makefile
@@ -0,0 +1,33 @@
+#
+# Copyright (C) 2008-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=bison
+PKG_VERSION:=3.8.2
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=06c9e13bdf7eb24d4ceb6b59205a4f67c2c7e7213119644430fe82fbd14a0abb
+PKG_CPE_ID:=cpe:/a:gnu:bison
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += --enable-threads=posix --disable-nls
+
+define Host/Install
+ $(call Host/Install/Default)
+ $(INSTALL_BIN) ./scripts/yacc $(STAGING_DIR_HOST)/bin/yacc
+endef
+
+define Host/Uninstall
+ rm -f $(STAGING_DIR_HOST)/bin/yacc
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/bison/patches/000-relocatable.patch b/tools/bison/patches/000-relocatable.patch
new file mode 100644
index 0000000..b98d7a8
--- /dev/null
+++ b/tools/bison/patches/000-relocatable.patch
@@ -0,0 +1,43 @@
+--- a/src/files.c
++++ b/src/files.c
+@@ -560,9 +560,9 @@ pkgdatadir (void)
+ char const *
+ m4path (void)
+ {
+- char const *m4 = getenv ("M4");
++ char const *m4 = getenv ("STAGING_DIR_HOST");
+ if (m4)
+- return m4;
++ return strcat(getenv ("STAGING_DIR_HOST"), "/bin/m4");
+
+ /* We don't use relocate2() to store the temporary buffer and re-use
+ it, because m4path() is only called once. */
+--- a/src/getargs.c
++++ b/src/getargs.c
+@@ -373,11 +373,13 @@ usage (int status)
+ A --long option is required.
+ Otherwise, add exceptions to ../build-aux/cross-options.pl. */
+
+- printf (_("Usage: %s [OPTION]... FILE\n"), program_name);
++ printf (_("Usage: STAGING_DIR_HOST=... %s [OPTION]... FILE\n"), program_name);
+ fputs (_("\
+ Generate a deterministic LR or generalized LR (GLR) parser employing\n\
+ LALR(1), IELR(1), or canonical LR(1) parser tables.\n\
+ \n\
++Environment Variable STAGING_DIR_HOST controls path to m4\n\
++\n\
+ "), stdout);
+
+ fputs (_("\
+@@ -450,6 +452,11 @@ Output Files:\n\
+ -M, --file-prefix-map=OLD=NEW replace prefix OLD with NEW when writing file paths\n\
+ in output files\n\
+ "), stdout);
++
++ fputs (_("\
++Environment Variables:\n\
++ STAGING_DIR_HOST Path to m4 is [STAGING_DIR_HOST]/bin/m4\n\
++"), stdout);
+ putc ('\n', stdout);
+
+ argmatch_report_usage (stdout);
diff --git a/tools/bison/scripts/yacc b/tools/bison/scripts/yacc
new file mode 100755
index 0000000..8f73e26
--- /dev/null
+++ b/tools/bison/scripts/yacc
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec bison -y "$@"
diff --git a/tools/bzip2/Makefile b/tools/bzip2/Makefile
new file mode 100644
index 0000000..86df143
--- /dev/null
+++ b/tools/bzip2/Makefile
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=bzip2
+PKG_VERSION:=1.0.8
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://sourceware.org/pub/bzip2
+PKG_HASH:=ab5a03176ee106d3f0fa90e381da478ddae405918153cca248e682cd0c4a2269
+
+PKG_LICENSE:=bzip2-1.0.8
+PKG_LICENSE_FILES:=LICENSE
+PKG_CPE_ID:=cpe:/a:bzip:bzip2
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOST_CFLAGS += $(HOST_FPIC)
+
+CMAKE_HOST_OPTIONS += -DENABLE_EXAMPLES=off
+
+$(eval $(call HostBuild))
diff --git a/tools/bzip2/patches/020-no-utime.patch b/tools/bzip2/patches/020-no-utime.patch
new file mode 100644
index 0000000..d0cd4f0
--- /dev/null
+++ b/tools/bzip2/patches/020-no-utime.patch
@@ -0,0 +1,27 @@
+--- a/bzip2.c
++++ b/bzip2.c
+@@ -69,7 +69,6 @@
+ #if BZ_UNIX
+ # include <fcntl.h>
+ # include <sys/types.h>
+-# include <utime.h>
+ # include <unistd.h>
+ # include <sys/stat.h>
+ # include <sys/times.h>
+@@ -1051,12 +1050,12 @@ void applySavedTimeInfoToOutputFile ( Ch
+ {
+ # if BZ_UNIX
+ IntNative retVal;
+- struct utimbuf uTimBuf;
++ struct timespec uTimBuf[2] = {};
+
+- uTimBuf.actime = fileMetaInfo.st_atime;
+- uTimBuf.modtime = fileMetaInfo.st_mtime;
++ uTimBuf[0].tv_sec = fileMetaInfo.st_atime;
++ uTimBuf[1].tv_sec = fileMetaInfo.st_mtime;
+
+- retVal = utime ( dstName, &uTimBuf );
++ retVal = utimensat ( AT_FDCWD, dstName, uTimBuf , 0 );
+ ERROR_IF_NOT_ZERO ( retVal );
+ # endif
+ }
diff --git a/tools/bzip2/patches/100-cmake.patch b/tools/bzip2/patches/100-cmake.patch
new file mode 100644
index 0000000..0ed37b2
--- /dev/null
+++ b/tools/bzip2/patches/100-cmake.patch
@@ -0,0 +1,382 @@
+--- /dev/null
++++ b/CMakeLists.txt
+@@ -0,0 +1,354 @@
++cmake_minimum_required(VERSION 3.12)
++
++project(bzip2
++ VERSION 1.0.8
++ DESCRIPTION "This Bzip2/libbz2 a program and library for lossless block-sorting data compression."
++ LANGUAGES C)
++
++# See versioning rule:
++# http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html
++#
++# KEEP THESE IN SYNC WITH meson.build OR STUFF WILL BREAK!
++set(LT_CURRENT 1)
++set(LT_REVISION 8)
++set(LT_AGE 0)
++
++set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
++
++include_directories(${PROJECT_BINARY_DIR})
++
++math(EXPR LT_SOVERSION "${LT_CURRENT} - ${LT_AGE}")
++set(LT_VERSION "${LT_SOVERSION}.${LT_AGE}.${LT_REVISION}")
++set(PACKAGE_VERSION ${PROJECT_VERSION})
++
++set(ENABLE_APP_DEFAULT ON)
++set(ENABLE_EXAMPLES_DEFAULT OFF)
++set(ENABLE_DOCS_DEFAULT OFF)
++include(CMakeOptions.txt)
++
++if(ENABLE_LIB_ONLY AND (ENABLE_APP OR ENABLE_EXAMPLES))
++ # Remember when disabled options are disabled for later diagnostics.
++ set(ENABLE_LIB_ONLY_DISABLED_OTHERS 1)
++else()
++ set(ENABLE_LIB_ONLY_DISABLED_OTHERS 0)
++endif()
++if(ENABLE_LIB_ONLY)
++ set(ENABLE_APP OFF)
++ set(ENABLE_EXAMPLES OFF)
++endif()
++
++# Do not disable assertions based on CMAKE_BUILD_TYPE.
++foreach(_build_type Release MinSizeRel RelWithDebInfo)
++ foreach(_lang C)
++ string(TOUPPER CMAKE_${_lang}_FLAGS_${_build_type} _var)
++ string(REGEX REPLACE "(^|)[/-]D *NDEBUG($|)" " " ${_var} "${${_var}}")
++ endforeach()
++endforeach()
++
++# Support the latest c++ standard available.
++include(CheckCCompilerFlag)
++include(CheckCXXCompilerFlag)
++
++function(extract_valid_c_flags varname)
++ set(valid_flags)
++ foreach(flag IN LISTS ARGN)
++ string(REGEX REPLACE "[^a-zA-Z0-9_]+" "_" flag_var ${flag})
++ set(flag_var "C_FLAG_${flag_var}")
++ check_c_compiler_flag("${flag}" "${flag_var}")
++ if(${flag_var})
++ set(valid_flags "${valid_flags} ${flag}")
++ endif()
++ endforeach()
++ set(${varname} "${valid_flags}" PARENT_SCOPE)
++endfunction()
++if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
++ set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the build type" FORCE)
++
++ # Include "None" as option to disable any additional (optimization) flags,
++ # relying on just CMAKE_C_FLAGS and CMAKE_CXX_FLAGS (which are empty by
++ # default). These strings are presented in cmake-gui.
++ set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
++ None Debug Release MinSizeRel RelWithDebInfo)
++endif()
++
++# Install a symlink of script to the "bin" directory.
++# Not intended for use on Windows.
++function(install_script_symlink original symlink)
++ add_custom_command(OUTPUT ${symlink}
++ COMMAND ${CMAKE_COMMAND} -E create_symlink ${original} ${symlink}
++ DEPENDS ${original}
++ COMMENT "Generating symbolic link ${symlink} of ${original}")
++ add_custom_target(${symlink}_tgt ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${symlink})
++ install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${symlink} DESTINATION ${CMAKE_INSTALL_BINDIR})
++endfunction()
++
++# Install a symlink of binary target to the "bin" directory.
++# On Windows, it will be a copy instead of a symlink.
++function(install_target_symlink original symlink)
++ if(WIN32)
++ set(op copy)
++ set(symlink "${symlink}.exe")
++ else()
++ set(op create_symlink)
++ endif()
++ add_custom_command(TARGET ${original} POST_BUILD
++ COMMAND ${CMAKE_COMMAND} -E ${op} $<TARGET_FILE_NAME:${original}> ${symlink}
++ WORKING_DIRECTORY $<TARGET_FILE_DIR:${original}>
++ COMMENT "Generating symbolic link (or copy) ${symlink} of ${original}")
++ install(PROGRAMS $<TARGET_FILE_DIR:${original}>/${symlink} DESTINATION ${CMAKE_INSTALL_BINDIR})
++endfunction()
++
++include(GNUInstallDirs)
++
++# Checks for header files.
++include(CheckIncludeFile)
++check_include_file(arpa/inet.h HAVE_ARPA_INET_H)
++check_include_file(fcntl.h HAVE_FCNTL_H)
++check_include_file(inttypes.h HAVE_INTTYPES_H)
++check_include_file(limits.h HAVE_LIMITS_H)
++check_include_file(netdb.h HAVE_NETDB_H)
++check_include_file(netinet/in.h HAVE_NETINET_IN_H)
++check_include_file(pwd.h HAVE_PWD_H)
++check_include_file(sys/socket.h HAVE_SYS_SOCKET_H)
++check_include_file(sys/time.h HAVE_SYS_TIME_H)
++check_include_file(syslog.h HAVE_SYSLOG_H)
++check_include_file(time.h HAVE_TIME_H)
++check_include_file(unistd.h HAVE_UNISTD_H)
++
++include(CheckTypeSize)
++# Checks for typedefs, structures, and compiler characteristics.
++# AC_TYPE_SIZE_T
++check_type_size("ssize_t" SIZEOF_SSIZE_T)
++if(NOT SIZEOF_SSIZE_T)
++ # ssize_t is a signed type in POSIX storing at least -1.
++ # Set it to "int" to match the behavior of AC_TYPE_SSIZE_T (autotools).
++ set(ssize_t int)
++endif()
++
++include(CheckStructHasMember)
++check_struct_has_member("struct tm" tm_gmtoff time.h HAVE_STRUCT_TM_TM_GMTOFF)
++
++include(CheckSymbolExists)
++# XXX does this correctly detect initgroups (un)availability on cygwin?
++check_symbol_exists(initgroups grp.h HAVE_DECL_INITGROUPS)
++if(NOT HAVE_DECL_INITGROUPS AND HAVE_UNISTD_H)
++ # FreeBSD declares initgroups() in unistd.h
++ check_symbol_exists(initgroups unistd.h HAVE_DECL_INITGROUPS2)
++ if(HAVE_DECL_INITGROUPS2)
++ set(HAVE_DECL_INITGROUPS 1)
++ endif()
++endif()
++
++set(WARNCFLAGS)
++if(CMAKE_C_COMPILER_ID MATCHES "MSVC")
++ if(ENABLE_WERROR)
++ set(WARNCFLAGS /WX)
++ endif()
++else()
++ if(ENABLE_WERROR)
++ extract_valid_c_flags(WARNCFLAGS -Werror)
++ endif()
++
++ # For C compiler
++ # Please keep this list in sync with meson.build
++ extract_valid_c_flags(WARNCFLAGS
++ -Wall
++ -Wextra
++ -Wmissing-prototypes
++ -Wstrict-prototypes
++ -Wmissing-declarations
++ -Wpointer-arith
++ -Wdeclaration-after-statement
++ -Wformat-security
++ -Wwrite-strings
++ -Wshadow
++ -Winline
++ -Wnested-externs
++ -Wfloat-equal
++ -Wundef
++ -Wendif-labels
++ -Wempty-body
++ -Wcast-align
++ -Wclobbered
++ -Wvla
++ -Wpragmas
++ -Wunreachable-code
++ -Waddress
++ -Wattributes
++ -Wdiv-by-zero
++ -Wshorten-64-to-32
++ -Wconversion
++ -Wextended-offsetof
++ -Wformat-nonliteral
++ -Wlanguage-extension-token
++ -Wmissing-field-initializers
++ -Wmissing-noreturn
++ -Wmissing-variable-declarations
++ # -Wpadded # Not used because we cannot change public structs
++ -Wsign-conversion
++ # -Wswitch-enum # Not used because this basically disallows default case
++ -Wunreachable-code-break
++ -Wunused-macros
++ -Wunused-parameter
++ -Wredundant-decls
++ -Wheader-guard
++ -Wno-format-nonliteral # This is required because we pass format string as "const char*.
++ )
++endif()
++
++if(ENABLE_DEBUG)
++ set(DEBUGBUILD 1)
++endif()
++
++#add_definitions(-DHAVE_CONFIG_H)
++#configure_file(cmakeconfig.h.in config.h)
++
++# autotools-compatible names
++# Sphinx expects relative paths in the .rst files. Use the fact that the files
++# below are all one directory level deep.
++file(RELATIVE_PATH top_srcdir ${CMAKE_CURRENT_BINARY_DIR}/dir ${CMAKE_CURRENT_SOURCE_DIR})
++file(RELATIVE_PATH top_builddir ${CMAKE_CURRENT_BINARY_DIR}/dir ${CMAKE_CURRENT_BINARY_DIR})
++set(abs_top_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
++set(abs_top_builddir ${CMAKE_CURRENT_BINARY_DIR})
++# bzip2.pc (pkg-config file)
++set(prefix ${CMAKE_INSTALL_PREFIX})
++set(exec_prefix ${CMAKE_INSTALL_PREFIX})
++set(bindir ${CMAKE_INSTALL_FULL_BINDIR})
++set(sbindir ${CMAKE_INSTALL_FULL_SBINDIR})
++set(libdir ${CMAKE_INSTALL_FULL_LIBDIR})
++set(includedir ${CMAKE_INSTALL_FULL_INCLUDEDIR})
++set(VERSION ${PACKAGE_VERSION})
++
++#
++# The build targets.
++# In a larger project, the following would be in subdirectories and
++# These targets would be included with `add_subdirectory()`
++#
++set(BZ2_SOURCES
++ blocksort.c
++ huffman.c
++ crctable.c
++ randtable.c
++ compress.c
++ decompress.c
++ bzlib.c)
++
++# The bz2 OBJECT-library, required for bzip2, bzip2recover.
++add_library(bz2_ObjLib OBJECT)
++target_sources(bz2_ObjLib
++ PRIVATE ${BZ2_SOURCES}
++ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
++ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h)
++
++if(ENABLE_SHARED_LIB)
++ # The libbz2 shared library.
++ add_library(bz2 SHARED ${BZ2_RES})
++ target_sources(bz2
++ PRIVATE ${BZ2_SOURCES}
++ ${CMAKE_CURRENT_SOURCE_DIR}/libbz2.def
++ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
++ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h)
++ # Always use '-fPIC'/'-fPIE' option for shared libraries.
++ set_property(TARGET bz2 PROPERTY POSITION_INDEPENDENT_CODE ON)
++ set_target_properties(bz2 PROPERTIES
++ COMPILE_FLAGS "${WARNCFLAGS}"
++ VERSION ${LT_VERSION} SOVERSION ${LT_SOVERSION})
++ install(TARGETS bz2 DESTINATION ${CMAKE_INSTALL_LIBDIR})
++ install(FILES bzlib.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
++
++ if(USE_OLD_SONAME)
++ # Hack to support the old libbz2.so.1.0 version by including an extra copy.
++ # Technically the old SONAME is not libtool compatible.
++ # This hack is to support binary compatibility with libbz2 in some distro packages.
++ if(UNIX AND NOT APPLE)
++ add_library(bz2_old_soname SHARED ${BZ2_RES})
++ target_sources(bz2_old_soname
++ PRIVATE ${BZ2_SOURCES}
++ ${CMAKE_CURRENT_SOURCE_DIR}/libbz2.def
++ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
++ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h
++ )
++ set_target_properties(bz2_old_soname PROPERTIES
++ COMPILE_FLAGS "${WARNCFLAGS}"
++ VERSION ${LT_SOVERSION}.${LT_AGE} SOVERSION ${LT_SOVERSION}.${LT_AGE}
++ OUTPUT_NAME bz2
++ )
++ install(TARGETS bz2_old_soname DESTINATION ${CMAKE_INSTALL_LIBDIR})
++ endif()
++ endif()
++endif()
++
++if(ENABLE_STATIC_LIB)
++ # The libbz2 static library.
++ add_library(bz2_static STATIC)
++ target_sources(bz2_static
++ PRIVATE ${BZ2_SOURCES}
++ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
++ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h)
++ set_target_properties(bz2_static PROPERTIES
++ COMPILE_FLAGS "${WARNCFLAGS}"
++ VERSION ${LT_VERSION}
++ SOVERSION ${LT_SOVERSION}
++ ARCHIVE_OUTPUT_NAME bz2_static)
++ target_compile_definitions(bz2_static PUBLIC BZ2_STATICLIB)
++ install(TARGETS bz2_static DESTINATION ${CMAKE_INSTALL_LIBDIR})
++ install(FILES bzlib.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
++endif()
++
++if(ENABLE_APP)
++ # The bzip2 executable.
++ add_executable(bzip2)
++ target_sources(bzip2
++ PRIVATE bzip2.c)
++ target_link_libraries(bzip2
++ PRIVATE bz2_ObjLib)
++ if(WIN32)
++ target_compile_definitions(bzip2 PUBLIC BZ_LCCWIN32 BZ_UNIX=0)
++ else()
++ target_compile_definitions(bzip2 PUBLIC BZ_LCCWIN32=0 BZ_UNIX)
++ endif()
++ install(TARGETS bzip2 DESTINATION ${CMAKE_INSTALL_BINDIR})
++
++ # Create bzip2 copies bzcat and bunzip.
++ # The default behavior is altered in bzip2.c code by checking the program name.
++ install_target_symlink(bzip2 bzcat)
++ install_target_symlink(bzip2 bunzip)
++
++ # The bzip2recover executable.
++ add_executable(bzip2recover)
++ target_sources(bzip2recover
++ PRIVATE bzip2recover.c)
++ target_link_libraries(bzip2recover
++ PRIVATE bz2_ObjLib)
++ if(WIN32)
++ target_compile_definitions(bzip2recover PUBLIC BZ_LCCWIN32 BZ_UNIX=0)
++ else()
++ target_compile_definitions(bzip2recover PUBLIC BZ_LCCWIN32=0 BZ_UNIX)
++ endif()
++ install(TARGETS bzip2recover DESTINATION ${CMAKE_INSTALL_BINDIR})
++
++ if(ENABLE_EXAMPLES)
++ if(ENABLE_SHARED_LIB)
++ # The dlltest executable.
++ add_executable(dlltest)
++ target_sources(dlltest
++ PRIVATE dlltest.c)
++ target_link_libraries(dlltest bz2)
++ install(TARGETS dlltest DESTINATION ${CMAKE_INSTALL_BINDIR})
++ endif()
++ endif()
++
++ if(NOT WIN32)
++ # Install shell scripts, and renamed copies.
++ install(PROGRAMS bzdiff bzgrep bzmore
++ DESTINATION ${CMAKE_INSTALL_BINDIR})
++
++ install_script_symlink(bzdiff bzcmp)
++
++ install_script_symlink(bzgrep bzegrep)
++ install_script_symlink(bzgrep bzfgrep)
++
++ install_script_symlink(bzmore bzless)
++ endif()
++
++endif()
+--- /dev/null
++++ b/CMakeOptions.txt
+@@ -0,0 +1,22 @@
++# Features that can be enabled for cmake (see CMakeLists.txt)
++
++option(ENABLE_WERROR "Turn on compile time warnings")
++
++option(ENABLE_DEBUG "Turn on debug output")
++
++option(ENABLE_APP "Build applications (bzip2, and bzip2recover)"
++ ${ENABLE_APP_DEFAULT})
++
++option(ENABLE_DOCS "Generate documentation"
++ ${ENABLE_DOCS_DEFAULT})
++
++option(ENABLE_EXAMPLES "Build examples"
++ ${ENABLE_EXAMPLES_DEFAULT})
++
++option(ENABLE_LIB_ONLY "Build libbz2 only. This is a short hand for -DENABLE_APP=0 -DENABLE_EXAMPLES=0")
++
++option(ENABLE_STATIC_LIB "Build libbz2 in static mode also")
++
++option(ENABLE_SHARED_LIB "Build libbz2 as a shared library" ON)
++
++option(USE_OLD_SONAME "Use libbz2.so.1.0 for compatibility with old Makefiles" OFF)
diff --git a/tools/cbootimage-configs/Makefile b/tools/cbootimage-configs/Makefile
new file mode 100644
index 0000000..586d1ef
--- /dev/null
+++ b/tools/cbootimage-configs/Makefile
@@ -0,0 +1,32 @@
+#
+# Copyright (c) 2017-2019 Tomasz Maciej Nowak <tmn505@gmail.com>
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME := cbootimage-configs
+
+PKG_SOURCE_DATE := 2017-04-13
+PKG_SOURCE_PROTO := git
+PKG_SOURCE_URL := https://github.com/NVIDIA/cbootimage-configs.git
+PKG_SOURCE_VERSION := 7c3b458b93ed6947cd083623f543e93f9103cc0f
+PKG_MIRROR_HASH := 6ba2dde907d3cc403720954738a92431b1f40d562db5815c08971c39374d72a1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/share/$(PKG_NAME)
+ $(CP) $(HOST_BUILD_DIR)/* \
+ $(STAGING_DIR_HOST)/share/$(PKG_NAME)
+endef
+
+define Host/Clean
+ rm -fR $(STAGING_DIR_HOST)/share/$(PKG_NAME)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/cbootimage/Makefile b/tools/cbootimage/Makefile
new file mode 100644
index 0000000..82be795
--- /dev/null
+++ b/tools/cbootimage/Makefile
@@ -0,0 +1,31 @@
+#
+# Copyright (c) 2017-2019 Tomasz Maciej Nowak <tmn505@gmail.com>
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME := cbootimage
+PKG_VERSION := 1.8
+
+PKG_SOURCE_PROTO := git
+PKG_SOURCE_URL := https://github.com/NVIDIA/cbootimage.git
+PKG_SOURCE_VERSION := 7c9db585d06cce9efffa2a82245f233233680060
+PKG_MIRROR_HASH := e38b1e9581524fcabc7b24fff1c18d13f7e3a93accf73c55caf33832249bfd03
+
+HOST_BUILD_PARALLEL := 1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+ (cd $(HOST_BUILD_DIR); autoreconf --install --symlink)
+ $(call Host/Configure/Default)
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/$(PKG_NAME) \
+ $(STAGING_DIR_HOST)/share/man/man1/$(PKG_NAME).1
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/ccache/Makefile b/tools/ccache/Makefile
new file mode 100644
index 0000000..447bc3e
--- /dev/null
+++ b/tools/ccache/Makefile
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=ccache
+PKG_VERSION:=4.10.2
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/ccache/ccache/releases/download/v$(PKG_VERSION)
+PKG_HASH:=108100960bb7e64573ea925af2ee7611701241abb36ce0aae3354528403a7d87
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_HOST_OPTIONS += \
+ -DCMAKE_C_COMPILER_LAUNCHER="" \
+ -DCMAKE_CXX_COMPILER_LAUNCHER="" \
+ -DCMAKE_SKIP_RPATH=FALSE \
+ -DCMAKE_INSTALL_RPATH="${STAGING_DIR_HOST}/lib" \
+ -DENABLE_DOCUMENTATION=OFF \
+ -DREDIS_STORAGE_BACKEND=OFF
+
+$(eval $(call HostBuild))
diff --git a/tools/ccache/patches/100-honour-copts.patch b/tools/ccache/patches/100-honour-copts.patch
new file mode 100644
index 0000000..c07c8ce
--- /dev/null
+++ b/tools/ccache/patches/100-honour-copts.patch
@@ -0,0 +1,10 @@
+--- a/src/ccache/ccache.cpp
++++ b/src/ccache/ccache.cpp
+@@ -1914,6 +1914,7 @@ get_manifest_key(Context& ctx, Hash& has
+ "OBJCPLUS_INCLUDE_PATH", // Clang
+ "CLANG_CONFIG_FILE_SYSTEM_DIR", // Clang
+ "CLANG_CONFIG_FILE_USER_DIR", // Clang
++ "GCC_HONOUR_COPTS",
+ nullptr,
+ };
+ for (const char** p = envvars; *p; ++p) {
diff --git a/tools/cmake/Makefile b/tools/cmake/Makefile
new file mode 100644
index 0000000..152d295
--- /dev/null
+++ b/tools/cmake/Makefile
@@ -0,0 +1,58 @@
+#
+# Copyright (C) 2006-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=cmake
+PKG_VERSION:=3.30.5
+PKG_VERSION_MAJOR:=$(word 1,$(subst ., ,$(PKG_VERSION))).$(word 2,$(subst ., ,$(PKG_VERSION)))
+PKG_RELEASE:=1
+PKG_CPE_ID:=cpe:/a:kitware:cmake
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/Kitware/CMake/releases/download/v$(PKG_VERSION)/ \
+ https://cmake.org/files/v$(PKG_VERSION_MAJOR)/
+PKG_HASH:=9f55e1a40508f2f29b7e065fa08c29f82c402fa0402da839fffe64a25755a86d
+
+HOST_BUILD_PARALLEL:=1
+HOST_CONFIGURE_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_VARS += \
+ CC="$(HOSTCC_NOCACHE)" \
+ CXX="$(HOSTCXX_NOCACHE)" \
+ MAKEFLAGS="$(HOST_JOBS)" \
+ CXXFLAGS="$(HOST_CFLAGS)" \
+ MAKE="$(STAGING_DIR_HOST)/bin/ninja"
+
+HOST_CONFIGURE_ARGS := \
+ --no-debugger \
+ $(if $(MAKE_JOBSERVER),--parallel="$(MAKE_JOBSERVER)") \
+ --prefix="$(STAGING_DIR_HOST)" \
+ --system-expat \
+ --system-liblzma \
+ --system-zlib \
+ --system-zstd \
+ --generator=Ninja
+
+define Host/Compile/Default
+ +$(NINJA) -C $(HOST_BUILD_DIR) $(1)
+endef
+
+define Host/Install/Default
+ +$(NINJA) -C $(HOST_BUILD_DIR) install
+endef
+
+define Host/Uninstall/Default
+ +$(NINJA) -C $(HOST_BUILD_DIR) uninstall
+endef
+
+ifneq ($(findstring c,$(OPENWRT_VERBOSE)),)
+ HOST_MAKE_FLAGS += VERBOSE=1
+endif
+
+$(eval $(call HostBuild))
diff --git a/tools/cmake/patches/100-no-testing.patch b/tools/cmake/patches/100-no-testing.patch
new file mode 100644
index 0000000..736a365
--- /dev/null
+++ b/tools/cmake/patches/100-no-testing.patch
@@ -0,0 +1,33 @@
+--- a/Modules/CTest.cmake
++++ b/Modules/CTest.cmake
+@@ -47,7 +47,7 @@ the :variable:`CTEST_USE_LAUNCHERS` vari
+ in the ``CTestConfig.cmake`` file.
+ #]=======================================================================]
+
+-option(BUILD_TESTING "Build the testing tree." ON)
++option(BUILD_TESTING "Build the testing tree." OFF)
+
+ # function to turn generator name into a version string
+ # like vs9 or vs10
+--- a/Modules/Dart.cmake
++++ b/Modules/Dart.cmake
+@@ -47,7 +47,7 @@ if(cmp0145 STREQUAL "")
+ message(AUTHOR_WARNING "${_cmp0145_warning}")
+ endif()
+
+-option(BUILD_TESTING "Build the testing tree." ON)
++option(BUILD_TESTING "Build the testing tree." OFF)
+
+ if(BUILD_TESTING)
+ # We only get here if a project already ran include(Dart),
+--- a/Tests/Contracts/VTK/Dashboard.cmake.in
++++ b/Tests/Contracts/VTK/Dashboard.cmake.in
+@@ -25,7 +25,7 @@ ctest_empty_binary_directory(${CTEST_BIN
+
+ file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "
+ VTK_BUILD_EXAMPLES:BOOL=ON
+- VTK_BUILD_TESTING:STRING=WANT
++ VTK_BUILD_TESTING:STRING=OFF
+ VTK_WRAP_PYTHON:BOOL=ON
+ ExternalData_OBJECT_STORES:FILEPATH=@base_dir@/ExternalData
+ ")
diff --git a/tools/cmake/patches/110-liblzma.patch b/tools/cmake/patches/110-liblzma.patch
new file mode 100644
index 0000000..4b8ec0d
--- /dev/null
+++ b/tools/cmake/patches/110-liblzma.patch
@@ -0,0 +1,17 @@
+--- a/Modules/FindLibLZMA.cmake
++++ b/Modules/FindLibLZMA.cmake
+@@ -61,7 +61,13 @@ The following variables are provided for
+ cmake_policy(PUSH)
+ cmake_policy(SET CMP0159 NEW) # file(STRINGS) with REGEX updates CMAKE_MATCH_<n>
+
+-find_path(LIBLZMA_INCLUDE_DIR lzma.h )
++if(UNIX)
++ find_package(PkgConfig QUIET)
++ pkg_search_module(PC_liblzma liblzma)
++endif()
++
++find_path(LIBLZMA_INCLUDE_DIR lzma.h HINTS ${PC_liblzma_INCLUDEDIR} ${PC_liblzma_INCLUDE_DIRS})
++find_library(LIBLZMA_LIBRARY NAMES lzma HINTS ${PC_liblzma_LIBDIR} ${PC_liblzma_LIBRARY_DIRS})
+ if(NOT LIBLZMA_LIBRARY)
+ find_library(LIBLZMA_LIBRARY_RELEASE NAMES lzma liblzma NAMES_PER_DIR PATH_SUFFIXES lib)
+ find_library(LIBLZMA_LIBRARY_DEBUG NAMES lzmad liblzmad NAMES_PER_DIR PATH_SUFFIXES lib)
diff --git a/tools/cmake/patches/120-curl-fix-libressl-linking.patch b/tools/cmake/patches/120-curl-fix-libressl-linking.patch
new file mode 100644
index 0000000..1921734
--- /dev/null
+++ b/tools/cmake/patches/120-curl-fix-libressl-linking.patch
@@ -0,0 +1,37 @@
+From: Jo-Philipp Wich <jo@mein.io>
+Date: Wed, 11 Jan 2017 03:36:04 +0100
+Subject: [PATCH] cmcurl: link librt
+
+When cmake is linked against LibreSSL, there might be an indirect
+dependency on librt on certain systems if LibreSSL's libcrypto uses
+clock_gettime() from librt:
+
+ [ 28%] Linking C executable LIBCURL
+ .../lib/libcrypto.a(getentropy_linux.o): In function `getentropy_fallback':
+ getentropy_linux.c:(.text+0x16d): undefined reference to `clock_gettime'
+ getentropy_linux.c:(.text+0x412): undefined reference to `clock_gettime'
+ collect2: error: ld returned 1 exit status
+ make[5]: *** [Utilities/cmcurl/LIBCURL] Error 1
+
+Modify the cmcurl CMakeLists.txt to check for clock_gettime() in librt
+and unconditionally link the rt library when the symbol is found.
+
+Signed-off-by: Jo-Philipp Wich <jo@mein.io>
+---
+--- a/Utilities/cmcurl/CMakeLists.txt
++++ b/Utilities/cmcurl/CMakeLists.txt
+@@ -648,6 +648,14 @@ if(CURL_USE_OPENSSL)
+ endif()
+ set(SSL_ENABLED ON)
+ set(USE_OPENSSL ON)
++ check_library_exists("rt" clock_gettime "" HAVE_LIBRT)
++ if(HAVE_LIBRT)
++ list(APPEND OPENSSL_LIBRARIES rt)
++ endif()
++ check_library_exists("pthread" pthread_once "" HAVE_PTHREAD)
++ if(HAVE_PTHREAD)
++ list(APPEND OPENSSL_LIBRARIES pthread)
++ endif()
+ list(APPEND CURL_LIBS ${OPENSSL_LIBRARIES})
+ include_directories(${OPENSSL_INCLUDE_DIR})
+
diff --git a/tools/cmake/patches/130-bootstrap_parallel_make_flag.patch b/tools/cmake/patches/130-bootstrap_parallel_make_flag.patch
new file mode 100644
index 0000000..a2a873f
--- /dev/null
+++ b/tools/cmake/patches/130-bootstrap_parallel_make_flag.patch
@@ -0,0 +1,14 @@
+--- a/bootstrap
++++ b/bootstrap
+@@ -1509,7 +1509,10 @@ int main(){ printf("1%c", (char)0x0a); r
+ ' > "test.c"
+ cmake_original_make_flags="${cmake_make_flags}"
+ if test "x${cmake_parallel_make}" != "x"; then
+- cmake_make_flags="${cmake_make_flags} -j ${cmake_parallel_make}"
++ case "$cmake_parallel_make" in
++ [0-9]*) cmake_parallel_make="-j ${cmake_parallel_make}";;
++ esac
++ cmake_make_flags="${cmake_make_flags} ${cmake_parallel_make}"
+ fi
+ for a in ${cmake_make_processors}; do
+ if test -z "${cmake_make_processor}" && cmake_try_make "${a}" "${cmake_make_flags}" >> ../cmake_bootstrap.log 2>&1; then
diff --git a/tools/cmake/patches/140-zlib.patch b/tools/cmake/patches/140-zlib.patch
new file mode 100644
index 0000000..17334a6
--- /dev/null
+++ b/tools/cmake/patches/140-zlib.patch
@@ -0,0 +1,20 @@
+--- a/Modules/FindZLIB.cmake
++++ b/Modules/FindZLIB.cmake
+@@ -120,10 +120,13 @@ else()
+ set(ZLIB_NAMES_DEBUG zd zlibd zdlld zlibd1 zlib1d zlibstaticd zlibwapid zlibvcd zlibstatd)
+ endif()
+
+-# Try each search configuration.
+-foreach(search ${_ZLIB_SEARCHES})
+- find_path(ZLIB_INCLUDE_DIR NAMES zlib.h ${${search}} PATH_SUFFIXES include)
+-endforeach()
++if(UNIX)
++ find_package(PkgConfig QUIET)
++ pkg_search_module(PC_zlib zlib)
++endif()
++
++find_path(ZLIB_INCLUDE_DIR zlib.h HINTS ${PC_zlib_INCLUDEDIR} ${PC_zlib_INCLUDE_DIRS})
++find_library(ZLIB_LIBRARY NAMES z HINTS ${PC_zlib_LIBDIR} ${PC_zlib_LIBRARY_DIRS})
+
+ # Allow ZLIB_LIBRARY to be set manually, as the location of the zlib library
+ if(NOT ZLIB_LIBRARY)
diff --git a/tools/cmake/patches/150-zstd-libarchive.patch b/tools/cmake/patches/150-zstd-libarchive.patch
new file mode 100644
index 0000000..a6f8e35
--- /dev/null
+++ b/tools/cmake/patches/150-zstd-libarchive.patch
@@ -0,0 +1,11 @@
+--- a/Utilities/cmlibarchive/CMakeLists.txt
++++ b/Utilities/cmlibarchive/CMakeLists.txt
+@@ -656,7 +656,7 @@ IF(ENABLE_ZSTD)
+ SET(ZSTD_FIND_QUIETLY TRUE)
+ ENDIF (ZSTD_INCLUDE_DIR)
+
+- IF(0) # CMake does not let pkg-config override its search paths.
++ IF(1) # CMake does not let pkg-config override its search paths.
+ IF(UNIX)
+ FIND_PACKAGE(PkgConfig QUIET)
+ PKG_SEARCH_MODULE(PC_ZSTD libzstd)
diff --git a/tools/cmake/patches/160-disable_xcode_generator.patch b/tools/cmake/patches/160-disable_xcode_generator.patch
new file mode 100644
index 0000000..0e29ded
--- /dev/null
+++ b/tools/cmake/patches/160-disable_xcode_generator.patch
@@ -0,0 +1,22 @@
+--- a/Source/CMakeLists.txt
++++ b/Source/CMakeLists.txt
+@@ -858,7 +858,7 @@ if(CMake_USE_XCOFF_PARSER)
+ endif()
+
+ # Xcode only works on Apple
+-if(APPLE)
++if(APPLE_DISABLED)
+ target_sources(
+ CMakeLib
+ PRIVATE
+--- a/Source/cmake.cxx
++++ b/Source/cmake.cxx
+@@ -134,7 +134,7 @@
+ # include "cmGlobalGhsMultiGenerator.h"
+ #endif
+
+-#if defined(__APPLE__)
++#if defined(__APPLE_DISABLED__)
+ # if !defined(CMAKE_BOOTSTRAP)
+ # include "cmGlobalXCodeGenerator.h"
+
diff --git a/tools/coreutils/Makefile b/tools/coreutils/Makefile
new file mode 100644
index 0000000..73b9591
--- /dev/null
+++ b/tools/coreutils/Makefile
@@ -0,0 +1,74 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=coreutils
+PKG_CPE_ID:=cpe:/a:gnu:coreutils
+PKG_VERSION:=9.5
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/coreutils
+PKG_HASH:=767ae6a22950ec42f3ba5f7c1de79dd27800ee8e9b8642da5dedb5974a1741e5
+
+HOST_BUILD_PARALLEL := 1
+
+PKG_PROGRAMS:=date readlink touch ln chown ginstall
+
+include $(INCLUDE_DIR)/host-build.mk
+
+export GNULIB_SRCDIR:=$(HOST_GNULIB_SRCDIR)
+
+HOST_GNULIB_SKIP := \
+ lib/nstrftime.c \
+ lib/fprintftime.c \
+ lib/fcntl.in.h \
+ lib/locale.in.h
+
+HOST_CONFIGURE_ARGS += \
+ --enable-install-program=$(subst $(space),$(comma),$(strip $(PKG_PROGRAMS)))
+
+HOST_MAKE_FLAGS += \
+ $(AM_TOOL_PATHS_FAKE) \
+ PROGRAMS="$(patsubst %,src/%,$(PKG_PROGRAMS))" \
+ LIBRARIES= MANS= SUBDIRS=.
+
+define Host/Bootstrap
+ ( \
+ cd $(HOST_BUILD_DIR); \
+ $(AM_TOOL_PATHS_FAKE) \
+ ./bootstrap \
+ --bootstrap-sync \
+ --force \
+ --no-git \
+ --skip-po \
+ --gnulib-srcdir=$(GNULIB_SRCDIR) \
+ )
+endef
+
+define Host/Prepare
+ $(call Host/Prepare/Default)
+ $(if $(QUILT),,$(call Host/Bootstrap))
+endef
+
+define Host/Configure
+ $(if $(QUILT),$(call Host/Bootstrap))
+ $(foreach src,$(HOST_GNULIB_SKIP),mv -f $(HOST_BUILD_DIR)/$(src)~ $(HOST_BUILD_DIR)/$(src) || true; )
+ $(call Host/Configure/Default)
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(1)/bin
+ $(INSTALL_BIN) $(patsubst %,$(HOST_BUILD_DIR)/src/%,$(PKG_PROGRAMS)) $(1)/bin/
+ ln -sf ginstall $(1)/bin/install
+endef
+
+define Host/Uninstall
+ rm -f $(STAGING_DIR_HOST)/bin/install
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/coreutils/patches/000-bootstrap.patch b/tools/coreutils/patches/000-bootstrap.patch
new file mode 100644
index 0000000..68db190
--- /dev/null
+++ b/tools/coreutils/patches/000-bootstrap.patch
@@ -0,0 +1,45 @@
+--- a/bootstrap
++++ b/bootstrap
+@@ -244,7 +244,7 @@ check_exists() {
+ ($2 --version </dev/null)
+ fi
+ else
+- ($1 --version </dev/null) >/dev/null 2>&1
++ ($@ --version </dev/null) >/dev/null 2>&1
+ fi
+
+ test $? -lt 126
+@@ -309,7 +309,7 @@ p
+ q'
+
+ get_version() {
+- app=$1
++ app="$@"
+
+ $app --version >/dev/null 2>&1 || { $app --version; return 1; }
+
+@@ -366,13 +366,13 @@ check_versions() {
+ if [ "$req_ver" = "-" ]; then
+ # Merely require app to exist; not all prereq apps are well-behaved
+ # so we have to rely on $? rather than get_version.
+- if ! check_exists --verbose $app; then
++ if ! check_exists --verbose "$app"; then
+ warn_ "Error: '$app' not found"
+ ret=1
+ fi
+ else
+ # Require app to produce a new enough version string.
+- inst_ver=$(get_version $app)
++ inst_ver=$(get_version "$app")
+ if [ ! "$inst_ver" ]; then
+ warn_ "Error: '$app' not found"
+ ret=1
+@@ -1157,7 +1157,7 @@ autogen()
+ # two just-pre-run programs.
+
+ # Import from gettext.
+- with_gettext=yes
++ with_gettext=no
+ grep '^[ ]*AM_GNU_GETTEXT_VERSION(' configure.ac >/dev/null || \
+ with_gettext=no
+
diff --git a/tools/cpio/Makefile b/tools/cpio/Makefile
new file mode 100644
index 0000000..bd6e258
--- /dev/null
+++ b/tools/cpio/Makefile
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: GPL-2.0-only
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=cpio
+PKG_CPE_ID:=cpe:/a:gnu:cpio
+PKG_VERSION:=2.15
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@GNU/cpio
+PKG_HASH:=937610b97c329a1ec9268553fb780037bcfff0dcffe9725ebc4fd9c1aa9075db
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/dosfstools/Makefile b/tools/dosfstools/Makefile
new file mode 100644
index 0000000..b332efd
--- /dev/null
+++ b/tools/dosfstools/Makefile
@@ -0,0 +1,31 @@
+#
+# Copyright (C) 2012-2015 OpenWrt.org
+# Copyright (C) 2016 LEDE-Project.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=dosfstools
+PKG_CPE_ID:=cpe:/a:dosfstools_project:dosfstools
+PKG_VERSION:=4.2
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/dosfstools/dosfstools/releases/download/v$(PKG_VERSION)/ \
+ http://fossies.org/linux/misc
+PKG_HASH:=64926eebf90092dca21b14259a5301b7b98e7b1943e8a201c7d726084809b527
+
+HOST_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+ifeq ($(HOST_OS),Darwin)
+HOST_CFLAGS += -UHAVE_ENDIAN_H
+endif
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/dosfstools/patches/100-source-date-epoch.patch b/tools/dosfstools/patches/100-source-date-epoch.patch
new file mode 100644
index 0000000..c758caa
--- /dev/null
+++ b/tools/dosfstools/patches/100-source-date-epoch.patch
@@ -0,0 +1,150 @@
+From 8da7bc93315cb0c32ad868f17808468b81fa76ec Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Bj=C3=B8rn=20Forsman?= <bjorn.forsman@gmail.com>
+Date: Wed, 5 Dec 2018 19:52:51 +0100
+Subject: [PATCH] Honor the SOURCE_DATE_EPOCH variable
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+Implement the SOURCE_DATE_EPOCH specification[1] for reproducible
+builds. If SOURCE_DATE_EPOCH is set, use it as timestamp instead of the
+current time.
+
+[1] https://reproducible-builds.org/specs/source-date-epoch/
+
+Signed-off-by: Bjørn Forsman <bjorn.forsman@gmail.com>
+---
+ src/boot.c | 23 +++++++++++++++++++++--
+ src/common.c | 18 ++++++++++++++++--
+ src/mkfs.fat.c | 19 ++++++++++++++++---
+ 3 files changed, 53 insertions(+), 7 deletions(-)
+
+--- a/src/boot.c
++++ b/src/boot.c
+@@ -33,6 +33,8 @@
+ #include <stdlib.h>
+ #include <sys/types.h>
+ #include <time.h>
++#include <errno.h>
++#include <ctype.h>
+
+ #include "common.h"
+ #include "fsck.fat.h"
+@@ -672,6 +674,7 @@ void write_volume_label(DOS_FS * fs, cha
+ {
+ time_t now;
+ struct tm *mtime;
++ char *source_date_epoch = NULL;
+ off_t offset;
+ int created;
+ DIR_ENT de;
+@@ -687,8 +690,24 @@ void write_volume_label(DOS_FS * fs, cha
+ if (de.name[0] == 0xe5)
+ de.name[0] = 0x05;
+
+- now = time(NULL);
+- mtime = (now != (time_t)-1) ? localtime(&now) : NULL;
++ source_date_epoch = getenv("SOURCE_DATE_EPOCH");
++ if (source_date_epoch) {
++ char *tmp = NULL;
++ long long conversion = 0;
++ errno = 0;
++ conversion = strtoll(source_date_epoch, &tmp, 10);
++ now = conversion;
++ if (!isdigit((unsigned char)*source_date_epoch) || *tmp != '\0'
++ || errno != 0 || (long long)now != conversion) {
++ die("SOURCE_DATE_EPOCH is too big or contains non-digits: \"%s\"",
++ source_date_epoch);
++ }
++ mtime = gmtime(&now);
++ } else {
++ now = time(NULL);
++ mtime = (now != (time_t)-1) ? localtime(&now) : NULL;
++ }
++
+ if (mtime && mtime->tm_year >= 80 && mtime->tm_year <= 207) {
+ de.time = htole16((unsigned short)((mtime->tm_sec >> 1) +
+ (mtime->tm_min << 5) +
+--- a/src/common.c
++++ b/src/common.c
+@@ -30,6 +30,7 @@
+ #include <string.h>
+ #include <stdarg.h>
+ #include <errno.h>
++#include <ctype.h>
+ #include <wctype.h>
+ #include <termios.h>
+ #include <sys/time.h>
+@@ -298,8 +299,21 @@ void check_atari(void)
+ uint32_t generate_volume_id(void)
+ {
+ struct timeval now;
++ char *source_date_epoch = NULL;
+
+- if (gettimeofday(&now, NULL) != 0 || now.tv_sec == (time_t)-1 || now.tv_sec < 0) {
++ source_date_epoch = getenv("SOURCE_DATE_EPOCH");
++ if (source_date_epoch) {
++ char *tmp = NULL;
++ long long conversion = 0;
++ errno = 0;
++ conversion = strtoll(source_date_epoch, &tmp, 10);
++ if (!isdigit((unsigned char)*source_date_epoch) || *tmp != '\0'
++ || errno != 0) {
++ die("SOURCE_DATE_EPOCH is too big or contains non-digits: \"%s\"",
++ source_date_epoch);
++ }
++ return (uint32_t)conversion;
++ } else if (gettimeofday(&now, NULL) != 0 || now.tv_sec == (time_t)-1 || now.tv_sec < 0) {
+ srand(getpid());
+ /* rand() returns int from [0,RAND_MAX], therefore only 31 bits */
+ return (((uint32_t)(rand() & 0xFFFF)) << 16) | ((uint32_t)(rand() & 0xFFFF));
+--- a/src/mkfs.fat.c
++++ b/src/mkfs.fat.c
+@@ -1074,7 +1074,7 @@ static void setup_tables(void)
+ }
+
+ /* If is not available then generate random 32 bit disk signature */
+- if (invariant)
++ if (invariant || getenv("SOURCE_DATE_EPOCH"))
+ disk_sig = volume_id;
+ else if (!disk_sig)
+ disk_sig = generate_volume_id();
+@@ -1287,7 +1287,7 @@ static void setup_tables(void)
+ de->name[0] = 0x05;
+ de->attr = ATTR_VOLUME;
+ if (create_time != (time_t)-1) {
+- if (!invariant)
++ if (!invariant && !getenv("SOURCE_DATE_EPOCH"))
+ ctime = localtime(&create_time);
+ else
+ ctime = gmtime(&create_time);
+@@ -1477,6 +1477,7 @@ int main(int argc, char **argv)
+ int blocks_specified = 0;
+ struct timeval create_timeval;
+ long long conversion;
++ char *source_date_epoch = NULL;
+
+ enum {OPT_HELP=1000, OPT_INVARIANT, OPT_MBR, OPT_VARIANT, OPT_CODEPAGE, OPT_OFFSET};
+ const struct option long_options[] = {
+@@ -1497,8 +1498,20 @@ int main(int argc, char **argv)
+ program_name = p + 1;
+ }
+
+- if (gettimeofday(&create_timeval, NULL) == 0 && create_timeval.tv_sec != (time_t)-1)
++ source_date_epoch = getenv("SOURCE_DATE_EPOCH");
++ if (source_date_epoch) {
++ errno = 0;
++ conversion = strtoll(source_date_epoch, &tmp, 10);
++ create_time = conversion;
++ if (!isdigit((unsigned char)*source_date_epoch) || *tmp != '\0'
++ || errno != 0 || (long long)create_time != conversion) {
++ die("SOURCE_DATE_EPOCH is too big or contains non-digits: \"%s\"",
++ source_date_epoch);
++ }
++ } else if (gettimeofday(&create_timeval, NULL) == 0 && create_timeval.tv_sec != (time_t)-1) {
+ create_time = create_timeval.tv_sec;
++ }
++
+ volume_id = generate_volume_id();
+ check_atari();
+
diff --git a/tools/dosfstools/patches/101-config-switch-to-AC_CHECK_LIB.patch b/tools/dosfstools/patches/101-config-switch-to-AC_CHECK_LIB.patch
new file mode 100644
index 0000000..ba2d00b
--- /dev/null
+++ b/tools/dosfstools/patches/101-config-switch-to-AC_CHECK_LIB.patch
@@ -0,0 +1,28 @@
+From e7671c2a3be03d790cbc225cd3e784b5434fb5da Mon Sep 17 00:00:00 2001
+From: David Bauer <mail@david-bauer.net>
+Date: Mon, 16 Jan 2023 01:29:22 +0100
+Subject: [PATCH] config: switch to AC_CHECK_LIB
+
+This fixes spurious build-errors on OpenWrt, where the AM_ICONV macro
+is undefined while invoking autoconfig. Later in the build, the ICONV
+LDOPTIONS are set to @LIBICONV@, failing the build.
+
+Signed-off-by: David Bauer <mail@david-bauer.net>
+---
+ configure.ac | 5 +----
+ 1 file changed, 1 insertion(+), 4 deletions(-)
+
+--- a/configure.ac
++++ b/configure.ac
+@@ -70,10 +70,7 @@ AC_CHECK_DECLS([getmntent], [], [], [[#i
+ AC_CHECK_DECLS([getmntinfo], [], [], [[#include <sys/mount.h>]])
+
+ # optional iconv support
+-AC_ARG_WITH([iconv], AS_HELP_STRING([--without-iconv], [build without iconv support]))
+-if test "x$with_iconv" != "xno"; then
+- AM_ICONV
+-fi
++AC_CHECK_LIB(iconv, iconv_open)
+
+ # xxd (distributed with vim) is used in the testsuite
+ AC_CHECK_PROG([XXD_FOUND], [xxd], [yes])
diff --git a/tools/dwarves/Makefile b/tools/dwarves/Makefile
new file mode 100644
index 0000000..5346126
--- /dev/null
+++ b/tools/dwarves/Makefile
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=dwarves
+PKG_VERSION:=1.28
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=https://fedorapeople.org/~acme/dwarves/
+PKG_HASH:=826efc0fc9237d3c1e9c01553ea387a8cb46e8dc119ff863889043f4ed54b2ae
+
+PKG_MAINTAINER:=Tony Ambardar <itugrok@yahoo.com>
+PKG_LICENSE:=GPL-2.0-only
+PKG_LICENSE_FILES:=COPYING
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_HOST_OPTIONS += \
+ -D__LIB=lib \
+ -DCMAKE_INSTALL_RPATH="$(STAGING_DIR_HOST)/lib" \
+ -DCMAKE_SKIP_RPATH=FALSE
+
+define Host/Clean
+ $(RM) $(STAGING_DIR_HOST)/bin/{codiff,ctracer,dtagnames,pahole,pdwtags}
+ $(RM) $(STAGING_DIR_HOST)/bin/{pfunct,pglobal,prefcnt,scncopy,syscse}
+ $(RM) $(STAGING_DIR_HOST)/bin/{ostra-cg,btfdiff,fullcircle}
+ $(RM) $(STAGING_DIR_HOST)/lib/libdwarves*.so*
+ $(RM) $(STAGING_DIR_HOST)/share/man/man1/pahole.1
+ rm -rf $(STAGING_DIR_HOST)/include/dwarves
+ rm -rf $(STAGING_DIR_HOST)/share/dwarves
+ $(call Host/Clean/Default)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/dwarves/patches/100-reproducible-builds.patch b/tools/dwarves/patches/100-reproducible-builds.patch
new file mode 100644
index 0000000..d8cbd11
--- /dev/null
+++ b/tools/dwarves/patches/100-reproducible-builds.patch
@@ -0,0 +1,12 @@
+--- a/pahole.c
++++ b/pahole.c
+@@ -3681,6 +3681,9 @@ int main(int argc, char *argv[])
+ goto out;
+ }
+
++ if (getenv("SOURCE_DATE_EPOCH") || getenv("KBUILD_BUILD_TIMESTAMP"))
++ conf_load.reproducible_build = true;
++
+ if (dwarves__init()) {
+ fputs("pahole: insufficient memory\n", stderr);
+ goto out;
diff --git a/tools/e2fsprogs/Makefile b/tools/e2fsprogs/Makefile
new file mode 100644
index 0000000..50c3888
--- /dev/null
+++ b/tools/e2fsprogs/Makefile
@@ -0,0 +1,55 @@
+#
+# Copyright (C) 2010-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=e2fsprogs
+PKG_CPE_ID:=cpe:/a:e2fsprogs_project:e2fsprogs
+PKG_VERSION:=1.47.0
+PKG_HASH:=0b4fe723d779b0927fb83c9ae709bc7b40f66d7df36433bef143e41c54257084
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@KERNEL/linux/kernel/people/tytso/e2fsprogs/v$(PKG_VERSION)/
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+ifneq ($(shell $(HOSTCC) --version | grep clang),)
+ HOST_CFLAGS += -D__GNUC_PREREQ\(...\)=0 -Dloff_t=off_t
+endif
+HOST_CFLAGS += $(HOST_FPIC)
+
+HOST_CONFIGURE_ARGS += \
+ --disable-elf-shlibs \
+ --disable-libuuid \
+ --disable-tls \
+ --disable-nls \
+ --enable-threads=pth \
+ --disable-fuse2fs \
+ --with-crond-dir=no
+
+# The following uses pkg-config the wrong way around. Just override it.
+HOST_CONFIGURE_VARS += \
+ ac_cv_lib_uuid_uuid_generate=yes
+
+define Host/Prepare
+ $(call Host/Prepare/Default)
+ rm -rf $(HOST_BUILD_DIR)/doc
+endef
+
+define Host/Install
+ $(call Host/Install/Default)
+ $(SED) 's|^DIR=.*|DIR=$$$${STAGING_DIR_HOST}/share/et|' $(STAGING_DIR_HOST)/bin/compile_et
+ $(SED) 's|^DIR=.*|DIR=$$$${STAGING_DIR_HOST}/share/ss|' $(STAGING_DIR_HOST)/bin/mk_cmds
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/elftosb/Makefile b/tools/elftosb/Makefile
new file mode 100644
index 0000000..9079ac5
--- /dev/null
+++ b/tools/elftosb/Makefile
@@ -0,0 +1,26 @@
+#
+# Copyright (C) 2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=elftosb
+PKG_VERSION:=10.12.01
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=http://repository.timesys.com/buildsources/e/elftosb/elftosb-10.12.01/
+PKG_HASH:=77bb6981620f7575b87d136d94c7daa88dd09195959cc75fc18b138369ecd42b
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR) LDFLAGS="$(HOST_LDFLAGS)"
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/bld/linux/elftosb $(STAGING_DIR_HOST)/bin/elftosb
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/elftosb/patches/001-libm.patch b/tools/elftosb/patches/001-libm.patch
new file mode 100644
index 0000000..6b49ac1
--- /dev/null
+++ b/tools/elftosb/patches/001-libm.patch
@@ -0,0 +1,11 @@
+--- a/makefile.rules
++++ b/makefile.rules
+@@ -101,7 +101,7 @@ OBJ_FILES_KEYGEN = \
+ keygen.o
+
+
+-LIBS = -lstdc++
++LIBS = -lstdc++ -lm
+
+
+ ifeq ("${UNAMES}", "Linux")
diff --git a/tools/elftosb/patches/002-fix-header-path.patch b/tools/elftosb/patches/002-fix-header-path.patch
new file mode 100644
index 0000000..5099b29
--- /dev/null
+++ b/tools/elftosb/patches/002-fix-header-path.patch
@@ -0,0 +1,18 @@
+This package had an absolute path for sys/types.h, which doesn't
+make much sense. It breaks on newer Ubuntu systems, and probably many
+others once multiarch becomes more common.
+
+This patch makes the types a relative path, and allows the system
+to use whatever include paths it feels are correct.
+
+--- a/common/stdafx.h
++++ b/common/stdafx.h
+@@ -27,7 +27,7 @@
+ // For Linux systems only, types.h only defines the signed
+ // integer types. This is not professional code.
+ // Update: They are defined in the header files in the more recent version of redhat enterprise gcc.
+-#include "/usr/include/sys/types.h"
++#include <sys/types.h>
+ #include <stdint.h>
+ //typedef unsigned long uint32_t;
+ //typedef unsigned short uint16_t;
diff --git a/tools/elftosb/patches/003-use-ldflags.patch b/tools/elftosb/patches/003-use-ldflags.patch
new file mode 100644
index 0000000..82fd1e8
--- /dev/null
+++ b/tools/elftosb/patches/003-use-ldflags.patch
@@ -0,0 +1,26 @@
+--- a/makefile.rules
++++ b/makefile.rules
+@@ -131,19 +131,20 @@ exec_always:
+ @echo "LIBS = ${LIBS}"
+ @echo "EXEC_FILE = ${EXEC_FILE}"
+ @echo "BUILD_DIR = ${BUILD_DIR}"
++ @echo "LDFLAGS = ${LDFLAGS}"
+
+ clean:
+ rm -f ${OBJ_FILES_ELFTOSB2} ${OBJ_FILES_SBTOOL} ${OBJ_FILES_KEYGEN} \
+ ${EXEC_FILE_ELFTOSB2} ${EXEC_FILE_SBTOOL} ${EXEC_FILE_KEYGEN}
+
+ elftosb: ${OBJ_FILES_ELFTOSB2}
+- gcc ${OBJ_FILES_ELFTOSB2} ${LIBS} -o ${EXEC_FILE_ELFTOSB2}
++ gcc ${OBJ_FILES_ELFTOSB2} ${LIBS} ${LDFLAGS} -o ${EXEC_FILE_ELFTOSB2}
+
+ sbtool: ${OBJ_FILES_SBTOOL}
+- gcc ${OBJ_FILES_SBTOOL} ${LIBS} -o ${EXEC_FILE_SBTOOL}
++ gcc ${OBJ_FILES_SBTOOL} ${LIBS} ${LDFLAGS} -o ${EXEC_FILE_SBTOOL}
+
+ keygen: ${OBJ_FILES_KEYGEN}
+- gcc ${OBJ_FILES_KEYGEN} ${LIBS} -o ${EXEC_FILE_KEYGEN}
++ gcc ${OBJ_FILES_KEYGEN} ${LIBS} ${LDFLAGS} -o ${EXEC_FILE_KEYGEN}
+
+
+ #ifeq ("${UNAMES}", "Linux")
diff --git a/tools/elfutils/Makefile b/tools/elfutils/Makefile
new file mode 100644
index 0000000..2836cad
--- /dev/null
+++ b/tools/elfutils/Makefile
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=elfutils
+PKG_VERSION:=0.191
+PKG_RELEASE:=2
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=https://sourceware.org/$(PKG_NAME)/ftp/$(PKG_VERSION)
+PKG_HASH:=df76db71366d1d708365fc7a6c60ca48398f14367eb2b8954efc8897147ad871
+
+PKG_LICENSE:=GPL-3.0-or-later
+PKG_LICENSE_FILES:=COPYING COPYING-GPLV2 COPYING-LGPLV3
+PKG_CPE_ID:=cpe:/a:elfutils_project:elfutils
+
+PKG_FIXUP:=autoreconf
+
+PKG_PROGRAMS:=elflint findtextrel elfcmp unstrip stack elfcompress elfclassify srcfiles
+
+PKG_SUBDIRS := \
+ config \
+ lib \
+ libelf \
+ libcpu \
+ backends \
+ libebl \
+ libdwelf \
+ libdwfl \
+ libdw \
+ src
+
+PKG_GNULIB_BASE:=libgnu
+
+PKG_GNULIB_ARGS = \
+ --dir=$(HOST_BUILD_DIR) \
+ --libtool \
+ --avoid=reallocarray \
+ --import
+
+PKG_GNULIB_MODS = \
+ argp \
+ fallocate-posix \
+ fnmatch-gnu \
+ fts \
+ obstack \
+ progname \
+ strchrnul \
+ tsearch
+
+include $(INCLUDE_DIR)/host-build.mk
+
+export $(PKG_GNULIB_BASE)=$(HOST_BUILD_DIR)/$(PKG_GNULIB_BASE)/.libs/$(PKG_GNULIB_BASE).a
+export $(PKG_GNULIB_BASE)_fallocate-posix=$(HOST_BUILD_DIR)/$(PKG_GNULIB_BASE)/$(PKG_GNULIB_BASE)_la-posix_fallocate.o
+export $(PKG_GNULIB_BASE)_tsearch=$(HOST_BUILD_DIR)/$(PKG_GNULIB_BASE)/$(PKG_GNULIB_BASE)_la-tsearch.o
+
+HOST_MAKE_FLAGS += \
+ DEFAULT_INCLUDES='-I. -I$$$$(top_builddir) -I$$$$(top_srcdir)/$(PKG_GNULIB_BASE)' \
+ AM_LDFLAGS='$$$$(STACK_USAGE_NO_ERROR)' \
+ LIBS+='$$$$(if $$$$(findstring $(lastword $(PKG_SUBDIRS)),$$$$(subdir)), $$$$($(PKG_GNULIB_BASE)))' \
+ LIBS+='$$$$(wildcard $$$$($(PKG_GNULIB_BASE)_fallocate-posix))' \
+ LIBS+='$$$$(wildcard $$$$($(PKG_GNULIB_BASE)_tsearch))' \
+ REPLACE_FCNTL=0 REPLACE_FREE=0 REPLACE_FSTAT=0 REPLACE_OPEN=0 \
+ bin_PROGRAMS='$(PKG_PROGRAMS)' EXEEXT=
+
+HOST_CPPFLAGS += "'-I$$$$(top_srcdir)/lib'"
+
+ifeq ($(HOST_OS),Darwin)
+ HOST_CFLAGS += -I/opt/homebrew/include
+endif
+
+HOST_CFLAGS += -Wno-error -fPIC
+
+HOST_CONFIGURE_ARGS += \
+ --without-libintl-prefix \
+ --without-libiconv-prefix \
+ --disable-debuginfod \
+ --disable-libdebuginfod \
+ --disable-nls \
+ --disable-shared \
+ --enable-static \
+ --without-lzma \
+ --without-bzlib \
+ --without-zstd
+
+ifeq ($(HOST_OS),Darwin)
+ HOST_CONFIGURE_ARGS += --disable-symbol-versioning
+endif
+
+HOST_CONFIGURE_VARS += \
+ ac_cv_search_argp_parse=yes \
+ ac_cv_search_fts_close=yes \
+ ac_cv_search__obstack_free=yes \
+ ac_cv_buildid=yes
+
+Hooks/HostConfigure/Pre := Host/Gnulib/Prepare $(Hooks/HostConfigure/Pre)
+Hooks/HostCompile/Pre := Host/Gnulib/Compile $(Hooks/HostCompile/Pre)
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/elfutils/patches/010-backport-mips-support-reloc.patch b/tools/elfutils/patches/010-backport-mips-support-reloc.patch
new file mode 100644
index 0000000..8a65e4e
--- /dev/null
+++ b/tools/elfutils/patches/010-backport-mips-support-reloc.patch
@@ -0,0 +1,2525 @@
+From 8d3bb7db9d6f07decfc59d83988cda54e5a8b0cd Mon Sep 17 00:00:00 2001
+From: Ying Huang <ying.huang@oss.cipunited.com>
+Date: Tue, 5 Mar 2024 17:51:17 +0800
+Subject: [PATCH 1/7] Support Mips architecture
+
+ * backends/Makefile.am (modules): Add mips.
+ (mips_SRCS): New var for mips_init.c mips_symbol.c.
+ (libebl_backends_a_SOURCES): Add mips_SRCS.
+ * backends/mips_init.c: New file.
+ * backends/mips_reloc.def: Likewise.
+ * backends/mips_symbol.c: Likewise.
+ * libebl/eblopenbackend.c (mips_init): Declare.
+ (machines): Add mips.
+ * libelf/libelfP.h: Add ELF64_MIPS_R_TYPE{1,2,3}
+
+Signed-off-by: Ying Huang <ying.huang@oss.cipunited.com>
+---
+ backends/Makefile.am | 6 ++-
+ backends/mips_init.c | 52 +++++++++++++++++++++++
+ backends/mips_reloc.def | 93 +++++++++++++++++++++++++++++++++++++++++
+ backends/mips_symbol.c | 63 ++++++++++++++++++++++++++++
+ libebl/eblopenbackend.c | 2 +
+ libelf/libelfP.h | 3 ++
+ 6 files changed, 217 insertions(+), 2 deletions(-)
+ create mode 100644 backends/mips_init.c
+ create mode 100644 backends/mips_reloc.def
+ create mode 100644 backends/mips_symbol.c
+
+--- a/backends/Makefile.am
++++ b/backends/Makefile.am
+@@ -37,7 +37,7 @@ AM_CPPFLAGS += -I$(top_srcdir)/libebl -I
+ noinst_LIBRARIES = libebl_backends.a libebl_backends_pic.a
+
+ modules = i386 sh x86_64 ia64 alpha arm aarch64 sparc ppc ppc64 s390 \
+- m68k bpf riscv csky loongarch arc
++ m68k bpf riscv csky loongarch arc mips
+
+ i386_SRCS = i386_init.c i386_symbol.c i386_corenote.c i386_cfi.c \
+ i386_retval.c i386_regs.c i386_auxv.c \
+@@ -102,12 +102,16 @@ loongarch_SRCS = loongarch_init.c loonga
+
+ arc_SRCS = arc_init.c arc_symbol.c
+
++mips_SRCS = mips_init.c mips_symbol.c mips_attrs.c mips_initreg.c \
++ mips_cfi.c mips_unwind.c mips_regs.c mips_retval.c \
++ mips_corenote.c mips64_corenote.c
++
+ libebl_backends_a_SOURCES = $(i386_SRCS) $(sh_SRCS) $(x86_64_SRCS) \
+ $(ia64_SRCS) $(alpha_SRCS) $(arm_SRCS) \
+ $(aarch64_SRCS) $(sparc_SRCS) $(ppc_SRCS) \
+ $(ppc64_SRCS) $(s390_SRCS) \
+ $(m68k_SRCS) $(bpf_SRCS) $(riscv_SRCS) $(csky_SRCS) \
+- $(loongarch_SRCS) $(arc_SRCS)
++ $(loongarch_SRCS) $(arc_SRCS) $(mips_SRCS)
+
+ libebl_backends_pic_a_SOURCES =
+ am_libebl_backends_pic_a_OBJECTS = $(libebl_backends_a_SOURCES:.c=.os)
+--- /dev/null
++++ b/backends/mips_init.c
+@@ -0,0 +1,74 @@
++/* Initialization of MIPS specific backend library.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#define BACKEND mips_
++#define RELOC_PREFIX R_MIPS_
++#include "libebl_CPU.h"
++#include "libelfP.h"
++
++#define RELOC_TYPE_ID(type) ((type) & 0xff)
++
++/* This defines the common reloc hooks based on mips_reloc.def. */
++#include "common-reloc.c"
++
++extern __typeof (EBLHOOK (core_note)) mips64_core_note attribute_hidden;
++
++Ebl *
++mips_init (Elf *elf __attribute__ ((unused)),
++ GElf_Half machine __attribute__ ((unused)),
++ Ebl *eh)
++{
++ /* We handle it. */
++ mips_init_reloc (eh);
++ HOOK (eh, reloc_simple_type);
++ HOOK (eh, section_type_name);
++ HOOK (eh, machine_flag_check);
++ HOOK (eh, machine_flag_name);
++ HOOK (eh, machine_section_flag_check);
++ HOOK (eh, segment_type_name);
++ HOOK (eh, dynamic_tag_check);
++ HOOK (eh, dynamic_tag_name);
++ HOOK (eh, check_object_attribute);
++ HOOK (eh, check_special_symbol);
++ HOOK (eh, check_reloc_target_type);
++ HOOK (eh, set_initial_registers_tid);
++ HOOK (eh, abi_cfi);
++ HOOK (eh, unwind);
++ HOOK (eh, register_info);
++ HOOK (eh, return_value_location);
++ if (eh->class == ELFCLASS64)
++ eh->core_note = mips64_core_note;
++ else
++ HOOK (eh, core_note);
++ eh->frame_nregs = 71;
++ return eh;
++}
+--- /dev/null
++++ b/backends/mips_reloc.def
+@@ -0,0 +1,93 @@
++/* List the relocation types for MIPS. -*- C -*-
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++/* NAME, REL|EXEC|DYN */
++
++
++RELOC_TYPE (NONE, REL|EXEC|DYN)
++RELOC_TYPE (16, REL|EXEC|DYN)
++RELOC_TYPE (32, REL)
++RELOC_TYPE (REL32, REL|EXEC|DYN)
++RELOC_TYPE (26, REL|DYN)
++RELOC_TYPE (HI16, REL)
++RELOC_TYPE (LO16, REL|EXEC|DYN)
++RELOC_TYPE (GPREL16, REL|EXEC|DYN)
++RELOC_TYPE (LITERAL, REL|EXEC|DYN)
++RELOC_TYPE (GOT16, REL|EXEC|DYN)
++RELOC_TYPE (PC16, REL)
++RELOC_TYPE (CALL16, REL)
++RELOC_TYPE (GPREL32, REL)
++RELOC_TYPE (SHIFT5, REL)
++RELOC_TYPE (SHIFT6, REL)
++RELOC_TYPE (64, REL)
++RELOC_TYPE (GOT_DISP, REL)
++RELOC_TYPE (GOT_PAGE, REL)
++RELOC_TYPE (GOT_OFST, REL)
++RELOC_TYPE (GOT_HI16, REL)
++RELOC_TYPE (GOT_LO16, REL)
++RELOC_TYPE (SUB, REL)
++RELOC_TYPE (INSERT_A, REL)
++RELOC_TYPE (INSERT_B, REL)
++RELOC_TYPE (DELETE, REL)
++RELOC_TYPE (HIGHER, REL)
++RELOC_TYPE (HIGHEST, REL)
++RELOC_TYPE (CALL_HI16, REL)
++RELOC_TYPE (CALL_LO16, REL)
++RELOC_TYPE (SCN_DISP, REL)
++RELOC_TYPE (REL16, REL)
++RELOC_TYPE (ADD_IMMEDIATE, REL)
++RELOC_TYPE (PJUMP, REL)
++RELOC_TYPE (RELGOT, REL)
++RELOC_TYPE (JALR, REL)
++RELOC_TYPE (TLS_DTPMOD32, DYN)
++RELOC_TYPE (TLS_DTPREL32, REL)
++RELOC_TYPE (TLS_DTPMOD64, DYN)
++RELOC_TYPE (TLS_DTPREL64, REL)
++RELOC_TYPE (TLS_GD, REL)
++RELOC_TYPE (TLS_LDM, REL)
++RELOC_TYPE (TLS_DTPREL_HI16, REL)
++RELOC_TYPE (TLS_DTPREL_LO16, REL)
++RELOC_TYPE (TLS_GOTTPREL, REL)
++RELOC_TYPE (TLS_TPREL32, REL)
++RELOC_TYPE (TLS_TPREL64, REL)
++RELOC_TYPE (TLS_TPREL_HI16, REL)
++RELOC_TYPE (TLS_TPREL_LO16, REL)
++RELOC_TYPE (GLOB_DAT, REL)
++RELOC_TYPE (PC21_S2, REL)
++RELOC_TYPE (PC26_S2, REL)
++RELOC_TYPE (PC18_S3, REL)
++RELOC_TYPE (PC19_S2, REL)
++RELOC_TYPE (PCHI16, REL)
++RELOC_TYPE (PCLO16, REL)
++RELOC_TYPE (COPY, REL)
++RELOC_TYPE (JUMP_SLOT, REL)
++RELOC_TYPE (PC32, REL)
++RELOC_TYPE (EH, REL)
++RELOC_TYPE (GNU_REL16_S2, REL)
++RELOC_TYPE (GNU_VTINHERIT, REL)
++RELOC_TYPE (GNU_VTENTRY, REL)
+--- /dev/null
++++ b/backends/mips_symbol.c
+@@ -0,0 +1,671 @@
++/* MIPS specific symbolic name handling.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <system.h>
++
++#include <elf.h>
++#include <stddef.h>
++#include <string.h>
++#include <stdio.h>
++#define BACKEND mips_
++#include "libebl_CPU.h"
++#include "libelfP.h"
++
++/* Check for the simple reloc types. */
++Elf_Type
++mips_reloc_simple_type (Ebl *ebl, int type,
++ int *addsub __attribute__ ((unused)))
++{
++ int typeNew = type;
++ if(ebl->elf->class == ELFCLASS64)
++ typeNew = ELF64_MIPS_R_TYPE1(type);
++ switch (typeNew)
++ {
++ case R_MIPS_64:
++ return ELF_T_XWORD;
++ case R_MIPS_32:
++ return ELF_T_WORD;
++ case R_MIPS_16:
++ return ELF_T_HALF;
++
++ default:
++ return ELF_T_NUM;
++ }
++}
++
++/* copy binutils-2.34/binutils/readelf.c get_mips_section_type_name */
++const char *
++mips_section_type_name (int type,
++ char *buf __attribute__ ((unused)),
++ size_t len __attribute__ ((unused)))
++{
++ switch (type)
++ {
++ case SHT_MIPS_LIBLIST:
++ return "MIPS_LIBLIST";
++ case SHT_MIPS_MSYM:
++ return "MIPS_MSYM";
++ case SHT_MIPS_CONFLICT:
++ return "MIPS_CONFLICT";
++ case SHT_MIPS_GPTAB:
++ return "MIPS_GPTAB";
++ case SHT_MIPS_UCODE:
++ return "MIPS_UCODE";
++ case SHT_MIPS_DEBUG:
++ return "MIPS_DEBUG";
++ case SHT_MIPS_REGINFO:
++ return "MIPS_REGINFO";
++ case SHT_MIPS_PACKAGE:
++ return "MIPS_PACKAGE";
++ case SHT_MIPS_PACKSYM:
++ return "MIPS_PACKSYM";
++ case SHT_MIPS_RELD:
++ return "MIPS_RELD";
++ case SHT_MIPS_IFACE:
++ return "MIPS_IFACE";
++ case SHT_MIPS_CONTENT:
++ return "MIPS_CONTENT";
++ case SHT_MIPS_OPTIONS:
++ return "MIPS_OPTIONS";
++ case SHT_MIPS_SHDR:
++ return "MIPS_SHDR";
++ case SHT_MIPS_FDESC:
++ return "MIPS_FDESC";
++ case SHT_MIPS_EXTSYM:
++ return "MIPS_EXTSYM";
++ case SHT_MIPS_DENSE:
++ return "MIPS_DENSE";
++ case SHT_MIPS_PDESC:
++ return "MIPS_PDESC";
++ case SHT_MIPS_LOCSYM:
++ return "MIPS_LOCSYM";
++ case SHT_MIPS_AUXSYM:
++ return "MIPS_AUXSYM";
++ case SHT_MIPS_OPTSYM:
++ return "MIPS_OPTSYM";
++ case SHT_MIPS_LOCSTR:
++ return "MIPS_LOCSTR";
++ case SHT_MIPS_LINE:
++ return "MIPS_LINE";
++ case SHT_MIPS_RFDESC:
++ return "MIPS_RFDESC";
++ case SHT_MIPS_DELTASYM:
++ return "MIPS_DELTASYM";
++ case SHT_MIPS_DELTAINST:
++ return "MIPS_DELTAINST";
++ case SHT_MIPS_DELTACLASS:
++ return "MIPS_DELTACLASS";
++ case SHT_MIPS_DWARF:
++ return "MIPS_DWARF";
++ case SHT_MIPS_DELTADECL:
++ return "MIPS_DELTADECL";
++ case SHT_MIPS_SYMBOL_LIB:
++ return "MIPS_SYMBOL_LIB";
++ case SHT_MIPS_EVENTS:
++ return "MIPS_EVENTS";
++ case SHT_MIPS_TRANSLATE:
++ return "MIPS_TRANSLATE";
++ case SHT_MIPS_PIXIE:
++ return "MIPS_PIXIE";
++ case SHT_MIPS_XLATE:
++ return "MIPS_XLATE";
++ case SHT_MIPS_XLATE_DEBUG:
++ return "MIPS_XLATE_DEBUG";
++ case SHT_MIPS_WHIRL:
++ return "MIPS_WHIRL";
++ case SHT_MIPS_EH_REGION:
++ return "MIPS_EH_REGION";
++ case SHT_MIPS_XLATE_OLD:
++ return "MIPS_XLATE_OLD";
++ case SHT_MIPS_PDR_EXCEPTION:
++ return "MIPS_PDR_EXCEPTION";
++ case SHT_MIPS_ABIFLAGS:
++ return "MIPS_ABIFLAGS";
++ case SHT_MIPS_XHASH:
++ return "MIPS_XHASH";
++ default:
++ break;
++ }
++ return NULL;
++}
++
++bool
++mips_check_reloc_target_type (Ebl *ebl __attribute__ ((unused)), Elf64_Word sh_type)
++{
++ return (sh_type == SHT_MIPS_DWARF);
++}
++
++/* Check whether given symbol's st_value and st_size are OK despite failing
++ normal checks. */
++bool
++mips_check_special_symbol (Elf *elf,
++ const GElf_Sym *sym __attribute__ ((unused)),
++ const char *name __attribute__ ((unused)),
++ const GElf_Shdr *destshdr)
++{
++ size_t shstrndx;
++ if (elf_getshdrstrndx (elf, &shstrndx) != 0)
++ return false;
++ const char *sname = elf_strptr (elf, shstrndx, destshdr->sh_name);
++ if (sname == NULL)
++ return false;
++ return (strcmp (sname, ".got") == 0 || strcmp (sname, ".bss") == 0);
++}
++
++/* Check whether SHF_MASKPROC flags are valid. */
++bool
++mips_machine_section_flag_check (GElf_Xword sh_flags)
++{
++ return ((sh_flags &~ (SHF_MIPS_GPREL |
++ SHF_MIPS_MERGE |
++ SHF_MIPS_ADDR |
++ SHF_MIPS_STRINGS |
++ SHF_MIPS_NOSTRIP |
++ SHF_MIPS_LOCAL |
++ SHF_MIPS_NAMES |
++ SHF_MIPS_NODUPE)) == 0);
++}
++
++/* Check whether machine flags are valid. */
++bool
++mips_machine_flag_check (GElf_Word flags)
++{
++ if ((flags &~ (EF_MIPS_NOREORDER |
++ EF_MIPS_PIC |
++ EF_MIPS_CPIC |
++ EF_MIPS_UCODE |
++ EF_MIPS_ABI2 |
++ EF_MIPS_OPTIONS_FIRST |
++ EF_MIPS_32BITMODE |
++ EF_MIPS_NAN2008 |
++ EF_MIPS_FP64 |
++ EF_MIPS_ARCH_ASE_MDMX |
++ EF_MIPS_ARCH_ASE_M16 |
++ EF_MIPS_ARCH_ASE_MICROMIPS)) == 0)
++ return false;
++
++ switch(flags & EF_MIPS_MACH)
++ {
++ case EF_MIPS_MACH_3900:
++ case EF_MIPS_MACH_4010:
++ case EF_MIPS_MACH_4100:
++ case EF_MIPS_MACH_4111:
++ case EF_MIPS_MACH_4120:
++ case EF_MIPS_MACH_4650:
++ case EF_MIPS_MACH_5400:
++ case EF_MIPS_MACH_5500:
++ case EF_MIPS_MACH_5900:
++ case EF_MIPS_MACH_SB1:
++ case EF_MIPS_MACH_9000:
++ case EF_MIPS_MACH_LS2E:
++ case EF_MIPS_MACH_LS2F:
++ case EF_MIPS_MACH_GS464:
++ case EF_MIPS_MACH_GS464E:
++ case EF_MIPS_MACH_GS264E:
++ case EF_MIPS_MACH_OCTEON:
++ case EF_MIPS_MACH_OCTEON2:
++ case EF_MIPS_MACH_OCTEON3:
++ case EF_MIPS_MACH_XLR:
++ case EF_MIPS_MACH_IAMR2:
++ case 0:
++ break;
++ default:
++ return false;
++ }
++
++ switch ((flags & EF_MIPS_ABI))
++ {
++ case EF_MIPS_ABI_O32:
++ case EF_MIPS_ABI_O64:
++ case EF_MIPS_ABI_EABI32:
++ case EF_MIPS_ABI_EABI64:
++ case 0:
++ break;
++ default:
++ return false;
++ }
++
++ switch ((flags & EF_MIPS_ARCH))
++ {
++ case EF_MIPS_ARCH_1:
++ case EF_MIPS_ARCH_2:
++ case EF_MIPS_ARCH_3:
++ case EF_MIPS_ARCH_4:
++ case EF_MIPS_ARCH_5:
++ case EF_MIPS_ARCH_32:
++ case EF_MIPS_ARCH_32R2:
++ case EF_MIPS_ARCH_32R6:
++ case EF_MIPS_ARCH_64:
++ case EF_MIPS_ARCH_64R2:
++ case EF_MIPS_ARCH_64R6:
++ return true;
++ default:
++ return false;
++ }
++ return false;
++}
++
++/* copy binutils-2.34/binutils/readelf.c get_machine_flags */
++const char *
++mips_machine_flag_name (Elf64_Word orig __attribute__ ((unused)), Elf64_Word *flagref)
++{
++ if (*flagref & EF_MIPS_NOREORDER)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_NOREORDER);
++ return "noreorder";
++ }
++
++ if (*flagref & EF_MIPS_PIC)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_PIC);
++ return "pic";
++ }
++
++ if (*flagref & EF_MIPS_CPIC)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_CPIC);
++ return "cpic";
++ }
++
++ if (*flagref & EF_MIPS_UCODE)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_UCODE);
++ return "ugen_reserved";
++ }
++
++ if (*flagref & EF_MIPS_ABI2)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI2);
++ return "abi2";
++ }
++
++ if (*flagref & EF_MIPS_OPTIONS_FIRST)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_OPTIONS_FIRST);
++ return "odk first";
++ }
++
++ if (*flagref & EF_MIPS_32BITMODE)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_32BITMODE);
++ return "32bitmode";
++ }
++
++ if (*flagref & EF_MIPS_NAN2008)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_NAN2008);
++ return "nan2008";
++ }
++
++ if (*flagref & EF_MIPS_FP64)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_FP64);
++ return "fp64";
++ }
++
++ switch (*flagref & EF_MIPS_MACH)
++ {
++ case EF_MIPS_MACH_3900:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_3900);
++ return "3900";
++ case EF_MIPS_MACH_4010:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_4010);
++ return "4010";
++ case EF_MIPS_MACH_4100:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_4100);
++ return "4100";
++ case EF_MIPS_MACH_4111:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_4111);
++ return "4111";
++ case EF_MIPS_MACH_4120:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_4120);
++ return "4120";
++ case EF_MIPS_MACH_4650:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_4650);
++ return "4650";
++ case EF_MIPS_MACH_5400:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_5400);
++ return "5400";
++ case EF_MIPS_MACH_5500:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_5500);
++ return "5500";
++ case EF_MIPS_MACH_5900:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_5900);
++ return "5900";
++ case EF_MIPS_MACH_SB1:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_SB1);
++ return "sb1";
++ case EF_MIPS_MACH_9000:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_9000);
++ return "9000";
++ case EF_MIPS_MACH_LS2E:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_LS2E);
++ return "loongson-2e";
++ case EF_MIPS_MACH_LS2F:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_LS2F);
++ return "loongson-2f";
++ case EF_MIPS_MACH_GS464:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_GS464);
++ return "gs464";
++ case EF_MIPS_MACH_GS464E:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_GS464E);
++ return "gs464e";
++ case EF_MIPS_MACH_GS264E:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_GS264E);
++ return "gs264e";
++ case EF_MIPS_MACH_OCTEON:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_OCTEON);
++ return "octeon";
++ case EF_MIPS_MACH_OCTEON2:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_OCTEON2);
++ return "octeon2";
++ case EF_MIPS_MACH_OCTEON3:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_OCTEON3);
++ return "octeon3";
++ case EF_MIPS_MACH_XLR:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_XLR);
++ return "xlr";
++ case EF_MIPS_MACH_IAMR2:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH_IAMR2);
++ return "interaptiv-mr2";
++ case 0:
++ /* We simply ignore the field in this case to avoid confusion:
++ MIPS ELF does not specify EF_MIPS_MACH, it is a GNU
++ extension. */
++ break;
++ default:
++ *flagref &= ~((Elf64_Word) EF_MIPS_MACH);
++ return "unknown CPU";
++ }
++ switch (*flagref & EF_MIPS_ABI)
++ {
++ case EF_MIPS_ABI_O32:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI_O32);
++ return "o32";
++ case EF_MIPS_ABI_O64:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI_O64);
++ return "o64";
++ case EF_MIPS_ABI_EABI32:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI_EABI32);
++ return "eabi32";
++ case EF_MIPS_ABI_EABI64:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI_EABI64);
++ return "eabi64";
++ case 0:
++ /* We simply ignore the field in this case to avoid confusion:
++ MIPS ELF does not specify EF_MIPS_ABI, it is a GNU extension.
++ This means it is likely to be an o32 file, but not for
++ sure. */
++ break;
++ default:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ABI);
++ return "unknown ABI";
++ }
++
++ if (*flagref & EF_MIPS_ARCH_ASE_MDMX)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_ASE_MDMX);
++ return "mdmx";
++ }
++
++ if (*flagref & EF_MIPS_ARCH_ASE_M16)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_ASE_M16);
++ return "mips16";
++ }
++
++ if (*flagref & EF_MIPS_ARCH_ASE_MICROMIPS)
++ {
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_ASE_MICROMIPS);
++ return "micromips";
++ }
++
++ switch (*flagref & EF_MIPS_ARCH)
++ {
++ case EF_MIPS_ARCH_1:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_1);
++ return "mips1";
++ case EF_MIPS_ARCH_2:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_2);
++ return "mips2";
++ case EF_MIPS_ARCH_3:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_3);
++ return "mips3";
++ case EF_MIPS_ARCH_4:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_4);
++ return "mips4";
++ case EF_MIPS_ARCH_5:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_5);
++ return "mips5";
++ case EF_MIPS_ARCH_32:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_32);
++ return "mips32";
++ case EF_MIPS_ARCH_32R2:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_32R2);
++ return "mips32r2";
++ case EF_MIPS_ARCH_32R6:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_32R6);
++ return "mips32r6";
++ case EF_MIPS_ARCH_64:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_64);
++ return "mips64";
++ case EF_MIPS_ARCH_64R2:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_64R2);
++ return "mips64r2";
++ case EF_MIPS_ARCH_64R6:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH_64R6);
++ return "mips64r6";
++ default:
++ *flagref &= ~((Elf64_Word) EF_MIPS_ARCH);
++ return "unknown ISA";
++ }
++ return NULL;
++}
++
++/* copy binutils-2.34/binutils/readelf.c get_mips_segment_type */
++const char *
++mips_segment_type_name (int segment, char *buf __attribute__ ((unused)),
++ size_t len __attribute__ ((unused)))
++{
++ switch (segment)
++ {
++ case PT_MIPS_REGINFO:
++ return "REGINFO";
++ case PT_MIPS_RTPROC:
++ return "RTPROC";
++ case PT_MIPS_OPTIONS:
++ return "OPTIONS";
++ case PT_MIPS_ABIFLAGS:
++ return "ABIFLAGS";
++ default:
++ return NULL;
++ }
++}
++
++bool
++mips_dynamic_tag_check (int64_t tag)
++{
++ return ((tag &~ (DT_MIPS_RLD_VERSION
++ | DT_MIPS_TIME_STAMP
++ | DT_MIPS_ICHECKSUM
++ | DT_MIPS_IVERSION
++ | DT_MIPS_FLAGS
++ | DT_MIPS_BASE_ADDRESS
++ | DT_MIPS_MSYM
++ | DT_MIPS_CONFLICT
++ | DT_MIPS_LIBLIST
++ | DT_MIPS_LOCAL_GOTNO
++ | DT_MIPS_CONFLICTNO
++ | DT_MIPS_LIBLISTNO
++ | DT_MIPS_SYMTABNO
++ | DT_MIPS_UNREFEXTNO
++ | DT_MIPS_GOTSYM
++ | DT_MIPS_HIPAGENO
++ | DT_MIPS_RLD_MAP
++ | DT_MIPS_DELTA_CLASS
++ | DT_MIPS_DELTA_CLASS_NO
++ | DT_MIPS_DELTA_INSTANCE
++ | DT_MIPS_DELTA_INSTANCE_NO
++ | DT_MIPS_DELTA_RELOC
++ | DT_MIPS_DELTA_RELOC_NO
++ | DT_MIPS_DELTA_SYM
++ | DT_MIPS_DELTA_SYM_NO
++ | DT_MIPS_DELTA_CLASSSYM
++ | DT_MIPS_DELTA_CLASSSYM_NO
++ | DT_MIPS_CXX_FLAGS
++ | DT_MIPS_PIXIE_INIT
++ | DT_MIPS_SYMBOL_LIB
++ | DT_MIPS_LOCALPAGE_GOTIDX
++ | DT_MIPS_LOCAL_GOTIDX
++ | DT_MIPS_HIDDEN_GOTIDX
++ | DT_MIPS_PROTECTED_GOTIDX
++ | DT_MIPS_OPTIONS
++ | DT_MIPS_INTERFACE
++ | DT_MIPS_DYNSTR_ALIGN
++ | DT_MIPS_INTERFACE_SIZE
++ | DT_MIPS_RLD_TEXT_RESOLVE_ADDR
++ | DT_MIPS_PERF_SUFFIX
++ | DT_MIPS_COMPACT_SIZE
++ | DT_MIPS_GP_VALUE
++ | DT_MIPS_AUX_DYNAMIC
++ | DT_MIPS_PLTGOT
++ | DT_MIPS_RWPLT
++ | DT_MIPS_RLD_MAP_REL
++ | DT_MIPS_XHASH)) == 0);
++}
++
++/* copy binutils-2.34/binutils/readelf.c get_mips_dynamic_type*/
++const char *
++mips_dynamic_tag_name (int64_t tag, char *buf __attribute__ ((unused)),
++ size_t len __attribute__ ((unused)))
++{
++ switch (tag)
++ {
++ case DT_MIPS_RLD_VERSION:
++ return "MIPS_RLD_VERSION";
++ case DT_MIPS_TIME_STAMP:
++ return "MIPS_TIME_STAMP";
++ case DT_MIPS_ICHECKSUM:
++ return "MIPS_ICHECKSUM";
++ case DT_MIPS_IVERSION:
++ return "MIPS_IVERSION";
++ case DT_MIPS_FLAGS:
++ return "MIPS_FLAGS";
++ case DT_MIPS_BASE_ADDRESS:
++ return "MIPS_BASE_ADDRESS";
++ case DT_MIPS_MSYM:
++ return "MIPS_MSYM";
++ case DT_MIPS_CONFLICT:
++ return "MIPS_CONFLICT";
++ case DT_MIPS_LIBLIST:
++ return "MIPS_LIBLIST";
++ case DT_MIPS_LOCAL_GOTNO:
++ return "MIPS_LOCAL_GOTNO";
++ case DT_MIPS_CONFLICTNO:
++ return "MIPS_CONFLICTNO";
++ case DT_MIPS_LIBLISTNO:
++ return "MIPS_LIBLISTNO";
++ case DT_MIPS_SYMTABNO:
++ return "MIPS_SYMTABNO";
++ case DT_MIPS_UNREFEXTNO:
++ return "MIPS_UNREFEXTNO";
++ case DT_MIPS_GOTSYM:
++ return "MIPS_GOTSYM";
++ case DT_MIPS_HIPAGENO:
++ return "MIPS_HIPAGENO";
++ case DT_MIPS_RLD_MAP:
++ return "MIPS_RLD_MAP";
++ case DT_MIPS_RLD_MAP_REL:
++ return "MIPS_RLD_MAP_REL";
++ case DT_MIPS_DELTA_CLASS:
++ return "MIPS_DELTA_CLASS";
++ case DT_MIPS_DELTA_CLASS_NO:
++ return "MIPS_DELTA_CLASS_NO";
++ case DT_MIPS_DELTA_INSTANCE:
++ return "MIPS_DELTA_INSTANCE";
++ case DT_MIPS_DELTA_INSTANCE_NO:
++ return "MIPS_DELTA_INSTANCE_NO";
++ case DT_MIPS_DELTA_RELOC:
++ return "MIPS_DELTA_RELOC";
++ case DT_MIPS_DELTA_RELOC_NO:
++ return "MIPS_DELTA_RELOC_NO";
++ case DT_MIPS_DELTA_SYM:
++ return "MIPS_DELTA_SYM";
++ case DT_MIPS_DELTA_SYM_NO:
++ return "MIPS_DELTA_SYM_NO";
++ case DT_MIPS_DELTA_CLASSSYM:
++ return "MIPS_DELTA_CLASSSYM";
++ case DT_MIPS_DELTA_CLASSSYM_NO:
++ return "MIPS_DELTA_CLASSSYM_NO";
++ case DT_MIPS_CXX_FLAGS:
++ return "MIPS_CXX_FLAGS";
++ case DT_MIPS_PIXIE_INIT:
++ return "MIPS_PIXIE_INIT";
++ case DT_MIPS_SYMBOL_LIB:
++ return "MIPS_SYMBOL_LIB";
++ case DT_MIPS_LOCALPAGE_GOTIDX:
++ return "MIPS_LOCALPAGE_GOTIDX";
++ case DT_MIPS_LOCAL_GOTIDX:
++ return "MIPS_LOCAL_GOTIDX";
++ case DT_MIPS_HIDDEN_GOTIDX:
++ return "MIPS_HIDDEN_GOTIDX";
++ case DT_MIPS_PROTECTED_GOTIDX:
++ return "MIPS_PROTECTED_GOTIDX";
++ case DT_MIPS_OPTIONS:
++ return "MIPS_OPTIONS";
++ case DT_MIPS_INTERFACE:
++ return "MIPS_INTERFACE";
++ case DT_MIPS_DYNSTR_ALIGN:
++ return "MIPS_DYNSTR_ALIGN";
++ case DT_MIPS_INTERFACE_SIZE:
++ return "MIPS_INTERFACE_SIZE";
++ case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
++ return "MIPS_RLD_TEXT_RESOLVE_ADDR";
++ case DT_MIPS_PERF_SUFFIX:
++ return "MIPS_PERF_SUFFIX";
++ case DT_MIPS_COMPACT_SIZE:
++ return "MIPS_COMPACT_SIZE";
++ case DT_MIPS_GP_VALUE:
++ return "MIPS_GP_VALUE";
++ case DT_MIPS_AUX_DYNAMIC:
++ return "MIPS_AUX_DYNAMIC";
++ case DT_MIPS_PLTGOT:
++ return "MIPS_PLTGOT";
++ case DT_MIPS_RWPLT:
++ return "MIPS_RWPLT";
++ case DT_MIPS_XHASH:
++ return "MIPS_XHASH";
++ default:
++ return NULL;
++ }
++ return NULL;
++}
+--- a/libebl/eblopenbackend.c
++++ b/libebl/eblopenbackend.c
+@@ -57,6 +57,7 @@ Ebl *riscv_init (Elf *, GElf_Half, Ebl *
+ Ebl *csky_init (Elf *, GElf_Half, Ebl *);
+ Ebl *loongarch_init (Elf *, GElf_Half, Ebl *);
+ Ebl *arc_init (Elf *, GElf_Half, Ebl *);
++Ebl *mips_init (Elf *, GElf_Half, Ebl *);
+
+ /* This table should contain the complete list of architectures as far
+ as the ELF specification is concerned. */
+@@ -154,6 +155,7 @@ static const struct
+ { csky_init, "elf_csky", "csky", 4, EM_CSKY, ELFCLASS32, ELFDATA2LSB },
+ { loongarch_init, "elf_loongarch", "loongarch", 9, EM_LOONGARCH, ELFCLASS64, ELFDATA2LSB },
+ { arc_init, "elf_arc", "arc", 3, EM_ARCV2, ELFCLASS32, ELFDATA2LSB },
++ { mips_init, "elf_mips", "mips", 4, EM_MIPS, 0, 0 },
+ };
+ #define nmachines (sizeof (machines) / sizeof (machines[0]))
+
+--- a/libelf/libelfP.h
++++ b/libelf/libelfP.h
+@@ -617,4 +617,8 @@ extern void __libelf_reset_rawdata (Elf_
+ #define INVALID_NDX(ndx, type, data) \
+ unlikely ((data)->d_size / sizeof (type) <= (unsigned int) (ndx))
+
++#define ELF64_MIPS_R_TYPE1(i) ((i) & 0xff)
++#define ELF64_MIPS_R_TYPE2(i) (((i) >> 8) & 0xff)
++#define ELF64_MIPS_R_TYPE3(i) (((i) >> 16) & 0xff)
++#define is_debug_section_type(type) (type == SHT_PROGBITS || type == SHT_MIPS_DWARF)
+ #endif /* libelfP.h */
+--- /dev/null
++++ b/backends/mips_cfi.c
+@@ -0,0 +1,68 @@
++/* MIPS ABI-specified defaults for DWARF CFI.
++ Copyright (C) 2009 Red Hat, Inc.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <dwarf.h>
++
++#define BACKEND mips_
++#include "libebl_CPU.h"
++
++int
++mips_abi_cfi (Ebl *ebl __attribute__ ((unused)), Dwarf_CIE *abi_info)
++{
++ static const uint8_t abi_cfi[] =
++ {
++ DW_CFA_def_cfa, ULEB128_7 (31), ULEB128_7 (0),
++ /* Callee-saved regs. */
++ DW_CFA_same_value, ULEB128_7 (16), /* s0 */
++ DW_CFA_same_value, ULEB128_7 (17), /* s1 */
++ DW_CFA_same_value, ULEB128_7 (18), /* s2 */
++ DW_CFA_same_value, ULEB128_7 (19), /* s3 */
++ DW_CFA_same_value, ULEB128_7 (20), /* s4 */
++ DW_CFA_same_value, ULEB128_7 (21), /* s5 */
++ DW_CFA_same_value, ULEB128_7 (22), /* s6 */
++ DW_CFA_same_value, ULEB128_7 (23), /* s7 */
++ DW_CFA_same_value, ULEB128_7 (28), /* gp */
++ DW_CFA_same_value, ULEB128_7 (29), /* sp */
++ DW_CFA_same_value, ULEB128_7 (30), /* fp */
++
++ DW_CFA_val_offset, ULEB128_7 (29), ULEB128_7 (0),
++ };
++
++ abi_info->initial_instructions = abi_cfi;
++ abi_info->initial_instructions_end = &abi_cfi[sizeof abi_cfi];
++ abi_info->data_alignment_factor = 8;
++
++ abi_info->return_address_register = 31; /* %ra */
++
++ return 0;
++}
+--- /dev/null
++++ b/backends/mips_initreg.c
+@@ -0,0 +1,61 @@
++/* Fetch live process registers from TID.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <stdlib.h>
++#if (defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__)) && defined(__linux__)
++# include <sys/user.h>
++# include <sys/ptrace.h>
++#include <asm/ptrace.h>
++#endif
++
++#define BACKEND mips_
++#include "libebl_CPU.h"
++
++
++bool
++mips_set_initial_registers_tid (pid_t tid __attribute__ ((unused)),
++ ebl_tid_registers_t *setfunc __attribute__ ((unused)),
++ void *arg __attribute__ ((unused)))
++{
++#if (!defined(mips) && !defined(__mips) && !defined(__mips__) && !defined(MIPS) && !defined(__MIPS__)) || !defined(__linux__)
++ return false;
++#else /* __mips__ */
++/* For PTRACE_GETREGS */
++
++ struct pt_regs gregs;
++ if (ptrace (PTRACE_GETREGS, tid, 0, &gregs) != 0)
++ return false;
++ if (! setfunc (-1, 1, (Dwarf_Word *) &gregs.cp0_epc, arg))
++ return false;
++ return setfunc (0, 32, (Dwarf_Word *) &gregs.regs[0], arg);
++#endif /* __mips__ */
++}
+--- /dev/null
++++ b/backends/mips_unwind.c
+@@ -0,0 +1,84 @@
++/* Get previous frame state for an existing frame state.
++ Copyright (C) 2016 The Qt Company Ltd.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#define BACKEND mips_
++#define SP_REG 29
++#define FP_REG 30
++#define LR_REG 31
++#define FP_OFFSET 0
++#define LR_OFFSET 8
++#define SP_OFFSET 16
++
++#include "libebl_CPU.h"
++
++/* There was no CFI. Maybe we happen to have a frame pointer and can unwind from that? */
++
++bool
++EBLHOOK(unwind) (Ebl *ebl __attribute__ ((unused)), Dwarf_Addr pc __attribute__ ((unused)),
++ ebl_tid_registers_t *setfunc, ebl_tid_registers_get_t *getfunc,
++ ebl_pid_memory_read_t *readfunc, void *arg,
++ bool *signal_framep __attribute__ ((unused)))
++{
++ Dwarf_Word fp, lr, sp;
++
++ if (!getfunc(LR_REG, 1, &lr, arg))
++ return false;
++
++ if (lr == 0 || !setfunc(-1, 1, &lr, arg))
++ return false;
++
++ if (!getfunc(FP_REG, 1, &fp, arg))
++ fp = 0;
++
++ if (!getfunc(SP_REG, 1, &sp, arg))
++ sp = 0;
++
++ Dwarf_Word newLr, newFp, newSp;
++
++ if (!readfunc(fp + LR_OFFSET, &newLr, arg))
++ newLr = 0;
++
++ if (!readfunc(fp + FP_OFFSET, &newFp, arg))
++ newFp = 0;
++
++ newSp = fp + SP_OFFSET;
++
++ // These are not fatal if they don't work. They will just prevent unwinding at the next frame.
++ setfunc(LR_REG, 1, &newLr, arg);
++ setfunc(FP_REG, 1, &newFp, arg);
++ setfunc(SP_REG, 1, &newSp, arg);
++
++ // If the fp is invalid, we might still have a valid lr.
++ // But if the fp is valid, then the stack should be moving in the right direction.
++ return fp == 0 || newSp > sp;
++}
+--- /dev/null
++++ b/backends/mips_corenote.c
+@@ -0,0 +1,104 @@
++/* MIPS specific core note handling.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <elf.h>
++#include <inttypes.h>
++#include <stddef.h>
++#include <stdio.h>
++#include <sys/time.h>
++#include "libebl_CPU.h"
++
++#ifndef BITS
++# define BITS 32
++#define BACKEND mips_
++#else
++# define BITS 64
++# define BACKEND mips64_
++#endif
++
++#define PRSTATUS_REGS_SIZE (45 * (BITS / 8))
++static const Ebl_Register_Location prstatus_regs[] =
++ {
++ { .offset = 0, .regno = 0, .count = (BITS == 32 ? 40 : 34), .bits = BITS },
++ { .offset = BITS/8 * (BITS == 32 ? 41 : 35), .regno = (BITS == 32 ? 41 : 35), .count = (BITS == 32 ? 4 : 10), .bits = BITS },
++ };
++
++#define PRSTATUS_REGSET_ITEMS \
++ { \
++ .name = "pc", .type = ELF_T_ADDR, .format = 'x', \
++ .offset = offsetof (struct EBLHOOK(prstatus), pr_reg) + ((BITS/8) * (BITS == 32 ? 40 : 34)), \
++ .group = "register", \
++ .pc_register = true \
++ }
++
++static const Ebl_Register_Location mips_fpregset_regs[] =
++ {
++ { .offset = 0, .regno = 38, .count = 32, .bits = 64 }, /* fp0-fp31 */
++ };
++
++static const Ebl_Core_Item mips_fpregset_items[] =
++ {
++ {
++ .name = "fcs", .type = ELF_T_WORD, .format = 'x',
++ .offset = 32 * 8, .group = "register"
++ },
++ {
++ .name = "fir", .type = ELF_T_WORD, .format = 'x',
++ .offset = 32 * 8 + 4, .group = "register"
++ }
++ };
++
++#if BITS == 32
++# define ULONG uint32_t
++# define ALIGN_ULONG 4
++# define TYPE_ULONG ELF_T_WORD
++#define TYPE_LONG ELF_T_SWORD
++#else
++#define ULONG uint64_t
++#define ALIGN_ULONG 8
++#define TYPE_ULONG ELF_T_XWORD
++#define TYPE_LONG ELF_T_SXWORD
++#endif
++#define PID_T int32_t
++#define UID_T uint32_t
++#define GID_T uint32_t
++#define ALIGN_PID_T 4
++#define ALIGN_UID_T 4
++#define ALIGN_GID_T 4
++#define TYPE_PID_T ELF_T_SWORD
++#define TYPE_UID_T ELF_T_WORD
++#define TYPE_GID_T ELF_T_WORD
++
++#define EXTRA_NOTES \
++ EXTRA_REGSET_ITEMS (NT_FPREGSET, 32 * 8 + 4 * 2, mips_fpregset_regs, mips_fpregset_items)
++
++#include "linux-core-note.c"
+--- /dev/null
++++ b/backends/mips_regs.c
+@@ -0,0 +1,135 @@
++/* Register names and numbers for mips DWARF.
++ Copyright (C) 2006 Red Hat, Inc.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <assert.h>
++#include <dwarf.h>
++#include <string.h>
++
++#define BACKEND mips_
++#include "libebl_CPU.h"
++#include <system.h>
++ssize_t
++mips_register_info (Ebl *ebl __attribute__ ((unused)),
++ int regno, char *name, size_t namelen,
++ const char **prefix, const char **setname,
++ int *bits, int *type)
++{
++ if (name == NULL)
++ return 72;
++
++ if (regno < 0 || regno > 71 || namelen < 4)
++ return -1;
++
++ *prefix = "$";
++ if (regno < 38)
++ {
++ *setname = "integer";
++ *type = DW_ATE_signed;
++ *bits = 32;
++ }
++ else
++ {
++ *setname = "FPU";
++ *type = DW_ATE_float;
++ *bits = 64;
++ }
++
++ if (regno < 32)
++ {
++ if (regno < 10)
++ {
++ name[0] = regno + '0';
++ namelen = 1;
++ }
++ else
++ {
++ name[0] = (regno / 10) + '0';
++ name[1] = (regno % 10) + '0';
++ namelen = 2;
++ }
++ if (regno == 28 || regno == 29 || regno == 31)
++ *type = DW_ATE_address;
++ }
++ else if (regno == 32)
++ {
++ return stpcpy (name, "lo") + 1 - name;
++ }
++ else if (regno == 33)
++ {
++ return stpcpy (name, "hi") + 1 - name;
++ }
++ else if (regno == 34)
++ {
++ return stpcpy (name, "pc") + 1 - name;
++ }
++ else if (regno == 35)
++ {
++ *type = DW_ATE_address;
++ return stpcpy (name, "bad") + 1 - name;
++ }
++ else if (regno == 36)
++ {
++ return stpcpy (name, "sr") + 1 - name;
++ }
++ else if (regno == 37)
++ {
++ *type = DW_ATE_address;
++ return stpcpy (name, "cause") + 1 - name;
++ }
++ else if (regno < 70)
++ {
++ name[0] = 'f';
++ if (regno < 38 + 10)
++ {
++ name[1] = (regno - 38) + '0';
++ namelen = 2;
++ }
++ else
++ {
++ name[1] = (regno - 38) / 10 + '0';
++ name[2] = (regno - 38) % 10 + '0';
++ namelen = 3;
++ }
++ }
++ else if (regno == 70)
++ {
++ return stpcpy (name, "fsr") + 1 - name;
++ }
++ else if (regno == 71)
++ {
++ return stpcpy (name, "fir") + 1 - name;
++ }
++
++ name[namelen++] = '\0';
++ return namelen;
++}
+--- /dev/null
++++ b/backends/mips_retval.c
+@@ -0,0 +1,196 @@
++/* Function return value location for Linux/mips ABI.
++ Copyright (C) 2005 Red Hat, Inc.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <assert.h>
++#include <dwarf.h>
++#include <string.h>
++#include <elf.h>
++#include <stdio.h>
++
++#define BACKEND mips_
++#include "libebl_CPU.h"
++#include "libdwP.h"
++#include <stdio.h>
++
++/* $v0 or pair $v0, $v1 */
++static const Dwarf_Op loc_intreg_o32[] =
++ {
++ { .atom = DW_OP_reg2 }, { .atom = DW_OP_piece, .number = 4 },
++ { .atom = DW_OP_reg3 }, { .atom = DW_OP_piece, .number = 4 },
++ };
++
++static const Dwarf_Op loc_intreg[] =
++ {
++ { .atom = DW_OP_reg2 }, { .atom = DW_OP_piece, .number = 8 },
++ { .atom = DW_OP_reg3 }, { .atom = DW_OP_piece, .number = 8 },
++ };
++#define nloc_intreg 1
++#define nloc_intregpair 4
++
++/* $f0 (float), or pair $f0, $f1 (double).
++ * f2/f3 are used for COMPLEX (= 2 doubles) returns in Fortran */
++static const Dwarf_Op loc_fpreg_o32[] =
++ {
++ { .atom = DW_OP_regx, .number = 32 }, { .atom = DW_OP_piece, .number = 4 },
++ { .atom = DW_OP_regx, .number = 33 }, { .atom = DW_OP_piece, .number = 4 },
++ { .atom = DW_OP_regx, .number = 34 }, { .atom = DW_OP_piece, .number = 4 },
++ { .atom = DW_OP_regx, .number = 35 }, { .atom = DW_OP_piece, .number = 4 },
++ };
++
++/* $f0, or pair $f0, $f2. */
++static const Dwarf_Op loc_fpreg[] =
++ {
++ { .atom = DW_OP_regx, .number = 32 }, { .atom = DW_OP_piece, .number = 8 },
++ { .atom = DW_OP_regx, .number = 34 }, { .atom = DW_OP_piece, .number = 8 },
++ };
++#define nloc_fpreg 1
++#define nloc_fpregpair 4
++#define nloc_fpregquad 8
++
++/* The return value is a structure and is actually stored in stack space
++ passed in a hidden argument by the caller. But, the compiler
++ helpfully returns the address of that space in $v0. */
++static const Dwarf_Op loc_aggregate[] =
++ {
++ { .atom = DW_OP_breg2, .number = 0 }
++ };
++#define nloc_aggregate 1
++
++int
++mips_return_value_location (Dwarf_Die *functypedie, const Dwarf_Op **locp)
++{
++ unsigned int regsize = (gelf_getclass (functypedie->cu->dbg->elf) == ELFCLASS32 ) ? 4 : 8;
++ if (!regsize)
++ return -2;
++
++ /* Start with the function's type, and get the DW_AT_type attribute,
++ which is the type of the return value. */
++
++ Dwarf_Attribute attr_mem;
++ Dwarf_Attribute *attr = dwarf_attr_integrate (functypedie, DW_AT_type, &attr_mem);
++ if (attr == NULL)
++ /* The function has no return value, like a `void' function in C. */
++ return 0;
++
++ Dwarf_Die die_mem;
++ Dwarf_Die *typedie = dwarf_formref_die (attr, &die_mem);
++ int tag = dwarf_tag (typedie);
++
++ /* Follow typedefs and qualifiers to get to the actual type. */
++ while (tag == DW_TAG_typedef
++ || tag == DW_TAG_const_type || tag == DW_TAG_volatile_type
++ || tag == DW_TAG_restrict_type)
++ {
++ attr = dwarf_attr_integrate (typedie, DW_AT_type, &attr_mem);
++ typedie = dwarf_formref_die (attr, &die_mem);
++ tag = dwarf_tag (typedie);
++ }
++
++ switch (tag)
++ {
++ case -1:
++ return -1;
++
++ case DW_TAG_subrange_type:
++ if (! dwarf_hasattr_integrate (typedie, DW_AT_byte_size))
++ {
++ attr = dwarf_attr_integrate (typedie, DW_AT_type, &attr_mem);
++ typedie = dwarf_formref_die (attr, &die_mem);
++ tag = dwarf_tag (typedie);
++ }
++ /* Fall through. */
++ FALLTHROUGH;
++
++ case DW_TAG_base_type:
++ case DW_TAG_enumeration_type:
++ CASE_POINTER:
++ {
++ Dwarf_Word size;
++ if (dwarf_formudata (dwarf_attr_integrate (typedie, DW_AT_byte_size,
++ &attr_mem), &size) != 0)
++ {
++ if (dwarf_is_pointer (tag))
++ size = regsize;
++ else
++ return -1;
++ }
++ if (tag == DW_TAG_base_type)
++ {
++ Dwarf_Word encoding;
++ if (dwarf_formudata (dwarf_attr_integrate (typedie, DW_AT_encoding,
++ &attr_mem), &encoding) != 0)
++ return -1;
++
++#define ARCH_LOC(loc, regsize) ((regsize) == 4 ? (loc ## _o32) : (loc))
++
++ if (encoding == DW_ATE_float)
++ {
++ *locp = ARCH_LOC(loc_fpreg, regsize);
++ if (size <= regsize)
++ return nloc_fpreg;
++
++ if (size <= 2*regsize)
++ return nloc_fpregpair;
++
++ if (size <= 4*regsize)
++ return nloc_fpregquad;
++
++ goto aggregate;
++ }
++ }
++ *locp = ARCH_LOC(loc_intreg, regsize);
++ if (size <= regsize)
++ return nloc_intreg;
++ if (size <= 2*regsize)
++ return nloc_intregpair;
++
++ /* Else fall through. Shouldn't happen though (at least with gcc) */
++ }
++ FALLTHROUGH;
++
++ case DW_TAG_structure_type:
++ case DW_TAG_class_type:
++ case DW_TAG_union_type:
++ case DW_TAG_array_type:
++ aggregate:
++ *locp = loc_aggregate;
++ return nloc_aggregate;
++ case DW_TAG_unspecified_type:
++ return 0;
++ }
++
++ /* XXX We don't have a good way to return specific errors from ebl calls.
++ This value means we do not understand the type, but it is well-formed
++ DWARF and might be valid. */
++ return -2;
++}
+--- a/libelf/elf_getdata.c
++++ b/libelf/elf_getdata.c
+@@ -135,6 +135,119 @@ __libelf_data_type (GElf_Ehdr *ehdr, int
+
+ /* Convert the data in the current section. */
+ static void
++convert_data_for_mips64el (Elf_Scn *scn, int eclass,
++ int data, size_t size, Elf_Type type)
++{
++ /* Do we need to convert the data and/or adjust for alignment? */
++ if (data == MY_ELFDATA || type == ELF_T_BYTE)
++ {
++ /* In order to adapt macro GELF_R_SYM and GELF_R_TYPE on mips64, need to convert
++ relocation info(raw data). Some eu-utils use read-mmap method to map file, so
++ we need to malloc and memcpy raw data to avoid segment fault. After modification,
++ the correct value are saved in the malloced memory not in process address space. */
++ scn->data_base = malloc (size);
++ if (scn->data_base == NULL)
++ {
++ __libelf_seterrno (ELF_E_NOMEM);
++ return;
++ }
++
++ /* The copy will be appropriately aligned for direct access. */
++ memcpy (scn->data_base, scn->rawdata_base, size);
++ }
++ else
++ {
++ xfct_t fp;
++
++ scn->data_base = malloc (size);
++ if (scn->data_base == NULL)
++ {
++ __libelf_seterrno (ELF_E_NOMEM);
++ return;
++ }
++
++ /* Make sure the source is correctly aligned for the conversion
++ function to directly access the data elements. */
++ char *rawdata_source;
++ /* In order to adapt macro GELF_R_SYM and GELF_R_TYPE on mips64, need to convert
++ relocation info(raw data). Some eu-utils use read-mmap method to map file, so
++ we need to malloc and memcpy raw data to avoid segment fault. After modification,
++ the correct value are saved in the malloced memory not in process address space. */
++ rawdata_source = malloc (size);
++ if (rawdata_source == NULL)
++ {
++ __libelf_seterrno (ELF_E_NOMEM);
++ return;
++ }
++
++ /* The copy will be appropriately aligned for direct access. */
++ memcpy (rawdata_source, scn->rawdata_base, size);
++
++ /* Get the conversion function. */
++ fp = __elf_xfctstom[eclass - 1][type];
++
++ fp (scn->data_base, rawdata_source, size, 0);
++
++ if (rawdata_source != scn->rawdata_base)
++ free (rawdata_source);
++ }
++
++ scn->data_list.data.d.d_buf = scn->data_base;
++ scn->data_list.data.d.d_size = size;
++ scn->data_list.data.d.d_type = type;
++ scn->data_list.data.d.d_off = scn->rawdata.d.d_off;
++ scn->data_list.data.d.d_align = scn->rawdata.d.d_align;
++ scn->data_list.data.d.d_version = scn->rawdata.d.d_version;
++
++ scn->data_list.data.s = scn;
++
++ /* In mips64 little-endian, r_info consists of four byte fields(contains
++ three reloc types) and a 32-bit symbol index. In order to adapt
++ GELF_R_SYM and GELF_R_TYPE, need to convert r_info to get correct symbol
++ index and type. */
++ /* references:
++ https://www.linux-mips.org/pub/linux/mips/doc/ABI/elf64-2.4.pdf
++ Page40 && Page41 */
++ GElf_Shdr shdr_mem;
++ GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
++ if (shdr->sh_type == SHT_REL)
++ {
++ size_t sh_entsize = gelf_fsize (scn->elf, ELF_T_REL, 1, EV_CURRENT);
++ int nentries = shdr->sh_size / sh_entsize;
++ for (int cnt = 0; cnt < nentries; ++cnt)
++ {
++ Elf_Data_Scn *data_scn = (Elf_Data_Scn *) &scn->data_list.data.d;
++ Elf64_Rel *value = &((Elf64_Rel *) data_scn->d.d_buf)[cnt];
++ Elf64_Xword info = value->r_info;
++ value->r_info = (((info & 0xffffffff) << 32)
++ | ((info >> 56) & 0xff)
++ | ((info >> 40) & 0xff00)
++ | ((info >> 24) & 0xff0000)
++ | ((info >> 8) & 0xff000000));
++ ((Elf64_Rel *) data_scn->d.d_buf)[cnt] = *value;
++ }
++ }
++ else if (shdr->sh_type == SHT_RELA)
++ {
++ size_t sh_entsize = gelf_fsize (scn->elf, ELF_T_RELA, 1, EV_CURRENT);
++ int nentries = shdr->sh_size / sh_entsize;
++ for (int cnt = 0; cnt < nentries; cnt++)
++ {
++ Elf_Data_Scn *data_scn = (Elf_Data_Scn *) &scn->data_list.data.d;
++ Elf64_Rela *value = &((Elf64_Rela *) data_scn->d.d_buf)[cnt];
++ Elf64_Xword info = value->r_info;
++ value->r_info = (((info & 0xffffffff) << 32)
++ | ((info >> 56) & 0xff)
++ | ((info >> 40) & 0xff00)
++ | ((info >> 24) & 0xff0000)
++ | ((info >> 8) & 0xff000000));
++ ((Elf64_Rela *) data_scn->d.d_buf)[cnt] = *value;
++ }
++ }
++}
++
++/* Convert the data in the current section. */
++static void
+ convert_data (Elf_Scn *scn, int eclass,
+ int data, size_t size, Elf_Type type)
+ {
+@@ -451,8 +564,23 @@ __libelf_set_data_list_rdlock (Elf_Scn *
+ return;
+ }
+
+- /* Convert according to the version and the type. */
+- convert_data (scn, elf->class,
++ GElf_Shdr shdr_mem;
++ GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
++ GElf_Ehdr ehdr_mem;
++ GElf_Ehdr *ehdr = gelf_getehdr (scn->elf, &ehdr_mem);
++ if (shdr != NULL && (shdr->sh_type == SHT_RELA || shdr->sh_type == SHT_REL) &&
++ scn->elf->class == ELFCLASS64 && ehdr != NULL &&
++ ehdr->e_machine == EM_MIPS && ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
++ convert_data_for_mips64el (scn, elf->class,
++ (elf->class == ELFCLASS32
++ || (offsetof (struct Elf, state.elf32.ehdr)
++ == offsetof (struct Elf, state.elf64.ehdr))
++ ? elf->state.elf32.ehdr->e_ident[EI_DATA]
++ : elf->state.elf64.ehdr->e_ident[EI_DATA]),
++ scn->rawdata.d.d_size, scn->rawdata.d.d_type);
++ else
++ /* Convert according to the version and the type. */
++ convert_data (scn, elf->class,
+ (elf->class == ELFCLASS32
+ || (offsetof (struct Elf, state.elf32.ehdr)
+ == offsetof (struct Elf, state.elf64.ehdr))
+--- a/libelf/elf_update.c
++++ b/libelf/elf_update.c
+@@ -228,7 +228,60 @@ elf_update (Elf *elf, Elf_Cmd cmd)
+ size = -1;
+ }
+ else
++ {
++ /* Because we converted the relocation info in mips order when we call elf_getdata.c,
++ so we need to convert the modified data in original order bits before writing the
++ data to the file. */
++ Elf_Scn *scn = NULL;
++ while ((scn = elf_nextscn (elf, scn)) != NULL)
++ {
++ GElf_Shdr shdr_mem;
++ GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
++ GElf_Ehdr ehdr_mem;
++ GElf_Ehdr *ehdr = gelf_getehdr (scn->elf, &ehdr_mem);
++ if (shdr != NULL && (shdr->sh_type == SHT_RELA || shdr->sh_type == SHT_REL) &&
++ scn->elf->class == ELFCLASS64 &&
++ ehdr != NULL && ehdr->e_machine == EM_MIPS && ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
++ {
++ Elf_Data *d = elf_getdata (scn, NULL);
++ if (shdr->sh_type == SHT_REL)
++ {
++ size_t sh_entsize = gelf_fsize (scn->elf, ELF_T_REL, 1, EV_CURRENT);
++ int nentries = shdr->sh_size / sh_entsize;
++ for (int cnt = 0; cnt < nentries; ++cnt)
++ {
++ Elf_Data_Scn *data_scn = (Elf_Data_Scn *) d;
++ Elf64_Rel *value = &((Elf64_Rel *) data_scn->d.d_buf)[cnt];
++ Elf64_Xword info = value->r_info;
++ value->r_info = (info >> 32
++ | ((info << 56) & 0xff00000000000000)
++ | ((info << 40) & 0xff000000000000)
++ | ((info << 24) & 0xff0000000000)
++ | ((info << 8) & 0xff00000000));
++ ((Elf64_Rel *) data_scn->d.d_buf)[cnt] = *value;
++ }
++ }
++ else if (shdr->sh_type == SHT_RELA)
++ {
++ size_t sh_entsize = gelf_fsize (scn->elf, ELF_T_RELA, 1, EV_CURRENT);
++ int nentries = shdr->sh_size / sh_entsize;
++ for (int cnt = 0; cnt < nentries; cnt++)
++ {
++ Elf_Data_Scn *data_scn = (Elf_Data_Scn *) d;
++ Elf64_Rela *value = &((Elf64_Rela *) data_scn->d.d_buf)[cnt];
++ Elf64_Xword info = value->r_info;
++ value->r_info = (info >> 32
++ | ((info << 56) & 0xff00000000000000)
++ | ((info << 40) & 0xff000000000000)
++ | ((info << 24) & 0xff0000000000)
++ | ((info << 8) & 0xff00000000));
++ ((Elf64_Rela *) data_scn->d.d_buf)[cnt] = *value;
++ }
++ }
++ }
++ }
+ size = write_file (elf, size, change_bo, shnum);
++ }
+ }
+
+ out:
+--- /dev/null
++++ b/backends/mips_attrs.c
+@@ -0,0 +1,140 @@
++/* Object attribute tags for MIPS.
++ Copyright (C) 2024 CIP United Inc.
++ This file is part of elfutils.
++
++ This file is free software; you can redistribute it and/or modify
++ it under the terms of either
++
++ * the GNU Lesser General Public License as published by the Free
++ Software Foundation; either version 3 of the License, or (at
++ your option) any later version
++
++ or
++
++ * the GNU General Public License as published by the Free
++ Software Foundation; either version 2 of the License, or (at
++ your option) any later version
++
++ or both in parallel, as here.
++
++ elfutils 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 copies of the GNU General Public License and
++ the GNU Lesser General Public License along with this program. If
++ not, see <http://www.gnu.org/licenses/>. */
++
++#ifdef HAVE_CONFIG_H
++# include <config.h>
++#endif
++
++#include <string.h>
++#include <dwarf.h>
++
++#define BACKEND mips_
++#include "libebl_CPU.h"
++
++#define KNOWN_VALUES(...) do \
++ { \
++ static const char *table[] = { __VA_ARGS__ }; \
++ if (value < sizeof table / sizeof table[0]) \
++ *value_name = table[value]; \
++ } while (0)
++
++//copy gnu attr tags from binutils-2.34/elfcpp/mips.h
++/* Object attribute tags. */
++enum
++{
++ /* 0-3 are generic. */
++
++ /* Floating-point ABI used by this object file. */
++ Tag_GNU_MIPS_ABI_FP = 4,
++
++ /* MSA ABI used by this object file. */
++ Tag_GNU_MIPS_ABI_MSA = 8,
++};
++
++/* Object attribute values. */
++enum
++{
++ /* Values defined for Tag_GNU_MIPS_ABI_MSA. */
++
++ /* Not tagged or not using any ABIs affected by the differences. */
++ Val_GNU_MIPS_ABI_MSA_ANY = 0,
++
++ /* Using 128-bit MSA. */
++ Val_GNU_MIPS_ABI_MSA_128 = 1,
++};
++
++/* Object attribute values. */
++enum
++{
++ /* This is reserved for backward-compatibility with an earlier
++ implementation of the MIPS NaN2008 functionality. */
++ Val_GNU_MIPS_ABI_FP_NAN2008 = 8,
++};
++
++/* copy binutils-2.34/binutils/readelf.c display_mips_gnu_attribute */
++bool
++mips_check_object_attribute (Ebl *ebl __attribute__ ((unused)),
++ const char *vendor, int tag, uint64_t value,
++ const char **tag_name, const char **value_name)
++{
++ if (!strcmp (vendor, "gnu"))
++ switch (tag)
++ {
++ case Tag_GNU_MIPS_ABI_FP:
++ *tag_name = "Tag_GNU_MIPS_ABI_FP";
++ switch (value)
++ {
++ case Val_GNU_MIPS_ABI_FP_ANY:
++ *value_name = "Hard or soft float";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_DOUBLE:
++ *value_name = "Hard float (double precision)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_SINGLE:
++ *value_name = "Hard float (single precision)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_SOFT:
++ *value_name = "Soft float";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_OLD_64:
++ *value_name = "Hard float (MIPS32r2 64-bit FPU 12 callee-saved)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_XX:
++ *value_name = "Hard float (32-bit CPU, Any FPU)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_64:
++ *value_name = "Hard float (32-bit CPU, 64-bit FPU)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_64A:
++ *value_name = "Hard float compat (32-bit CPU, 64-bit FPU)";
++ return true;
++ case Val_GNU_MIPS_ABI_FP_NAN2008:
++ *value_name = "NaN 2008 compatibility";
++ return true;
++ default:
++ return true;
++ }
++ return true;
++ case Tag_GNU_MIPS_ABI_MSA:
++ *tag_name = "Tag_GNU_MIPS_ABI_MSA";
++ switch (value)
++ {
++ case Val_GNU_MIPS_ABI_MSA_ANY:
++ *value_name = "Any MSA or not";
++ return true;
++ case Val_GNU_MIPS_ABI_MSA_128:
++ *value_name = "128-bit MSA";
++ return true;
++ default:
++ return true;
++ }
++ return true;
++ }
++
++ return false;
++}
+--- a/src/readelf.c
++++ b/src/readelf.c
+@@ -2219,17 +2219,41 @@ handle_relocs_rel (Ebl *ebl, GElf_Ehdr *
+ (long int) GELF_R_SYM (rel->r_info));
+ }
+ else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
+- printf (" %#0*" PRIx64 " %-20s %#0*" PRIx64 " %s\n",
+- class == ELFCLASS32 ? 10 : 18, rel->r_offset,
+- likely (ebl_reloc_type_check (ebl,
+- GELF_R_TYPE (rel->r_info)))
+- /* Avoid the leading R_ which isn't carrying any
+- information. */
+- ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
+- buf, sizeof (buf)) + 2
+- : _("<INVALID RELOC>"),
+- class == ELFCLASS32 ? 10 : 18, sym->st_value,
+- elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
++ {
++ unsigned long inf = rel->r_info;
++ printf (" %#0*" PRIx64 " %-20s %#0*" PRIx64 " %s\n",
++ class == ELFCLASS32 ? 10 : 18, rel->r_offset,
++ likely (ebl_reloc_type_check (ebl,
++ GELF_R_TYPE (rel->r_info)))
++ /* Avoid the leading R_ which isn't carrying any
++ information. */
++ ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
++ buf, sizeof (buf)) + 2
++ : _("<INVALID RELOC>"),
++ class == ELFCLASS32 ? 10 : 18, sym->st_value,
++ elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
++
++ /* copy binutils-2.34/binutils/readelf.c dump_relocations+1753 */
++ if(ebl->elf->class == ELFCLASS64 && ebl->elf->state.elf64.ehdr->e_machine == EM_MIPS)
++ {
++ unsigned int type2 = ELF64_MIPS_R_TYPE2 (inf);
++ unsigned int type3 = ELF64_MIPS_R_TYPE3 (inf);
++ const char * rtype2 = ebl_reloc_type_name (ebl, type2, buf, sizeof (buf)) + 2;
++ const char * rtype3 = ebl_reloc_type_name (ebl, type3, buf, sizeof (buf)) + 2;
++ printf(" Type2: ");
++ if (rtype2 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type2 & 0xffffffff);
++ else
++ printf ("%s", rtype2);
++
++ printf ("\n Type3: ");
++ if (rtype3 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type3 & 0xffffffff);
++ else
++ printf ("%s", rtype3);
++ printf("\n");
++ }
++ }
+ else
+ {
+ /* This is a relocation against a STT_SECTION symbol. */
+@@ -2253,16 +2277,40 @@ handle_relocs_rel (Ebl *ebl, GElf_Ehdr *
+ (long int) (sym->st_shndx == SHN_XINDEX
+ ? xndx : sym->st_shndx));
+ else
+- printf (" %#0*" PRIx64 " %-20s %#0*" PRIx64 " %s\n",
+- class == ELFCLASS32 ? 10 : 18, rel->r_offset,
+- ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
+- /* Avoid the leading R_ which isn't carrying any
+- information. */
+- ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
+- buf, sizeof (buf)) + 2
+- : _("<INVALID RELOC>"),
+- class == ELFCLASS32 ? 10 : 18, sym->st_value,
+- elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
++ {
++ unsigned long inf = rel->r_info;
++ printf (" %#0*" PRIx64 " %-20s %#0*" PRIx64 " %s\n",
++ class == ELFCLASS32 ? 10 : 18, rel->r_offset,
++ ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
++ /* Avoid the leading R_ which isn't carrying any
++ information. */
++ ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
++ buf, sizeof (buf)) + 2
++ : _("<INVALID RELOC>"),
++ class == ELFCLASS32 ? 10 : 18, sym->st_value,
++ elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
++
++ /* copy binutils-2.34/binutils/readelf.c dump_relocations+1753 */
++ if(ebl->elf->class == ELFCLASS64 && ebl->elf->state.elf64.ehdr->e_machine == EM_MIPS)
++ {
++ unsigned int type2 = ELF64_MIPS_R_TYPE2 (inf);
++ unsigned int type3 = ELF64_MIPS_R_TYPE3 (inf);
++ const char * rtype2 = ebl_reloc_type_name (ebl, type2, buf, sizeof (buf)) + 2;
++ const char * rtype3 = ebl_reloc_type_name (ebl, type3, buf, sizeof (buf)) + 2;
++ printf(" Type2: ");
++ if (rtype2 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type2 & 0xffffffff);
++ else
++ printf ("%s", rtype2);
++
++ printf ("\n Type3: ");
++ if (rtype3 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type3 & 0xffffffff);
++ else
++ printf ("%s", rtype3);
++ printf("\n");
++ }
++ }
+ }
+ }
+ }
+@@ -2410,19 +2458,43 @@ handle_relocs_rela (Ebl *ebl, GElf_Ehdr
+ (long int) GELF_R_SYM (rel->r_info));
+ }
+ else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
+- printf ("\
++ {
++ unsigned long inf = rel->r_info;
++ printf ("\
+ %#0*" PRIx64 " %-15s %#0*" PRIx64 " %+6" PRId64 " %s\n",
+- class == ELFCLASS32 ? 10 : 18, rel->r_offset,
+- likely (ebl_reloc_type_check (ebl,
+- GELF_R_TYPE (rel->r_info)))
+- /* Avoid the leading R_ which isn't carrying any
+- information. */
+- ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
+- buf, sizeof (buf)) + 2
+- : _("<INVALID RELOC>"),
+- class == ELFCLASS32 ? 10 : 18, sym->st_value,
+- rel->r_addend,
+- elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
++ class == ELFCLASS32 ? 10 : 18, rel->r_offset,
++ likely (ebl_reloc_type_check (ebl,
++ GELF_R_TYPE (rel->r_info)))
++ /* Avoid the leading R_ which isn't carrying any
++ information. */
++ ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
++ buf, sizeof (buf)) + 2
++ : _("<INVALID RELOC>"),
++ class == ELFCLASS32 ? 10 : 18, sym->st_value,
++ rel->r_addend,
++ elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
++
++ /* copy binutils-2.34/binutils/readelf.c dump_relocations+1753 */
++ if(ebl->elf->class == ELFCLASS64 && ebl->elf->state.elf64.ehdr->e_machine == EM_MIPS)
++ {
++ unsigned int type2 = ELF64_MIPS_R_TYPE2 (inf);
++ unsigned int type3 = ELF64_MIPS_R_TYPE3 (inf);
++ const char * rtype2 = ebl_reloc_type_name (ebl, type2, buf, sizeof (buf)) + 2;
++ const char * rtype3 = ebl_reloc_type_name (ebl, type3, buf, sizeof (buf)) + 2;
++ printf(" Type2: ");
++ if (rtype2 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type2 & 0xffffffff);
++ else
++ printf ("%s", rtype2);
++
++ printf ("\n Type3: ");
++ if (rtype3 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type3 & 0xffffffff);
++ else
++ printf ("%s", rtype3);
++ printf("\n");
++ }
++ }
+ else
+ {
+ /* This is a relocation against a STT_SECTION symbol. */
+@@ -2446,18 +2518,42 @@ handle_relocs_rela (Ebl *ebl, GElf_Ehdr
+ (long int) (sym->st_shndx == SHN_XINDEX
+ ? xndx : sym->st_shndx));
+ else
+- printf ("\
++ {
++ unsigned long inf = rel->r_info;
++ printf ("\
+ %#0*" PRIx64 " %-15s %#0*" PRIx64 " %+6" PRId64 " %s\n",
+- class == ELFCLASS32 ? 10 : 18, rel->r_offset,
+- ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
+- /* Avoid the leading R_ which isn't carrying any
+- information. */
+- ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
+- buf, sizeof (buf)) + 2
+- : _("<INVALID RELOC>"),
+- class == ELFCLASS32 ? 10 : 18, sym->st_value,
+- rel->r_addend,
+- elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
++ class == ELFCLASS32 ? 10 : 18, rel->r_offset,
++ ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
++ /* Avoid the leading R_ which isn't carrying any
++ information. */
++ ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
++ buf, sizeof (buf)) + 2
++ : _("<INVALID RELOC>"),
++ class == ELFCLASS32 ? 10 : 18, sym->st_value,
++ rel->r_addend,
++ elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
++
++ /* copy binutils-2.34/binutils/readelf.c dump_relocations+1753 */
++ if(ebl->elf->class == ELFCLASS64 && ebl->elf->state.elf64.ehdr->e_machine == EM_MIPS)
++ {
++ unsigned int type2 = ELF64_MIPS_R_TYPE2 (inf);
++ unsigned int type3 = ELF64_MIPS_R_TYPE3 (inf);
++ const char * rtype2 = ebl_reloc_type_name (ebl, type2, buf, sizeof (buf)) + 2;
++ const char * rtype3 = ebl_reloc_type_name (ebl, type3, buf, sizeof (buf)) + 2;
++ printf(" Type2: ");
++ if (rtype2 == NULL)
++ printf (_("unrecognized: %-7lx"), (unsigned long) type2 & 0xffffffff);
++ else
++ printf ("%s", rtype2);
++
++ printf ("\n Type3: ");
++ if (rtype3 == NULL)
++ printf (_("unrecognized: %lx"), (unsigned long) type3 & 0xffffffff);
++ else
++ printf ("%s", rtype3);
++ printf("\n");
++ }
++ }
+ }
+ }
+ }
+@@ -12043,7 +12139,7 @@ print_debug (Dwfl_Module *dwflmod, Ebl *
+ GElf_Shdr shdr_mem;
+ GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
+
+- if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
++ if (shdr != NULL && is_debug_section_type(shdr->sh_type))
+ {
+ const char *name = elf_strptr (ebl->elf, shstrndx,
+ shdr->sh_name);
+@@ -12073,7 +12169,7 @@ print_debug (Dwfl_Module *dwflmod, Ebl *
+ GElf_Shdr shdr_mem;
+ GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
+
+- if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
++ if (shdr != NULL && is_debug_section_type(shdr->sh_type))
+ {
+ static const struct
+ {
+--- a/tests/Makefile.am
++++ b/tests/Makefile.am
+@@ -214,7 +214,7 @@ TESTS = run-arextract.sh run-arsymtest.s
+ run-nvidia-extended-linemap-libdw.sh run-nvidia-extended-linemap-readelf.sh \
+ run-readelf-dw-form-indirect.sh run-strip-largealign.sh \
+ run-readelf-Dd.sh run-dwfl-core-noncontig.sh run-cu-dwp-section-info.sh \
+- run-declfiles.sh
++ run-declfiles.sh run-readelf-reloc.sh
+
+ if !BIARCH
+ export ELFUTILS_DISABLE_BIARCH = 1
+@@ -646,7 +646,8 @@ EXTRA_DIST = run-arextract.sh run-arsymt
+ testfile-dwp-5-cu-index-overflow.dwp.bz2 \
+ testfile-dwp-4-cu-index-overflow.bz2 \
+ testfile-dwp-4-cu-index-overflow.dwp.bz2 \
+- testfile-dwp-cu-index-overflow.source
++ testfile-dwp-cu-index-overflow.source \
++ run-readelf-reloc.sh
+
+
+ if USE_VALGRIND
+--- /dev/null
++++ b/tests/run-readelf-reloc.sh
+@@ -0,0 +1,42 @@
++#! /bin/bash
++# Copyright (C) 2024 CIP United Inc.
++# This file is part of elfutils.
++#
++# This file 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.
++#
++# elfutils 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/>.
++
++. $srcdir/test-subr.sh
++
++tempfiles test-readelf-h.txt test-readelf-reloc.txt
++testrun ${abs_top_builddir}/src/readelf -h ${abs_top_builddir}/src/strip.o > test-readelf-h.txt
++machine=`cat test-readelf-h.txt | grep Machine`
++class=`cat test-readelf-h.txt | grep Class`
++endian=`cat test-readelf-h.txt | grep Data`
++if [[ "$machine" == *MIPS* && "$class" == *ELF64 && "$endian" == *little* ]]; then
++testrun ${abs_top_builddir}/src/readelf -r ${abs_top_builddir}/src/strip.o | head -n 12 | tail -n 10 > test-readelf-reloc.txt
++
++testrun_compare cat test-readelf-reloc.txt << EOF
++ Offset Type Value Addend Name
++ 0x0000000000000008 MIPS_GPREL16 000000000000000000 +0 .text
++ Type2: MIPS_SUB
++ Type3: MIPS_HI16
++ 0x0000000000000010 MIPS_GPREL16 000000000000000000 +0 .text
++ Type2: MIPS_SUB
++ Type3: MIPS_LO16
++ 0x0000000000000014 MIPS_CALL16 000000000000000000 +0 gelf_getehdr
++ Type2: MIPS_NONE
++ Type3: MIPS_NONE
++EOF
++fi
++
++exit 0
+--- a/src/elflint.c
++++ b/src/elflint.c
+@@ -936,7 +936,9 @@ section [%2d] '%s': symbol %zu (%s): non
+ }
+
+ if (GELF_ST_TYPE (sym->st_info) == STT_SECTION
+- && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
++ && GELF_ST_BIND (sym->st_info) != STB_LOCAL
++ && ehdr->e_machine != EM_MIPS
++ && strcmp (name, "_DYNAMIC_LINKING") != 0)
+ ERROR (_("\
+ section [%2d] '%s': symbol %zu (%s): non-local section symbol\n"),
+ idx, section_name (ebl, idx), cnt, name);
+@@ -3828,6 +3830,10 @@ cannot get section header for section [%
+ && ebl_bss_plt_p (ebl))
+ good_type = SHT_NOBITS;
+
++ if (ehdr->e_machine == EM_MIPS
++ && (strstr(special_sections[s].name, ".debug") != NULL))
++ good_type = SHT_MIPS_DWARF;
++
+ /* In a debuginfo file, any normal section can be SHT_NOBITS.
+ This is only invalid for DWARF sections and .shstrtab. */
+ if (shdr->sh_type != good_type
+@@ -3988,12 +3994,21 @@ section [%2zu] '%s': size not multiple o
+ ERROR (_("section [%2zu] '%s'"
+ " contains invalid processor-specific flag(s)"
+ " %#" PRIx64 "\n"),
+- cnt, section_name (ebl, cnt), sh_flags & SHF_MASKPROC);
++ cnt, section_name (ebl, cnt), sh_flags & SHF_MASKPROC);
+ sh_flags &= ~(GElf_Xword) SHF_MASKPROC;
+ }
+ if (sh_flags & SHF_MASKOS)
+- if (gnuld)
+- sh_flags &= ~(GElf_Xword) SHF_GNU_RETAIN;
++ {
++ if (gnuld)
++ sh_flags &= ~(GElf_Xword) SHF_GNU_RETAIN;
++ if (!ebl_machine_section_flag_check (ebl,
++ sh_flags & SHF_MASKOS))
++ ERROR (_("section [%2zu] '%s'"
++ " contains invalid os-specific flag(s)"
++ " %#" PRIx64 "\n"),
++ cnt, section_name (ebl, cnt), sh_flags & SHF_MASKOS);
++ sh_flags &= ~(GElf_Xword) SHF_MASKOS;
++ }
+ if (sh_flags != 0)
+ ERROR (_("section [%2zu] '%s' contains unknown flag(s)"
+ " %#" PRIx64 "\n"),
+@@ -4059,6 +4074,7 @@ section [%2zu] '%s': merge flag set but
+ switch (shdr->sh_type)
+ {
+ case SHT_PROGBITS:
++ case SHT_MIPS_DWARF:
+ break;
+
+ case SHT_NOBITS:
+@@ -4716,7 +4732,7 @@ program header offset in ELF header and
+ if (shdr != NULL
+ && ((is_debuginfo && shdr->sh_type == SHT_NOBITS)
+ || (! is_debuginfo
+- && (shdr->sh_type == SHT_PROGBITS
++ && (is_debug_section_type(shdr->sh_type)
+ || shdr->sh_type == SHT_X86_64_UNWIND)))
+ && elf_strptr (ebl->elf, shstrndx, shdr->sh_name) != NULL
+ && ! strcmp (".eh_frame_hdr",
+--- /dev/null
++++ b/backends/mips64_corenote.c
+@@ -0,0 +1,2 @@
++#define BITS 64
++#include "mips_corenote.c"
+--- a/libebl/eblcorenotetypename.c
++++ b/libebl/eblcorenotetypename.c
+@@ -94,6 +94,8 @@ ebl_core_note_type_name (Ebl *ebl, uint3
+ KNOWNSTYPE (ARM_SYSTEM_CALL);
+ KNOWNSTYPE (SIGINFO);
+ KNOWNSTYPE (FILE);
++ KNOWNSTYPE (MIPS_FP_MODE);
++ KNOWNSTYPE (MIPS_MSA);
+ #undef KNOWNSTYPE
+
+ default:
+--- a/tests/run-allregs.sh
++++ b/tests/run-allregs.sh
+@@ -2904,4 +2904,83 @@ FPU registers:
+ 62: ft10 (ft10), float 64 bits
+ 63: ft11 (ft11), float 64 bits
+ EOF
++
++# See run-readelf-mixed-corenote.sh for instructions to regenerate
++# this core file.
++regs_test testfile-mips64-core <<\EOF
++integer registers:
++ 0: $0 (0), signed 32 bits
++ 1: $1 (1), signed 32 bits
++ 2: $2 (2), signed 32 bits
++ 3: $3 (3), signed 32 bits
++ 4: $4 (4), signed 32 bits
++ 5: $5 (5), signed 32 bits
++ 6: $6 (6), signed 32 bits
++ 7: $7 (7), signed 32 bits
++ 8: $8 (8), signed 32 bits
++ 9: $9 (9), signed 32 bits
++ 10: $10 (10), signed 32 bits
++ 11: $11 (11), signed 32 bits
++ 12: $12 (12), signed 32 bits
++ 13: $13 (13), signed 32 bits
++ 14: $14 (14), signed 32 bits
++ 15: $15 (15), signed 32 bits
++ 16: $16 (16), signed 32 bits
++ 17: $17 (17), signed 32 bits
++ 18: $18 (18), signed 32 bits
++ 19: $19 (19), signed 32 bits
++ 20: $20 (20), signed 32 bits
++ 21: $21 (21), signed 32 bits
++ 22: $22 (22), signed 32 bits
++ 23: $23 (23), signed 32 bits
++ 24: $24 (24), signed 32 bits
++ 25: $25 (25), signed 32 bits
++ 26: $26 (26), signed 32 bits
++ 27: $27 (27), signed 32 bits
++ 28: $28 (28), address 32 bits
++ 29: $29 (29), address 32 bits
++ 30: $30 (30), signed 32 bits
++ 31: $31 (31), address 32 bits
++ 32: $lo (lo), signed 32 bits
++ 33: $hi (hi), signed 32 bits
++ 34: $pc (pc), signed 32 bits
++ 35: $bad (bad), address 32 bits
++ 36: $sr (sr), signed 32 bits
++ 37: $cause (cause), address 32 bits
++FPU registers:
++ 38: $f0 (f0), float 64 bits
++ 39: $f1 (f1), float 64 bits
++ 40: $f2 (f2), float 64 bits
++ 41: $f3 (f3), float 64 bits
++ 42: $f4 (f4), float 64 bits
++ 43: $f5 (f5), float 64 bits
++ 44: $f6 (f6), float 64 bits
++ 45: $f7 (f7), float 64 bits
++ 46: $f8 (f8), float 64 bits
++ 47: $f9 (f9), float 64 bits
++ 48: $f10 (f10), float 64 bits
++ 49: $f11 (f11), float 64 bits
++ 50: $f12 (f12), float 64 bits
++ 51: $f13 (f13), float 64 bits
++ 52: $f14 (f14), float 64 bits
++ 53: $f15 (f15), float 64 bits
++ 54: $f16 (f16), float 64 bits
++ 55: $f17 (f17), float 64 bits
++ 56: $f18 (f18), float 64 bits
++ 57: $f19 (f19), float 64 bits
++ 58: $f20 (f20), float 64 bits
++ 59: $f21 (f21), float 64 bits
++ 60: $f22 (f22), float 64 bits
++ 61: $f23 (f23), float 64 bits
++ 62: $f24 (f24), float 64 bits
++ 63: $f25 (f25), float 64 bits
++ 64: $f26 (f26), float 64 bits
++ 65: $f27 (f27), float 64 bits
++ 66: $f28 (f28), float 64 bits
++ 67: $f29 (f29), float 64 bits
++ 68: $f30 (f30), float 64 bits
++ 69: $f31 (f31), float 64 bits
++ 70: $fsr (fsr), float 64 bits
++ 71: $fir (fir), float 64 bits
++EOF
+ exit 0
+--- a/tests/run-readelf-mixed-corenote.sh
++++ b/tests/run-readelf-mixed-corenote.sh
+@@ -716,4 +716,101 @@ Note segment of 1408 bytes at offset 0x3
+ 2000155000-2000157000 00122000 8192 /lib64/libc-2.27.so
+ EOF
+
++# To reproduce this core dump, do this on a mips machine:
++# $ gcc -x c <(echo 'int main () { return *(int *)0x12345678; }')
++# $ ./a.out
++testfiles testfile-mips64-core
++testrun_compare ${abs_top_builddir}/src/readelf -n testfile-mips64-core <<\EOF
++
++Note segment of 2572 bytes at offset 0x3c0:
++ Owner Data size Type
++ CORE 480 PRSTATUS
++ info.si_signo: 11, info.si_code: 0, info.si_errno: 0, cursig: 11
++ sigpend: <>
++ sighold: <>
++ pid: 1660204, ppid: 1457483, pgrp: 1660204, sid: 1457483
++ utime: 0.000000, stime: 0.012000, cutime: 0.000000, cstime: 0.000000
++ pc: 0x000000aaacce0a64, fpvalid: 1
++ bad: 0x12345678 sr: 0 cause: 0x0400ccf3
++ f0: 0x1000000800000000 f1: 0x0000000000000000 f2: 0x0000000000000000
++ f3: 0x0000000000000000 f4: 0x0000000000000000 f5: 0x0000000000000000
++ f6: 0x0000000000000000
++ 0: 0 1: 0 2: 1
++ 3: 0 4: 305419896 5: 0
++ 6: -73593800 7: 255 8: 1
++ 9: 0 10: -73593464 11: 255
++ 12: -73593448 13: 255 14: 0
++ 15: 0 16: -244869184 17: 255
++ 18: -244886336 19: 255 20: -73593472
++ 21: 255 22: -1 23: -1
++ 24: 3 25: 0 26: 3167716
++ 27: 0 28: 0x00000024 29: 0x00000000
++ 30: 49495 31: 0x00000000 lo: -73593464
++ hi: 255 bad: 0x12345678 sr: 0
++ cause: 0x0400ccf3 f0: 0x1000000800000000
++ f1: 0x0000000000000000 f2: 0x0000000000000000
++ f3: 0x0000000000000000 f4: 0x0000000000000000
++ f5: 0x0000000000000000 f6: 0x0000000000000000
++ CORE 136 PRPSINFO
++ state: 0, sname: R, zomb: 0, nice: 0, flag: 0x0000000000402600
++ uid: 1014, gid: 100, pid: 1660204, ppid: 1457483, pgrp: 1660204
++ sid: 1457483
++ fname: a.out, psargs: ./a.out
++ CORE 128 SIGINFO
++ si_signo: 11, si_errno: 1, si_code: 0
++ sender PID: 305419896, sender UID: 0
++ CORE 320 AUXV
++ SYSINFO_EHDR: 0xffff14c000
++ HWCAP: 0x7806
++ PAGESZ: 16384
++ CLKTCK: 100
++ PHDR: 0xaaacce0040
++ PHENT: 56
++ PHNUM: 9
++ BASE: 0xfff1694000
++ FLAGS: 0
++ ENTRY: 0xaaacce08d0
++ UID: 1014
++ EUID: 1014
++ GID: 100
++ EGID: 100
++ SECURE: 0
++ RANDOM: 0xfffb9d0f9c
++ EXECFN: 0xfffb9d3ff0
++ PLATFORM: 0xfffb9d0fb5
++ BASE_PLATFORM: 0xfffb9d0fac
++ NULL
++ CORE 549 FILE
++ 9 files:
++ aaacce0000-aaacce4000 00000000 16384 /tmp/a.out
++ aaaccf0000-aaaccf4000 00000000 16384 /tmp/a.out
++ fff1470000-fff165c000 00000000 2015232 /usr/lib/mips64el-linux-gnuabi64/libc.so.6
++ fff165c000-fff1668000 001ec000 49152 /usr/lib/mips64el-linux-gnuabi64/libc.so.6
++ fff1668000-fff1670000 001e8000 32768 /usr/lib/mips64el-linux-gnuabi64/libc.so.6
++ fff1670000-fff1678000 001f0000 32768 /usr/lib/mips64el-linux-gnuabi64/libc.so.6
++ fff1694000-fff16c4000 00000000 196608 /usr/lib/mips64el-linux-gnuabi64/ld.so.1
++ fff16d0000-fff16d4000 0002c000 16384 /usr/lib/mips64el-linux-gnuabi64/ld.so.1
++ fff16d4000-fff16d8000 00030000 16384 /usr/lib/mips64el-linux-gnuabi64/ld.so.1
++ CORE 264 FPREGSET
++ fcs: 0x000c0000, fir: 0x00f70501
++ f0: 0xffffffffffffffff f1: 0xffffffffffffffff
++ f2: 0xffffffffffffffff f3: 0xffffffffffffffff
++ f4: 0xffffffffffffffff f5: 0xffffffffffffffff
++ f6: 0xffffffffffffffff f7: 0xffffffffffffffff
++ f8: 0xffffffffffffffff f9: 0xffffffffffffffff
++ f10: 0xffffffffffffffff f11: 0xffffffffffffffff
++ f12: 0xffffffffffffffff f13: 0xffffffffffffffff
++ f14: 0xffffffffffffffff f15: 0xffffffffffffffff
++ f16: 0xffffffffffffffff f17: 0xffffffffffffffff
++ f18: 0xffffffffffffffff f19: 0xffffffffffffffff
++ f20: 0xffffffffffffffff f21: 0xffffffffffffffff
++ f22: 0xffffffffffffffff f23: 0xffffffffffffffff
++ f24: 0xffffffffffffffff f25: 0xffffffffffffffff
++ f26: 0xffffffffffffffff f27: 0xffffffffffffffff
++ f28: 0xffffffffffffffff f29: 0xffffffffffffffff
++ f30: 0xffffffffffffffff f31: 0xffffffffffffffff
++ LINUX 4 MIPS_FP_MODE
++ LINUX 528 MIPS_MSA
++EOF
++
+ exit 0
diff --git a/tools/elfutils/patches/100-portability.patch b/tools/elfutils/patches/100-portability.patch
new file mode 100644
index 0000000..2cc8a4c
--- /dev/null
+++ b/tools/elfutils/patches/100-portability.patch
@@ -0,0 +1,300 @@
+--- a/configure.ac
++++ b/configure.ac
+@@ -44,6 +44,7 @@ fi
+
+ AC_CONFIG_AUX_DIR([config])
+ AC_CONFIG_FILES([config/Makefile])
++AC_CONFIG_FILES([libgnu/Makefile])
+
+ AC_COPYRIGHT([Copyright (C) 1996-2024 The elfutils developers.])
+ AC_PREREQ(2.63) dnl Minimum Autoconf version required.
+@@ -88,11 +89,14 @@ AS_IF([test "$use_locks" = yes],
+
+ AH_TEMPLATE([USE_LOCKS], [Defined if libraries should be thread-safe.])
+
++AC_USE_SYSTEM_EXTENSIONS()
++
+ m4_version_prereq([2.70], [AC_PROG_CC], [AC_PROG_CC_C99])
+ AC_PROG_CXX
+ AC_PROG_RANLIB
+ AC_PROG_YACC
+ AC_PROG_LEX([noyywrap])
++gl_EARLY
+ # Only available since automake 1.12
+ m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
+ AC_CHECK_TOOL([READELF], [readelf])
+@@ -635,6 +639,8 @@ AC_COMPILE_IFELSE([AC_LANG_SOURCE([])],
+ CFLAGS="$old_CFLAGS"])
+ AS_IF([test "x$ac_cv_fno_addrsig" = "xyes"], CFLAGS="$CFLAGS -fno-addrsig")
+
++gl_INIT
++
+ saved_LIBS="$LIBS"
+ AC_SEARCH_LIBS([argp_parse], [argp])
+ LIBS="$saved_LIBS"
+--- a/lib/eu-config.h
++++ b/lib/eu-config.h
+@@ -59,14 +59,19 @@
+ # define once(once_control, init_routine) init_routine()
+ #endif /* USE_LOCKS */
+
+-#include <libintl.h>
++#include <gettext.h>
+ /* gettext helper macros. */
+ #define N_(Str) Str
+ #define _(Str) dgettext ("elfutils", Str)
+
+ /* Compiler-specific definitions. */
++#define __PRAGMA(str) _Pragma (#str)
++#ifdef __APPLE__
++#define strong_alias(name, aliasname) __PRAGMA(weak aliasname = name)
++#else
+ #define strong_alias(name, aliasname) \
+ extern __typeof (name) aliasname __attribute__ ((alias (#name)));
++#endif
+
+ #ifdef __i386__
+ # define internal_function __attribute__ ((regparm (3), stdcall))
+@@ -77,7 +82,7 @@
+ #define internal_strong_alias(name, aliasname) \
+ extern __typeof (name) aliasname __attribute__ ((alias (#name))) internal_function;
+
+-#ifdef HAVE_VISIBILITY
++#if defined(HAVE_VISIBILITY) && !defined(__APPLE__)
+ #define attribute_hidden \
+ __attribute__ ((visibility ("hidden")))
+ #else
+@@ -166,7 +171,7 @@ asm (".section predict_data, \"aw\"; .pr
+ #endif
+
+ /* Avoid PLT entries. */
+-#ifdef PIC
++#if defined(PIC) && !defined(__APPLE__)
+ # define INTUSE(name) _INTUSE(name)
+ # define _INTUSE(name) __##name##_internal
+ # define INTDEF(name) _INTDEF(name)
+--- a/backends/i386_auxv.c
++++ b/backends/i386_auxv.c
+@@ -48,5 +48,4 @@ EBLHOOK(auxv_info) (GElf_Xword a_type, c
+ return 1;
+ }
+
+-__typeof (i386_auxv_info) x86_64_auxv_info
+- __attribute__ ((alias ("i386_auxv_info")));
++auxv_info_alias(x86_64)
+--- a/backends/ppc_regs.c
++++ b/backends/ppc_regs.c
+@@ -204,5 +204,11 @@ ppc_register_info (Ebl *ebl __attribute_
+ return namelen;
+ }
+
+-__typeof (ppc_register_info)
+- ppc64_register_info __attribute__ ((alias ("ppc_register_info")));
++ssize_t
++ppc64_register_info (Ebl *ebl,
++ int regno, char *name, size_t namelen,
++ const char **prefix, const char **setname,
++ int *bits, int *type)
++{
++ return ppc_register_info(ebl, regno, name, namelen, prefix, setname, bits, type);
++}
+--- a/backends/libebl_CPU.h
++++ b/backends/libebl_CPU.h
+@@ -97,4 +97,10 @@ dwarf_is_pointer (int tag)
+ case DW_TAG_reference_type: \
+ case DW_TAG_rvalue_reference_type
+
++#define auxv_info_alias(arch) \
++ int EBLHOOK_1(arch ## _, auxv_info) (GElf_Xword a_type, const char **name, const char **format) \
++ { \
++ return EBLHOOK(auxv_info)(a_type, name, format); \
++ }
++
+ #endif /* libebl_CPU.h */
+--- a/backends/ppc_auxv.c
++++ b/backends/ppc_auxv.c
+@@ -51,5 +51,4 @@ EBLHOOK(auxv_info) (GElf_Xword a_type, c
+ return 1;
+ }
+
+-__typeof (ppc_auxv_info) ppc64_auxv_info
+- __attribute__ ((alias ("ppc_auxv_info")));
++auxv_info_alias(ppc64)
+--- a/backends/ppc_cfi.c
++++ b/backends/ppc_cfi.c
+@@ -72,6 +72,7 @@ ppc_abi_cfi (Ebl *ebl __attribute__ ((un
+ return 0;
+ }
+
+-__typeof (ppc_abi_cfi)
+- ppc64_abi_cfi
+- __attribute__ ((alias ("ppc_abi_cfi")));
++int ppc64_abi_cfi(Ebl *ebl, Dwarf_CIE *abi_info)
++{
++ return ppc_abi_cfi(ebl, abi_info);
++}
+--- a/backends/ppc_initreg.c
++++ b/backends/ppc_initreg.c
+@@ -68,9 +68,10 @@ ppc_dwarf_to_regno (Ebl *ebl __attribute
+ abort ();
+ }
+
+-__typeof (ppc_dwarf_to_regno)
+- ppc64_dwarf_to_regno
+- __attribute__ ((alias ("ppc_dwarf_to_regno")));
++bool ppc64_dwarf_to_regno (Ebl *ebl, unsigned *regno)
++{
++ return ppc_dwarf_to_regno(ebl, regno);
++}
+
+ bool
+ ppc_set_initial_registers_tid (pid_t tid __attribute__ ((unused)),
+@@ -127,6 +128,7 @@ ppc_set_initial_registers_tid (pid_t tid
+ #endif /* __powerpc__ */
+ }
+
+-__typeof (ppc_set_initial_registers_tid)
+- ppc64_set_initial_registers_tid
+- __attribute__ ((alias ("ppc_set_initial_registers_tid")));
++bool ppc64_set_initial_registers_tid(pid_t tid, ebl_tid_registers_t *setfunc, void *arg)
++{
++ return ppc_set_initial_registers_tid(tid, setfunc, arg);
++}
+--- a/backends/ppc_attrs.c
++++ b/backends/ppc_attrs.c
+@@ -81,6 +81,9 @@ ppc_check_object_attribute (Ebl *ebl __a
+ return false;
+ }
+
+-__typeof (ppc_check_object_attribute)
+- ppc64_check_object_attribute
+- __attribute__ ((alias ("ppc_check_object_attribute")));
++bool ppc64_check_object_attribute(Ebl *ebl,
++ const char *vendor, int tag, uint64_t value,
++ const char **tag_name, const char **value_name)
++{
++ return ppc_check_object_attribute(ebl, vendor, tag, value, tag_name, value_name);
++}
+--- a/libdwfl/libdwflP.h
++++ b/libdwfl/libdwflP.h
+@@ -31,6 +31,7 @@
+
+ #include <libdwfl.h>
+ #include <libebl.h>
++#include <libeu.h>
+ #include <assert.h>
+ #include <dirent.h>
+ #include <errno.h>
+--- /dev/null
++++ b/lib/stdio_ext.h
+@@ -0,0 +1,6 @@
++#include <stdio.h>
++#ifndef __APPLE__
++#include_next <stdio_ext.h>
++#else
++#define __fsetlocking(...) 0
++#endif
+--- a/libdw/libdwP.h
++++ b/libdw/libdwP.h
+@@ -32,6 +32,7 @@
+ #include <stdbool.h>
+ #include <pthread.h>
+
++#include <libeu.h>
+ #include <libdw.h>
+ #include <dwarf.h>
+
+--- a/config/libdebuginfod.pc.in
++++ b/config/libdebuginfod.pc.in
+@@ -8,5 +8,5 @@ Description: elfutils library to query d
+ Version: @VERSION@
+ URL: http://elfutils.org/
+
+-Libs: -L${libdir} -ldebuginfod
++Libs: -L${libdir} -ldebuginfod -lpthread
+ Cflags: -I${includedir}
+--- a/config/libdw.pc.in
++++ b/config/libdw.pc.in
+@@ -8,7 +8,7 @@ Description: elfutils library for DWARF
+ Version: @VERSION@
+ URL: http://elfutils.org/
+
+-Libs: -L${libdir} -ldw
++Libs: -L${libdir} -ldw -lz -lelf -lz -ldl -lpthread
+ Cflags: -I${includedir}
+
+ # We need the exact matching elfutils libelf version since internal data
+--- a/config/libelf.pc.in
++++ b/config/libelf.pc.in
+@@ -8,7 +8,7 @@ Description: elfutils libelf library to
+ Version: @VERSION@
+ URL: http://elfutils.org/
+
+-Libs: -L${libdir} -lelf
++Libs: -L${libdir} -lelf -lz
+ Cflags: -I${includedir}
+
+ Requires.private: zlib @LIBZSTD@
+--- a/lib/next_prime.c
++++ b/lib/next_prime.c
+@@ -27,6 +27,7 @@
+ the GNU Lesser General Public License along with this program. If
+ not, see <http://www.gnu.org/licenses/>. */
+
++#include <config.h>
+ #include <stddef.h>
+
+
+--- a/libebl/eblopenbackend.c
++++ b/libebl/eblopenbackend.c
+@@ -200,8 +200,6 @@ static bool default_object_note (const c
+ uint32_t descsz, const char *desc);
+ static bool default_debugscn_p (const char *name);
+ static bool default_copy_reloc_p (int reloc);
+-static bool default_none_reloc_p (int reloc);
+-static bool default_relative_reloc_p (int reloc);
+ static bool default_check_special_symbol (Elf *elf,
+ const GElf_Sym *sym,
+ const char *name,
+@@ -253,8 +251,8 @@ fill_defaults (Ebl *result)
+ result->object_note = default_object_note;
+ result->debugscn_p = default_debugscn_p;
+ result->copy_reloc_p = default_copy_reloc_p;
+- result->none_reloc_p = default_none_reloc_p;
+- result->relative_reloc_p = default_relative_reloc_p;
++ result->none_reloc_p = default_copy_reloc_p;
++ result->relative_reloc_p = default_copy_reloc_p;
+ result->check_special_symbol = default_check_special_symbol;
+ result->data_marker_symbol = default_data_marker_symbol;
+ result->check_st_other_bits = default_check_st_other_bits;
+@@ -636,8 +634,6 @@ default_copy_reloc_p (int reloc __attrib
+ {
+ return false;
+ }
+-strong_alias (default_copy_reloc_p, default_none_reloc_p)
+-strong_alias (default_copy_reloc_p, default_relative_reloc_p)
+
+ static bool
+ default_check_special_symbol (Elf *elf __attribute__ ((unused)),
+--- a/src/srcfiles.cxx
++++ b/src/srcfiles.cxx
+@@ -78,7 +78,9 @@ ARGP_PROGRAM_VERSION_HOOK_DEF = print_ve
+ /* Bug report address. */
+ ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
+
++#ifdef HAVE_LIBARCHIVE
+ constexpr size_t BUFFER_SIZE = 8192;
++#endif
+
+ /* Definitions of arguments for argp functions. */
+ static const struct argp_option options[] =
+--- a/src/Makefile.am
++++ b/src/Makefile.am
+@@ -92,6 +92,7 @@ strings_LDADD = $(libelf) $(libeu) $(arg
+ ar_LDADD = libar.a $(libelf) $(libeu) $(argp_LDADD) $(obstack_LIBS)
+ unstrip_LDADD = $(libebl) $(libelf) $(libdw) $(libeu) $(argp_LDADD)
+ stack_LDADD = $(libebl) $(libelf) $(libdw) $(libeu) $(argp_LDADD) $(demanglelib)
++EXTRA_stack_DEPENDENCIES = $(if $(findstring srcfiles,$(bin_PROGRAMS)),$(srcfiles_OBJECTS))
+ elfcompress_LDADD = $(libebl) $(libelf) $(libdw) $(libeu) $(argp_LDADD)
+ elfclassify_LDADD = $(libelf) $(libdw) $(libeu) $(argp_LDADD)
+ srcfiles_SOURCES = srcfiles.cxx
diff --git a/tools/elfutils/patches/101-shared-conditional.patch b/tools/elfutils/patches/101-shared-conditional.patch
new file mode 100644
index 0000000..17d8cc7
--- /dev/null
+++ b/tools/elfutils/patches/101-shared-conditional.patch
@@ -0,0 +1,183 @@
+--- a/configure.ac
++++ b/configure.ac
+@@ -102,6 +102,8 @@ m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
+ AC_CHECK_TOOL([READELF], [readelf])
+ AC_CHECK_TOOL([NM], [nm])
+
++LT_INIT([shared disable-static])
++
+ AC_CACHE_CHECK([whether gcc supports __attribute__((visibility()))],
+ ac_cv_visibility, [dnl
+ save_CFLAGS="$CFLAGS"
+@@ -419,7 +421,10 @@ AS_HELP_STRING([--enable-install-elfh],[
+ AM_CONDITIONAL(INSTALL_ELFH, test "$install_elfh" = yes)
+
+ AM_CONDITIONAL(BUILD_STATIC, [dnl
+-test "$use_gprof" = yes -o "$use_gcov" = yes])
++test "$use_gprof" = yes -o "$use_gcov" = yes -o "$enable_static" = yes])
++
++AM_CONDITIONAL(BUILD_SHARED, [dnl
++test "$enable_shared" = yes])
+
+ AC_ARG_ENABLE([tests-rpath],
+ AS_HELP_STRING([--enable-tests-rpath],[build $ORIGIN-using rpath into tests]),
+--- a/libelf/Makefile.am
++++ b/libelf/Makefile.am
+@@ -35,8 +35,11 @@ endif
+ VERSION = 1
+
+ lib_LIBRARIES = libelf.a
++if BUILD_SHARED
+ noinst_LIBRARIES = libelf_pic.a
+ noinst_DATA = $(noinst_LIBRARIES:_pic.a=.so)
++endif
++
+ include_HEADERS = libelf.h gelf.h nlist.h
+
+ noinst_HEADERS = abstract.h common.h exttypes.h gelf_xlate.h libelfP.h \
+@@ -122,11 +125,15 @@ libelf.so: $(srcdir)/libelf.map $(libelf
+ @$(textrel_check)
+ $(AM_V_at)ln -fs $@ $@.$(VERSION)
+
++if BUILD_SHARED
+ install: install-am libelf.so
+ $(mkinstalldirs) $(DESTDIR)$(libdir)
+ $(INSTALL_PROGRAM) libelf.so $(DESTDIR)$(libdir)/libelf-$(PACKAGE_VERSION).so
+ ln -fs libelf-$(PACKAGE_VERSION).so $(DESTDIR)$(libdir)/libelf.so.$(VERSION)
+ ln -fs libelf.so.$(VERSION) $(DESTDIR)$(libdir)/libelf.so
++else
++libelf_a_LIBADD = $(foreach dep,$(libelf_so_DEPS:.so=.a) $(LIBS:.so=.a),$(if $(findstring a,$(suffix $(dep))),$(addprefix $(dir $(dep)),$(shell cat $(basename $(dep)).manifest)),$(dep)))
++endif
+
+ uninstall: uninstall-am
+ rm -f $(DESTDIR)$(libdir)/libelf-$(PACKAGE_VERSION).so
+--- a/libdw/Makefile.am
++++ b/libdw/Makefile.am
+@@ -35,8 +35,10 @@ AM_CPPFLAGS += -I$(srcdir)/../libebl -I$
+ VERSION = 1
+
+ lib_LIBRARIES = libdw.a
++if BUILD_SHARED
+ noinst_LIBRARIES = libdw_pic.a
+ noinst_DATA = $(noinst_LIBRARIES:_pic.a=.so)
++endif
+
+ include_HEADERS = dwarf.h
+ pkginclude_HEADERS = libdw.h known-dwarf.h
+@@ -121,11 +123,13 @@ libdw.so: $(srcdir)/libdw.map $(libdw_so
+ @$(textrel_check)
+ $(AM_V_at)ln -fs $@ $@.$(VERSION)
+
++if BUILD_SHARED
+ install: install-am libdw.so
+ $(mkinstalldirs) $(DESTDIR)$(libdir)
+ $(INSTALL_PROGRAM) libdw.so $(DESTDIR)$(libdir)/libdw-$(PACKAGE_VERSION).so
+ ln -fs libdw-$(PACKAGE_VERSION).so $(DESTDIR)$(libdir)/libdw.so.$(VERSION)
+ ln -fs libdw.so.$(VERSION) $(DESTDIR)$(libdir)/libdw.so
++endif
+
+ uninstall: uninstall-am
+ rm -f $(DESTDIR)$(libdir)/libdw-$(PACKAGE_VERSION).so
+@@ -148,6 +152,10 @@ libdw_a_LIBADD += $(addprefix ../backend
+ libcpu_objects = $(shell $(AR) t ../libcpu/libcpu.a)
+ libdw_a_LIBADD += $(addprefix ../libcpu/,$(libcpu_objects))
+
++if !BUILD_SHARED
++libdw_a_LIBADD += $(foreach dep,$(libdw_so_DEPS:.so=.a) $(LIBS:.so=.a),$(if $(findstring a,$(suffix $(dep))),$(addprefix $(dir $(dep)),$(shell cat $(basename $(dep)).manifest)),$(dep)))
++endif
++
+ noinst_HEADERS = libdwP.h memory-access.h dwarf_abbrev_hash.h \
+ dwarf_sig8_hash.h cfi.h encoded-value.h
+
+--- a/libasm/Makefile.am
++++ b/libasm/Makefile.am
+@@ -33,8 +33,11 @@ AM_CPPFLAGS += -I$(top_srcdir)/libelf -I
+ VERSION = 1
+
+ lib_LIBRARIES = libasm.a
++if BUILD_SHARED
+ noinst_LIBRARIES = libasm_pic.a
+ noinst_DATA = $(noinst_LIBRARIES:_pic.a=.so)
++endif
++
+ pkginclude_HEADERS = libasm.h
+
+ libasm_a_SOURCES = asm_begin.c asm_abort.c asm_end.c asm_error.c \
+@@ -71,11 +74,15 @@ libasm.so: $(srcdir)/libasm.map $(libasm
+ @$(textrel_check)
+ $(AM_V_at)ln -fs $@ $@.$(VERSION)
+
++if BUILD_SHARED
+ install: install-am libasm.so
+ $(mkinstalldirs) $(DESTDIR)$(libdir)
+ $(INSTALL_PROGRAM) libasm.so $(DESTDIR)$(libdir)/libasm-$(PACKAGE_VERSION).so
+ ln -fs libasm-$(PACKAGE_VERSION).so $(DESTDIR)$(libdir)/libasm.so.$(VERSION)
+ ln -fs libasm.so.$(VERSION) $(DESTDIR)$(libdir)/libasm.so
++else
++libasm_a_LIBADD = $(foreach dep,$(libasm_so_DEPS:.so=.a) $(LIBS:.so=.a),$(if $(findstring a,$(suffix $(dep))),$(addprefix $(dir $(dep)),$(shell cat $(basename $(dep)).manifest)),$(dep)))
++endif
+
+ uninstall: uninstall-am
+ rm -f $(DESTDIR)$(libdir)/libasm-$(PACKAGE_VERSION).so
+--- a/debuginfod/Makefile.am
++++ b/debuginfod/Makefile.am
+@@ -77,8 +77,10 @@ debuginfod_find_LDADD = $(libdw) $(libel
+
+ if LIBDEBUGINFOD
+ noinst_LIBRARIES = libdebuginfod.a
++if BUILD_SHARED
+ noinst_LIBRARIES += libdebuginfod_pic.a
+ endif
++endif
+
+ libdebuginfod_a_SOURCES = debuginfod-client.c
+ libdebuginfod_pic_a_SOURCES = debuginfod-client.c
+@@ -111,12 +113,16 @@ $(LIBDEBUGINFOD_SONAME): $(srcdir)/libde
+ libdebuginfod.so: $(LIBDEBUGINFOD_SONAME)
+ ln -fs $< $@
+
++if BUILD_SHARED
+ install: install-am libdebuginfod.so
+ $(mkinstalldirs) $(DESTDIR)$(libdir)
+ $(INSTALL_PROGRAM) $(LIBDEBUGINFOD_SONAME) \
+ $(DESTDIR)$(libdir)/libdebuginfod-$(PACKAGE_VERSION).so
+ ln -fs libdebuginfod-$(PACKAGE_VERSION).so $(DESTDIR)$(libdir)/$(LIBDEBUGINFOD_SONAME)
+ ln -fs libdebuginfod-$(PACKAGE_VERSION).so $(DESTDIR)$(libdir)/libdebuginfod.so
++else
++libdebuginfod_a_LIBADD = $(foreach dep,$(wildcard $(libdebuginfod_so_LDLIBS:.so=.a)) $(LIBS:.so=.a),$(if $(findstring a,$(suffix $(dep))),$(addprefix $(dir $(dep)),$(shell cat $(basename $(dep)).manifest)),$(dep)))
++endif
+
+ uninstall: uninstall-am
+ rm -f $(DESTDIR)$(libdir)/libdebuginfod-$(PACKAGE_VERSION).so
+--- a/tests/Makefile.am
++++ b/tests/Makefile.am
+@@ -50,7 +50,7 @@ check_PROGRAMS = arextract arsymtest new
+ dwfl-report-offline-memory \
+ varlocs backtrace backtrace-child \
+ backtrace-data backtrace-dwarf debuglink debugaltlink \
+- buildid deleted deleted-lib.so aggregate_size peel_type \
++ buildid aggregate_size peel_type \
+ vdsosyms \
+ getsrc_die strptr newdata elfstrtab dwfl-proc-attach \
+ elfshphehdr elfstrmerge dwelfgnucompressed elfgetchdr \
+@@ -180,7 +180,7 @@ TESTS = run-arextract.sh run-arsymtest.s
+ run-readelf-addr.sh run-readelf-str.sh \
+ run-readelf-multi-noline.sh \
+ run-readelf-types.sh \
+- run-readelf-dwz-multi.sh run-allfcts-multi.sh run-deleted.sh \
++ run-readelf-dwz-multi.sh run-allfcts-multi.sh \
+ run-linkmap-cut.sh run-aggregate-size.sh run-peel-type.sh \
+ vdsosyms run-readelf-A.sh \
+ run-getsrc-die.sh run-strptr.sh newdata elfstrtab dwfl-proc-attach \
+@@ -284,6 +284,11 @@ funcretval_test__11_SOURCES = funcretval
+ TESTS += run-funcretval++11.sh
+ endif
+
++if BUILD_SHARED
++check_PROGRAMS += deleted deleted-lib.so
++TESTS += run-deleted.sh
++endif
++
+ EXTRA_DIST = run-arextract.sh run-arsymtest.sh run-ar.sh \
+ run-ar-N.sh \
+ run-show-die-info.sh run-get-files.sh run-get-lines.sh \
diff --git a/tools/elfutils/patches/110-objects-manifest.patch b/tools/elfutils/patches/110-objects-manifest.patch
new file mode 100644
index 0000000..1f5b5d2
--- /dev/null
+++ b/tools/elfutils/patches/110-objects-manifest.patch
@@ -0,0 +1,161 @@
+--- a/libdw/Makefile.am
++++ b/libdw/Makefile.am
+@@ -137,19 +137,19 @@ uninstall: uninstall-am
+ rm -f $(DESTDIR)$(libdir)/libdw.so
+ rmdir --ignore-fail-on-non-empty $(DESTDIR)$(includedir)/elfutils
+
+-libdwfl_objects = $(shell $(AR) t ../libdwfl/libdwfl.a)
++libdwfl_objects = $(shell cat ../libdwfl/libdwfl.manifest)
+ libdw_a_LIBADD = $(addprefix ../libdwfl/,$(libdwfl_objects))
+
+-libdwelf_objects = $(shell $(AR) t ../libdwelf/libdwelf.a)
++libdwelf_objects = $(shell cat ../libdwelf/libdwelf.manifest)
+ libdw_a_LIBADD += $(addprefix ../libdwelf/,$(libdwelf_objects))
+
+-libebl_objects = $(shell $(AR) t ../libebl/libebl.a)
++libebl_objects = $(shell cat ../libebl/libebl.manifest)
+ libdw_a_LIBADD += $(addprefix ../libebl/,$(libebl_objects))
+
+-backends_objects = $(shell $(AR) t ../backends/libebl_backends.a)
++backends_objects = $(shell cat ../backends/libebl_backends.manifest)
+ libdw_a_LIBADD += $(addprefix ../backends/,$(backends_objects))
+
+-libcpu_objects = $(shell $(AR) t ../libcpu/libcpu.a)
++libcpu_objects = $(shell cat ../libcpu/libcpu.manifest)
+ libdw_a_LIBADD += $(addprefix ../libcpu/,$(libcpu_objects))
+
+ if !BUILD_SHARED
+@@ -161,4 +161,9 @@ noinst_HEADERS = libdwP.h memory-access.
+
+ EXTRA_DIST = libdw.map
+
+-MOSTLYCLEANFILES = $(am_libdw_pic_a_OBJECTS) libdw.so libdw.so.$(VERSION)
++EXTRA_libdw_a_DEPENDENCIES = libdw.manifest
++
++libdw.manifest: $(libdw_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(am_libdw_pic_a_OBJECTS) $(EXTRA_libdw_a_DEPENDENCIES) libdw.so libdw.so.$(VERSION)
+--- a/libdwfl/Makefile.am
++++ b/libdwfl/Makefile.am
+@@ -93,4 +93,10 @@ am_libdwfl_pic_a_OBJECTS = $(libdwfl_a_S
+
+ noinst_HEADERS = libdwflP.h
+
++EXTRA_libdwfl_a_DEPENDENCIES = libdwfl.manifest
++
++libdwfl.manifest: $(libdwfl_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(EXTRA_libdwfl_a_DEPENDENCIES)
+ CLEANFILES += $(am_libdwfl_pic_a_OBJECTS)
+--- a/libdwelf/Makefile.am
++++ b/libdwelf/Makefile.am
+@@ -54,4 +54,10 @@ libeu = ../lib/libeu.a
+ libdwelf_pic_a_SOURCES =
+ am_libdwelf_pic_a_OBJECTS = $(libdwelf_a_SOURCES:.c=.os)
+
++EXTRA_libdwelf_a_DEPENDENCIES = libdwelf.manifest
++
++libdwelf.manifest: $(libdwelf_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(EXTRA_libdwelf_a_DEPENDENCIES)
+ CLEANFILES += $(am_libdwelf_pic_a_OBJECTS)
+--- a/libebl/Makefile.am
++++ b/libebl/Makefile.am
+@@ -61,4 +61,9 @@ am_libebl_pic_a_OBJECTS = $(libebl_a_SOU
+
+ noinst_HEADERS = libebl.h libeblP.h ebl-hooks.h
+
+-MOSTLYCLEANFILES = $(am_libebl_pic_a_OBJECTS)
++EXTRA_libebl_a_DEPENDENCIES = libebl.manifest
++
++libebl.manifest: $(libebl_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(am_libebl_pic_a_OBJECTS) $(EXTRA_libebl_a_DEPENDENCIES)
+--- a/backends/Makefile.am
++++ b/backends/Makefile.am
+@@ -119,4 +119,9 @@ am_libebl_backends_pic_a_OBJECTS = $(lib
+ noinst_HEADERS = libebl_CPU.h common-reloc.c linux-core-note.c x86_corenote.c
+ EXTRA_DIST = $(modules:=_reloc.def)
+
+-MOSTLYCLEANFILES = $(am_libebl_backends_pic_a_OBJECTS)
++EXTRA_libebl_backends_a_DEPENDENCIES = libebl_backends.manifest
++
++libebl_backends.manifest: $(libebl_backends_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(am_libebl_backends_pic_a_OBJECTS) $(EXTRA_libebl_backends_a_DEPENDENCIES)
+--- a/libcpu/Makefile.am
++++ b/libcpu/Makefile.am
+@@ -101,6 +101,11 @@ bpf_disasm_CFLAGS = -Wno-format-nonliter
+
+ EXTRA_DIST = defs/i386
+
+-MOSTLYCLEANFILES = $(am_libcpu_pic_a_OBJECTS)
++EXTRA_libcpu_a_DEPENDENCIES = libcpu.manifest
++
++libcpu.manifest: $(libcpu_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(am_libcpu_pic_a_OBJECTS) $(EXTRA_libcpu_a_DEPENDENCIES)
+ CLEANFILES += $(foreach P,i386 x86_64,$P_defs $P.mnemonics)
+ MAINTAINERCLEANFILES = $(foreach P,i386 x86_64, $P_dis.h)
+--- a/libelf/Makefile.am
++++ b/libelf/Makefile.am
+@@ -142,4 +142,10 @@ uninstall: uninstall-am
+
+ EXTRA_DIST = libelf.map
+
++EXTRA_libelf_a_DEPENDENCIES = libelf.manifest
++
++libelf.manifest: $(libelf_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(EXTRA_libelf_a_DEPENDENCIES)
+ CLEANFILES += $(am_libelf_pic_a_OBJECTS) libelf.so libelf.so.$(VERSION)
+--- a/lib/Makefile.am
++++ b/lib/Makefile.am
+@@ -41,3 +41,10 @@ noinst_HEADERS = fixedsizehash.h libeu.h
+ eu-config.h color.h printversion.h bpf.h \
+ atomics.h stdatomic-fbsd.h dynamicsizehash_concurrent.h
+ EXTRA_DIST = dynamicsizehash.c dynamicsizehash_concurrent.c
++
++EXTRA_libeu_a_DEPENDENCIES = libeu.manifest
++
++libeu.manifest: $(libeu_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(EXTRA_libeu_a_DEPENDENCIES)
+--- a/libasm/Makefile.am
++++ b/libasm/Makefile.am
+@@ -93,4 +93,10 @@ uninstall: uninstall-am
+ noinst_HEADERS = libasmP.h symbolhash.h
+ EXTRA_DIST = libasm.map
+
++EXTRA_libasm_a_DEPENDENCIES = libasm.manifest
++
++libasm.manifest: $(libasm_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(EXTRA_libasm_a_DEPENDENCIES)
+ CLEANFILES += $(am_libasm_pic_a_OBJECTS) libasm.so libasm.so.$(VERSION)
+--- a/debuginfod/Makefile.am
++++ b/debuginfod/Makefile.am
+@@ -132,7 +132,13 @@ uninstall: uninstall-am
+ endif
+
+ EXTRA_DIST = libdebuginfod.map
+-MOSTLYCLEANFILES = $(am_libdebuginfod_pic_a_OBJECTS) $(LIBDEBUGINFOD_SONAME)
++
++EXTRA_libdebuginfod_a_DEPENDENCIES = libdebuginfod.manifest
++
++libdebuginfod.manifest: $(libdebuginfod_a_OBJECTS)
++ echo $^ > $@
++
++MOSTLYCLEANFILES = $(am_libdebuginfod_pic_a_OBJECTS) $(LIBDEBUGINFOD_SONAME) $(EXTRA_libdebuginfod_a_DEPENDENCIES)
+ CLEANFILES += $(am_libdebuginfod_pic_a_OBJECTS) libdebuginfod.so
+
+ # automake std-options override: arrange to pass LD_LIBRARY_PATH
diff --git a/tools/expat/Makefile b/tools/expat/Makefile
new file mode 100644
index 0000000..d488372
--- /dev/null
+++ b/tools/expat/Makefile
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2006-2014 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=expat
+PKG_CPE_ID:=cpe:/a:libexpat:libexpat
+PKG_VERSION:=2.6.3
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_HASH:=17aa6cfc5c4c219c09287abfc10bc13f0c06f30bb654b28bfe6f567ca646eb79
+PKG_SOURCE_URL:=https://github.com/libexpat/libexpat/releases/download/R_$(subst .,_,$(PKG_VERSION))
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+
+HOST_CONFIGURE_ARGS += \
+ --disable-shared \
+ --without-docbook \
+ --without-tests \
+ --with-pic
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/fakeroot/Makefile b/tools/fakeroot/Makefile
new file mode 100644
index 0000000..22b2c8f
--- /dev/null
+++ b/tools/fakeroot/Makefile
@@ -0,0 +1,32 @@
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=fakeroot
+PKG_VERSION:=1.36
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)_$(PKG_VERSION).orig.tar.gz
+PKG_SOURCE_URL:=@DEBIAN/pool/main/f/fakeroot
+PKG_HASH:=7fe3cf3daf95ee93b47e568e85f4d341a1f9ae91766b4f9a9cdc29737dea4988
+PKG_LICENSE:=GPL-3.0-or-later
+PKG_LICENSE_FILES:=COPYING
+PKG_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_VARS += \
+ ac_cv_header_sys_capability_h=no \
+ ac_cv_func_capset=no \
+ CPP="$(HOSTCC) -E"
+
+HOST_CONFIGURE_ARGS += \
+ --with-ipc=tcp
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/fakeroot/patches/000-relocatable.patch b/tools/fakeroot/patches/000-relocatable.patch
new file mode 100644
index 0000000..44897c5
--- /dev/null
+++ b/tools/fakeroot/patches/000-relocatable.patch
@@ -0,0 +1,29 @@
+--- a/scripts/fakeroot.in
++++ b/scripts/fakeroot.in
+@@ -30,13 +30,20 @@ fatal ()
+ }
+
+ # strip /bin/fakeroot to find install prefix
+-FAKEROOT_PREFIX=@prefix@
+-FAKEROOT_BINDIR=@bindir@
++if [ -n "$STAGING_DIR_HOST" ]; then
++ USEABSLIBPATH=1
++ FAKEROOT_LIB=${STAGING_DIR_HOST}/lib/lib@fakeroot_transformed@@DLSUFFIX@
++ FAKED=${STAGING_DIR_HOST}/bin/faked
++ PATHS=
++else
++ FAKEROOT_PREFIX=@prefix@
++ FAKEROOT_BINDIR=@bindir@
+
+-USEABSLIBPATH=@LDPRELOADABS@
+-FAKEROOT_LIB=lib@fakeroot_transformed@@DLSUFFIX@
+-PATHS=@libdir@:${FAKEROOT_PREFIX}/lib64/libfakeroot:${FAKEROOT_PREFIX}/lib32/libfakeroot
+-FAKED=${FAKEROOT_BINDIR}/@faked_transformed@
++ USEABSLIBPATH=@LDPRELOADABS@
++ FAKEROOT_LIB=lib@fakeroot_transformed@@DLSUFFIX@
++ PATHS=@libdir@:${FAKEROOT_PREFIX}/lib64/libfakeroot:${FAKEROOT_PREFIX}/lib32/libfakeroot
++ FAKED=${FAKEROOT_BINDIR}/@faked_transformed@
++fi
+
+ FAKED_MODE="unknown-is-root"
+ export FAKED_MODE
diff --git a/tools/fakeroot/patches/200-disable-doc.patch b/tools/fakeroot/patches/200-disable-doc.patch
new file mode 100644
index 0000000..cceb6cc
--- /dev/null
+++ b/tools/fakeroot/patches/200-disable-doc.patch
@@ -0,0 +1,10 @@
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -1,6 +1,6 @@
+ AUTOMAKE_OPTIONS=foreign
+ ACLOCAL_AMFLAGS = -I build-aux
+-SUBDIRS=doc scripts test
++SUBDIRS=scripts test
+
+ noinst_LTLIBRARIES = libcommunicate.la libmacosx.la libfakeroot_time64.la
+ libcommunicate_la_SOURCES = communicate.c
diff --git a/tools/fakeroot/patches/300-time64-hack.patch b/tools/fakeroot/patches/300-time64-hack.patch
new file mode 100644
index 0000000..46132cd
--- /dev/null
+++ b/tools/fakeroot/patches/300-time64-hack.patch
@@ -0,0 +1,11 @@
+--- a/configure.ac
++++ b/configure.ac
+@@ -390,7 +390,7 @@ dnl Digital Unix: stat
+ time64_hack=no
+ AH_TEMPLATE([TIME64_HACK], [time64 shuffle])
+ AC_MSG_CHECKING([if we need to cope with time64])
+-AC_EGREP_CPP([time64],[
++AC_EGREP_CPP([_*[a-z0-9]+_time64[^_]],[
+ #include <bits/wordsize.h>
+ #if __WORDSIZE == 32
+ #define __USE_TIME_BITS64 1
diff --git a/tools/fakeroot/patches/400-alpine-libc.musl-fix.patch b/tools/fakeroot/patches/400-alpine-libc.musl-fix.patch
new file mode 100644
index 0000000..5936034
--- /dev/null
+++ b/tools/fakeroot/patches/400-alpine-libc.musl-fix.patch
@@ -0,0 +1,23 @@
+Alpine linux libc.musl build error fix
+
+Prevent build error on Alpine Linux host:
+libfakeroot.c error: conflicting types for 'id_t'
+Error relocating openwrt/staging_dir/host/lib/libfakeroot.so: SEND_GET_XATTR: symbol not found
+
+--- a/libfakeroot.c
++++ b/libfakeroot.c
+@@ -86,12 +86,14 @@
+ #define SEND_STAT64(a,b,c) send_stat64(a,b,c)
+ #define SEND_GET_STAT(a,b) send_get_stat(a,b)
+ #define SEND_GET_STAT64(a,b) send_get_stat64(a,b)
++#define SEND_GET_XATTR(a,b,c) send_get_xattr(a,b,c)
+ #define SEND_GET_XATTR64(a,b,c) send_get_xattr64(a,b,c)
+ #else
+ #define SEND_STAT(a,b,c) send_stat(a,b)
+ #define SEND_STAT64(a,b,c) send_stat64(a,b)
+ #define SEND_GET_STAT(a,b) send_get_stat(a)
+ #define SEND_GET_STAT64(a,b) send_get_stat64(a)
++#define SEND_GET_XATTR(a,b,c) send_get_xattr(a,b)
+ #define SEND_GET_XATTR64(a,b,c) send_get_xattr64(a,b)
+ #endif
+
diff --git a/tools/fakeroot/patches/600-macOS.patch b/tools/fakeroot/patches/600-macOS.patch
new file mode 100644
index 0000000..df4eb2d
--- /dev/null
+++ b/tools/fakeroot/patches/600-macOS.patch
@@ -0,0 +1,56 @@
+--- a/communicate.c
++++ b/communicate.c
+@@ -441,6 +441,10 @@ void semaphore_down(){
+
+ #else /* FAKEROOT_FAKENET */
+
++#ifndef SOL_TCP
++# define SOL_TCP 6 /* this should probably be done with getprotoent */
++#endif
++
+ static struct sockaddr *get_addr(void)
+ {
+ static struct sockaddr_in addr = { 0, 0, { 0 } };
+--- a/libfakeroot_inode64.c
++++ b/libfakeroot_inode64.c
+@@ -25,7 +25,7 @@
+ #include "config.h"
+ #include "communicate.h"
+
+-#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
++#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 && !__DARWIN_ONLY_64_BIT_INO_T
+
+ #include <stdio.h>
+ #include <spawn.h>
+--- a/wrapfunc.inp
++++ b/wrapfunc.inp
+@@ -51,9 +51,11 @@ getattrlist$UNIX2003;int;(const char *pa
+ #endif
+ #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
+ #include <spawn.h>
++#if !__DARWIN_ONLY_64_BIT_INO_T
+ lstat$INODE64;int;(const char *file_name, struct stat *buf);(file_name, buf)
+ stat$INODE64;int;(const char *file_name, struct stat *buf);(file_name, buf)
+ fstat$INODE64;int;(int fd, struct stat *buf);(fd, buf)
++#endif
+ posix_spawn;int;(pid_t * __restrict pid, const char * __restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t * __restrict attrp, char *const argv[ __restrict], char *const envp[ __restrict]);(pid, path, file_actions, attrp, argv, envp)
+ posix_spawnp;int;(pid_t * __restrict pid, const char * __restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t * __restrict attrp, char *const argv[ __restrict], char *const envp[ __restrict]);(pid, path, file_actions, attrp, argv, envp)
+ #endif
+@@ -235,7 +237,7 @@ facl;int;(int fd, int cmd, int cnt, void
+ #ifdef HAVE_FTS_READ
+ fts_read;FTSENT *;(FTS *ftsp);(ftsp)
+ #ifdef __APPLE__
+-#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
++#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 && !__DARWIN_ONLY_64_BIT_INO_T
+ fts_read$INODE64;FTSENT *;(FTS *ftsp);(ftsp)
+ #endif
+ #endif /* ifdef __APPLE__ */
+@@ -243,7 +245,7 @@ fts_read$INODE64;FTSENT *;(FTS *ftsp);(f
+ #ifdef HAVE_FTS_CHILDREN
+ fts_children;FTSENT *;(FTS *ftsp, int options);(ftsp, options)
+ #ifdef __APPLE__
+-#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
++#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 && !__DARWIN_ONLY_64_BIT_INO_T
+ fts_children$INODE64;FTSENT *;(FTS *ftsp, int options);(ftsp, options)
+ #endif
+ #endif /* ifdef __APPLE__ */
diff --git a/tools/findutils/Makefile b/tools/findutils/Makefile
new file mode 100644
index 0000000..6587c75
--- /dev/null
+++ b/tools/findutils/Makefile
@@ -0,0 +1,37 @@
+#
+# Copyright (C) 2006-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=findutils
+PKG_CPE_ID:=cpe:/a:gnu:findutils
+PKG_VERSION:=4.10.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=1387e0b67ff247d2abde998f90dfbf70c1491391a59ddfecb8ae698789f0a4f5
+
+PKG_PROGRAMS:=find locate updatedb xargs
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+ifeq ($(HOST_OS),Darwin)
+ HOST_CFLAGS +=-D__nonnull\\(params\\)=
+endif
+
+HOST_CONFIGURE_ARGS += \
+ --enable-threads=pth \
+ --disable-rpath \
+ --disable-nls \
+ --without-selinux
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/firmware-utils/Makefile b/tools/firmware-utils/Makefile
new file mode 100644
index 0000000..3caaa8e
--- /dev/null
+++ b/tools/firmware-utils/Makefile
@@ -0,0 +1,21 @@
+#
+# Copyright (C) 2006-2020 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=firmware-utils
+PKG_RELEASE:=1
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL=$(PROJECT_GIT)/project/firmware-utils.git
+PKG_SOURCE_DATE:=2025-02-16
+PKG_SOURCE_VERSION:=5d1446bf57d6490573dc71f10c05e83b36d44374
+PKG_MIRROR_HASH:=e054ea416f5a596f681bba593f71dfbe8149361432d7c17f2374c60dfe227749
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+$(eval $(call HostBuild))
diff --git a/tools/firmware-utils/patches/010-allow_addr_overlapped_part_for_sdtim.patch b/tools/firmware-utils/patches/010-allow_addr_overlapped_part_for_sdtim.patch
new file mode 100644
index 0000000..743bd3b
--- /dev/null
+++ b/tools/firmware-utils/patches/010-allow_addr_overlapped_part_for_sdtim.patch
@@ -0,0 +1,11 @@
+--- a/src/ptgen.c
++++ b/src/ptgen.c
+@@ -436,7 +436,7 @@ static int gen_gptable(uint32_t signatur
+ if (parts[i].start * 2 < start) {
+ fprintf(stderr, "Invalid start %ld for partition %d!\n",
+ parts[i].start, i);
+- return ret;
++ //return ret;
+ }
+ start = parts[i].start * 2;
+ } else if (kb_align != 0) {
diff --git a/tools/flex/Makefile b/tools/flex/Makefile
new file mode 100644
index 0000000..177136b
--- /dev/null
+++ b/tools/flex/Makefile
@@ -0,0 +1,42 @@
+#
+# Copyright (C) 2008-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=flex
+PKG_CPE_ID:=cpe:/a:westes:flex
+PKG_VERSION:=2.6.4
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/westes/flex/releases/download/v$(PKG_VERSION)/
+PKG_HASH:=e87aae032bf07c26f85ac0ed3250998c37621d95f8bd748b31f15b33c45ee995
+
+HOST_FIXUP:=autoreconf
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += --disable-shared
+
+define Host/Compile
+ $(call Host/Compile/Default,SUBDIRS='src tools')
+endef
+
+define Host/Install
+ $(call Host/Compile/Default,install SUBDIRS='src tools')
+ $(LN) flex $(STAGING_DIR_HOST)/bin/lex
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall SUBDIRS='src tools')
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/lex
+ $(call Host/Clean/Default)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/flex/patches/200-build-AC_USE_SYSTEM_EXTENSIONS-in-configure.ac.patch b/tools/flex/patches/200-build-AC_USE_SYSTEM_EXTENSIONS-in-configure.ac.patch
new file mode 100644
index 0000000..7c3645c
--- /dev/null
+++ b/tools/flex/patches/200-build-AC_USE_SYSTEM_EXTENSIONS-in-configure.ac.patch
@@ -0,0 +1,27 @@
+From 24fd0551333e7eded87b64dd36062da3df2f6380 Mon Sep 17 00:00:00 2001
+From: Explorer09 <explorer09@gmail.com>
+Date: Mon, 4 Sep 2017 10:47:33 +0800
+Subject: [PATCH] build: AC_USE_SYSTEM_EXTENSIONS in configure.ac.
+
+This would, e.g. define _GNU_SOURCE in config.h, enabling the
+reallocarray() prototype in glibc 2.26+ on Linux systems with that
+version of glibc.
+
+Fixes #241.
+---
+ configure.ac | 2 ++
+ 1 file changed, 2 insertions(+)
+
+--- a/configure.ac
++++ b/configure.ac
+@@ -25,8 +25,10 @@
+ # autoconf requirements and initialization
+
+ AC_INIT([the fast lexical analyser generator],[2.6.4],[flex-help@lists.sourceforge.net],[flex])
++AC_PREREQ([2.60])
+ AC_CONFIG_SRCDIR([src/scan.l])
+ AC_CONFIG_AUX_DIR([build-aux])
++AC_USE_SYSTEM_EXTENSIONS
+ LT_INIT
+ AM_INIT_AUTOMAKE([1.11.3 -Wno-portability foreign check-news std-options dist-lzip parallel-tests subdir-objects])
+ AC_CONFIG_HEADER([src/config.h])
diff --git a/tools/flex/patches/300-m4-path.patch b/tools/flex/patches/300-m4-path.patch
new file mode 100644
index 0000000..48e376f
--- /dev/null
+++ b/tools/flex/patches/300-m4-path.patch
@@ -0,0 +1,23 @@
+--- a/src/main.c
++++ b/src/main.c
+@@ -213,6 +213,8 @@ int main (int argc, char *argv[])
+
+ void check_options (void)
+ {
++ const char * staging_dir = NULL;
++ char * m4_staging = NULL;
+ int i;
+ const char * m4 = NULL;
+
+@@ -341,7 +343,10 @@ void check_options (void)
+
+ /* Setup the filter chain. */
+ output_chain = filter_create_int(NULL, filter_tee_header, headerfilename);
+- if ( !(m4 = getenv("M4"))) {
++ if ( (staging_dir = getenv("STAGING_DIR_HOST"))) {
++ asprintf(&m4_staging, "%s/bin/m4", staging_dir);
++ m4 = m4_staging;
++ } else if ( !(m4 = getenv("M4"))) {
+ char *slash;
+ m4 = M4;
+ if ((slash = strrchr(M4, '/')) != NULL) {
diff --git a/tools/flock/Makefile b/tools/flock/Makefile
new file mode 100644
index 0000000..4e0a454
--- /dev/null
+++ b/tools/flock/Makefile
@@ -0,0 +1,31 @@
+#
+# Copyright (C) 2006-2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME := flock
+PKG_VERSION := 2.18
+PKG_RELEASE := 1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOSTCXX := $(HOSTCXX_NOCACHE)
+
+define Host/Compile
+ mkdir -p $(HOST_BUILD_DIR)
+ $(HOSTCC) $(HOST_CFLAGS) -o $(HOST_BUILD_DIR)/flock src/flock.c
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/flock $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/flock
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/flock/src/flock.c b/tools/flock/src/flock.c
new file mode 100644
index 0000000..37ab0ea
--- /dev/null
+++ b/tools/flock/src/flock.c
@@ -0,0 +1,342 @@
+/* ----------------------------------------------------------------------- *
+ *
+ * Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
+ *
+ * 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.
+ *
+ * ----------------------------------------------------------------------- */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <signal.h>
+#include <ctype.h>
+#include <string.h>
+#include <paths.h>
+#include <sysexits.h>
+#include <sys/types.h>
+#include <sys/file.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+
+#define PACKAGE_STRING "util-linux-ng 2.18"
+#define _(x) (x)
+
+static const struct option long_options[] = {
+ { "shared", 0, NULL, 's' },
+ { "exclusive", 0, NULL, 'x' },
+ { "unlock", 0, NULL, 'u' },
+ { "nonblocking", 0, NULL, 'n' },
+ { "nb", 0, NULL, 'n' },
+ { "timeout", 1, NULL, 'w' },
+ { "wait", 1, NULL, 'w' },
+ { "close", 0, NULL, 'o' },
+ { "help", 0, NULL, 'h' },
+ { "version", 0, NULL, 'V' },
+ { 0, 0, 0, 0 }
+};
+
+const char *program;
+
+static void usage(int ex)
+{
+ fputs("flock (" PACKAGE_STRING ")\n", stderr);
+ fprintf(stderr,
+ _("Usage: %1$s [-sxun][-w #] fd#\n"
+ " %1$s [-sxon][-w #] file [-c] command...\n"
+ " %1$s [-sxon][-w #] directory [-c] command...\n"
+ " -s --shared Get a shared lock\n"
+ " -x --exclusive Get an exclusive lock\n"
+ " -u --unlock Remove a lock\n"
+ " -n --nonblock Fail rather than wait\n"
+ " -w --timeout Wait for a limited amount of time\n"
+ " -o --close Close file descriptor before running command\n"
+ " -c --command Run a single command string through the shell\n"
+ " -h --help Display this text\n"
+ " -V --version Display version\n"),
+ program);
+ exit(ex);
+}
+
+
+static sig_atomic_t timeout_expired = 0;
+
+static void timeout_handler(int sig)
+{
+ (void)sig;
+
+ timeout_expired = 1;
+}
+
+
+static char * strtotimeval(const char *str, struct timeval *tv)
+{
+ char *s;
+ long fs; /* Fractional seconds */
+ int i;
+
+ tv->tv_sec = strtol(str, &s, 10);
+ fs = 0;
+
+ if ( *s == '.' ) {
+ s++;
+
+ for ( i = 0 ; i < 6 ; i++ ) {
+ if ( !isdigit(*s) )
+ break;
+
+ fs *= 10;
+ fs += *s++ - '0';
+ }
+
+ for ( ; i < 6; i++ )
+ fs *= 10;
+
+ while ( isdigit(*s) )
+ s++;
+ }
+
+ tv->tv_usec = fs;
+ return s;
+}
+
+int main(int argc, char *argv[])
+{
+ struct itimerval timeout, old_timer;
+ int have_timeout = 0;
+ int type = LOCK_EX;
+ int block = 0;
+ int fd = -1;
+ int opt, ix;
+ int do_close = 0;
+ int err;
+ int status;
+ int open_flags = 0;
+ char *eon;
+ char **cmd_argv = NULL, *sh_c_argv[4];
+ const char *filename = NULL;
+ struct sigaction sa, old_sa;
+
+ program = argv[0];
+
+ if ( argc < 2 )
+ usage(EX_USAGE);
+
+ memset(&timeout, 0, sizeof timeout);
+
+ optopt = 0;
+ while ( (opt = getopt_long(argc, argv, "+sexnouw:hV?", long_options, &ix)) != EOF ) {
+ switch(opt) {
+ case 's':
+ type = LOCK_SH;
+ break;
+ case 'e':
+ case 'x':
+ type = LOCK_EX;
+ break;
+ case 'u':
+ type = LOCK_UN;
+ break;
+ case 'o':
+ do_close = 1;
+ break;
+ case 'n':
+ block = LOCK_NB;
+ break;
+ case 'w':
+ have_timeout = 1;
+ eon = strtotimeval(optarg, &timeout.it_value);
+ if ( *eon )
+ usage(EX_USAGE);
+ break;
+ case 'V':
+ printf("flock (%s)\n", PACKAGE_STRING);
+ exit(0);
+ default:
+ /* optopt will be set if this was an unrecognized option, i.e. *not* 'h' or '?' */
+ usage(optopt ? EX_USAGE : 0);
+ break;
+ }
+ }
+
+ if ( argc > optind+1 ) {
+ /* Run command */
+
+ if ( !strcmp(argv[optind+1], "-c") ||
+ !strcmp(argv[optind+1], "--command") ) {
+
+ if ( argc != optind+3 ) {
+ fprintf(stderr, _("%s: %s requires exactly one command argument\n"),
+ program, argv[optind+1]);
+ exit(EX_USAGE);
+ }
+
+ cmd_argv = sh_c_argv;
+
+ cmd_argv[0] = getenv("SHELL");
+ if ( !cmd_argv[0] || !*cmd_argv[0] )
+ cmd_argv[0] = _PATH_BSHELL;
+
+ cmd_argv[1] = "-c";
+ cmd_argv[2] = argv[optind+2];
+ cmd_argv[3] = 0;
+ } else {
+ cmd_argv = &argv[optind+1];
+ }
+
+ filename = argv[optind];
+ fd = open(filename, O_RDONLY|O_NOCTTY|O_CREAT, 0666);
+ /* Linux doesn't like O_CREAT on a directory, even though it should be a
+ no-op */
+ if (fd < 0 && errno == EISDIR)
+ fd = open(filename, O_RDONLY|O_NOCTTY);
+
+ if ( fd < 0 ) {
+ err = errno;
+ fprintf(stderr, _("%s: cannot open lock file %s: %s\n"),
+ program, argv[optind], strerror(err));
+ exit((err == ENOMEM||err == EMFILE||err == ENFILE) ? EX_OSERR :
+ (err == EROFS||err == ENOSPC) ? EX_CANTCREAT :
+ EX_NOINPUT);
+ }
+
+ } else if (optind < argc) {
+ /* Use provided file descriptor */
+
+ fd = (int)strtol(argv[optind], &eon, 10);
+ if ( *eon || !argv[optind] ) {
+ fprintf(stderr, _("%s: bad number: %s\n"), program, argv[optind]);
+ exit(EX_USAGE);
+ }
+
+ } else {
+ /* Bad options */
+
+ fprintf(stderr, _("%s: requires file descriptor, file or directory\n"),
+ program);
+ exit(EX_USAGE);
+ }
+
+
+ if ( have_timeout ) {
+ if ( timeout.it_value.tv_sec == 0 &&
+ timeout.it_value.tv_usec == 0 ) {
+ /* -w 0 is equivalent to -n; this has to be special-cased
+ because setting an itimer to zero means disabled! */
+
+ have_timeout = 0;
+ block = LOCK_NB;
+ } else {
+ memset(&sa, 0, sizeof sa);
+
+ sa.sa_handler = timeout_handler;
+ sa.sa_flags = SA_RESETHAND;
+ sigaction(SIGALRM, &sa, &old_sa);
+
+ setitimer(ITIMER_REAL, &timeout, &old_timer);
+ }
+ }
+
+ while ( flock(fd, type|block) ) {
+ switch( (err = errno) ) {
+ case EWOULDBLOCK: /* -n option set and failed to lock */
+ exit(1);
+ case EINTR: /* Signal received */
+ if ( timeout_expired )
+ exit(1); /* -w option set and failed to lock */
+ continue; /* otherwise try again */
+ case EBADF: /* since Linux 3.4 (commit 55725513) */
+ /* Probably NFSv4 where flock() is emulated by fcntl().
+ * Let's try to reopen in read-write mode.
+ */
+ if (!(open_flags & O_RDWR) &&
+ type != LOCK_SH &&
+ filename &&
+ access(filename, R_OK | W_OK) == 0) {
+
+ close(fd);
+ open_flags = O_RDWR;
+ fd = open(filename, open_flags);
+ break;
+ }
+ /* go through */
+ default: /* Other errors */
+ if ( filename )
+ fprintf(stderr, "%s: %s: %s\n", program, filename, strerror(err));
+ else
+ fprintf(stderr, "%s: %d: %s\n", program, fd, strerror(err));
+ exit((err == ENOLCK||err == ENOMEM) ? EX_OSERR : EX_DATAERR);
+ }
+ }
+
+ if ( have_timeout ) {
+ setitimer(ITIMER_REAL, &old_timer, NULL); /* Cancel itimer */
+ sigaction(SIGALRM, &old_sa, NULL); /* Cancel signal handler */
+ }
+
+ status = 0;
+
+ if ( cmd_argv ) {
+ pid_t w, f;
+
+ /* Clear any inherited settings */
+ signal(SIGCHLD, SIG_DFL);
+ f = fork();
+
+ if ( f < 0 ) {
+ err = errno;
+ fprintf(stderr, _("%s: fork failed: %s\n"), program, strerror(err));
+ exit(EX_OSERR);
+ } else if ( f == 0 ) {
+ if ( do_close )
+ close(fd);
+ err = errno;
+ execvp(cmd_argv[0], cmd_argv);
+ /* execvp() failed */
+ fprintf(stderr, "%s: %s: %s\n", program, cmd_argv[0], strerror(err));
+ _exit((err == ENOMEM) ? EX_OSERR: EX_UNAVAILABLE);
+ } else {
+ do {
+ w = waitpid(f, &status, 0);
+ if (w == -1 && errno != EINTR)
+ break;
+ } while ( w != f );
+
+ if (w == -1) {
+ err = errno;
+ status = EXIT_FAILURE;
+ fprintf(stderr, "%s: waitpid failed: %s\n", program, strerror(err));
+ } else if ( WIFEXITED(status) )
+ status = WEXITSTATUS(status);
+ else if ( WIFSIGNALED(status) )
+ status = WTERMSIG(status) + 128;
+ else
+ status = EX_OSERR; /* WTF? */
+ }
+ }
+
+ return status;
+}
+
diff --git a/tools/genext2fs/Makefile b/tools/genext2fs/Makefile
new file mode 100644
index 0000000..4e7abf8
--- /dev/null
+++ b/tools/genext2fs/Makefile
@@ -0,0 +1,58 @@
+#
+# Copyright (C) 2006 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=genext2fs
+PKG_VERSION:=1.5.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://codeload.github.com/bestouff/$(PKG_NAME)/tar.gz/v$(PKG_VERSION)?
+PKG_HASH:=d3861e4fe89131bd21fbd25cf0b683b727b5c030c4c336fadcd738ada830aab0
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS = \
+ --target=$(GNU_HOST_NAME) \
+ --host=$(GNU_HOST_NAME) \
+ --build=$(GNU_HOST_NAME) \
+ --program-prefix="" \
+ --program-suffix="" \
+ --prefix=/usr \
+ --exec-prefix=/usr \
+ --bindir=/usr/bin \
+ --sbindir=/usr/sbin \
+ --libexecdir=/usr/lib \
+ --sysconfdir=/etc \
+ --datadir=/usr/share \
+ --localstatedir=/var \
+ --mandir=/usr/man \
+ --infodir=/usr/info \
+
+define Host/Configure
+ (cd $(HOST_BUILD_DIR); \
+ ./autogen.sh \
+ );
+ $(call Host/Configure/Default)
+endef
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR) \
+ CFLAGS="$(HOST_CFLAGS)" \
+ LDFLAGS="$(HOST_LDFLAGS)" \
+ all
+endef
+
+define Host/Install
+ install -m0755 $(HOST_BUILD_DIR)/genext2fs $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/genext2fs
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/gengetopt/Makefile b/tools/gengetopt/Makefile
new file mode 100644
index 0000000..5a5b5eb
--- /dev/null
+++ b/tools/gengetopt/Makefile
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2014 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=gengetopt
+PKG_VERSION:=2.23
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=b941aec9011864978dd7fdeb052b1943535824169d2aa2b0e7eae9ab807584ac
+
+PKG_SUBDIRS:=$$$$(foreach dir,gl src skels,$$$$(wildcard $$$$(dir)) )
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ $(call Host/Compile/Default,SUBDIRS='$(PKG_SUBDIRS)')
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/src/gengetopt $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/gengetopt
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/gengetopt/patches/001-gm_utils.cpp-Call-clear-instead-of-empty.patch b/tools/gengetopt/patches/001-gm_utils.cpp-Call-clear-instead-of-empty.patch
new file mode 100644
index 0000000..6aa3f54
--- /dev/null
+++ b/tools/gengetopt/patches/001-gm_utils.cpp-Call-clear-instead-of-empty.patch
@@ -0,0 +1,25 @@
+From bfba6445a778007f40af5cbfbe725e12c0fcafc6 Mon Sep 17 00:00:00 2001
+From: Tomas Volf <~@wolfsden.cz>
+Date: Tue, 5 Mar 2024 22:25:20 +0100
+Subject: [PATCH] gm_utils.cpp: Call clear instead of empty.
+
+Since the intention seem to be to erase the next word, I believe calling empty
+was a mistake and it should have been clear. Empty does nothing in this
+context.
+
+* src/gm_utils.cpp (wrap_cstr): Call clear.
+---
+ src/gm_utils.cpp | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+--- a/src/gm_utils.cpp
++++ b/src/gm_utils.cpp
+@@ -311,7 +311,7 @@ void wrap_cstr(string& wrapped, unsigned
+ // trim leading spaces
+ std::size_t pos = next_word.find_first_not_of(' ');
+ if( pos == std::string::npos )
+- next_word.empty();
++ next_word.clear();
+ else if( pos )
+ next_word.erase( 0, pos );
+
diff --git a/tools/gengetopt/patches/002-gm_utils.h-Drop-std-unary_function.patch b/tools/gengetopt/patches/002-gm_utils.h-Drop-std-unary_function.patch
new file mode 100644
index 0000000..ce997f4
--- /dev/null
+++ b/tools/gengetopt/patches/002-gm_utils.h-Drop-std-unary_function.patch
@@ -0,0 +1,33 @@
+From a3d0a0419a35bef9b80a6a12432ab30e2d1e0f5a Mon Sep 17 00:00:00 2001
+From: Tomas Volf <~@wolfsden.cz>
+Date: Tue, 5 Mar 2024 22:27:42 +0100
+Subject: [PATCH] gm_utils.h: Drop std::unary_function.
+
+I am not sure what it does, it is deprecated/removed (depending on C++ version)
+and the advice seems to be that is just is not necessary. So just remove it.
+
+* src/gm_utils.h (print_f, pair_print_f): Drop std::unary_function.
+---
+ src/gm_utils.h | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+--- a/src/gm_utils.h
++++ b/src/gm_utils.h
+@@ -117,7 +117,7 @@ bool string_contains(const char *s, cons
+ * Function object to print something into a stream (to be used with for_each)
+ */
+ template<class T>
+-struct print_f : public std::unary_function<T, void>
++struct print_f
+ {
+ print_f(std::ostream& out, const string &s = ", ") : os(out), sep(s) {}
+ void operator() (T x) { os << x << sep; }
+@@ -129,7 +129,7 @@ struct print_f : public std::unary_funct
+ * Function object to print a pair into two streams (to be used with for_each)
+ */
+ template<class T>
+-struct pair_print_f : public std::unary_function<T, void>
++struct pair_print_f
+ {
+ pair_print_f(std::ostream& out1, std::ostream& out2, const string &s = ", ") :
+ os1(out1), os2(out2), sep(s) {}
diff --git a/tools/gmp/Makefile b/tools/gmp/Makefile
new file mode 100644
index 0000000..c6e396c
--- /dev/null
+++ b/tools/gmp/Makefile
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2009-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=gmp
+PKG_VERSION:=6.3.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@GNU/gmp/
+PKG_HASH:=a3c2b80201b89e68616f4ad30bc66aee4927c3ce50e33929ca819d5c43538898
+PKG_CPE_ID:=cpe:/a:gmplib:gmp
+
+HOST_FIXUP:=autoreconf
+
+HOST_BUILD_PARALLEL:=0
+
+include $(INCLUDE_DIR)/host-build.mk
+
+unexport CFLAGS
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static \
+ --disable-shared \
+ --disable-assembly \
+ --enable-cxx
+
+ifeq ($(GNU_HOST_NAME),x86_64-linux-gnux32)
+HOST_CONFIGURE_ARGS += ABI=x32
+endif
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/gnulib/Makefile b/tools/gnulib/Makefile
new file mode 100644
index 0000000..5119355
--- /dev/null
+++ b/tools/gnulib/Makefile
@@ -0,0 +1,28 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=gnulib
+PKG_CPE_ID:=cpe:/a:gnu:$(PKG_NAME)
+PKG_VERSION:=c99c8d491850dc3a6e0b8604a2729d8bc5c0eff1# # stable-202401
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://git.savannah.gnu.org/cgit/$(PKG_NAME).git/snapshot
+PKG_HASH:=8e6f4a907d9677b55fd452e1340a3e030a6f530b138d420c11975da33f086b1e
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(1)/share/aclocal
+ $(INSTALL_DATA) $(HOST_BUILD_DIR)/m4/*.m4 $(1)/share/aclocal/
+ $(INSTALL_DIR) $(1)/share/gnulib
+ $(CP) $(HOST_BUILD_DIR)/* $(1)/share/gnulib/
+ ln -sf ../share/gnulib/gnulib-tool $(STAGING_DIR_HOST)/bin/gnulib-tool
+endef
+
+define Host/Clean
+ rm -rf $(STAGING_DIR_HOST)/bin/gnulib-tool $(STAGING_DIR_HOST)/share/gnulib
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/gnulib/patches/000-bootstrap.patch b/tools/gnulib/patches/000-bootstrap.patch
new file mode 100644
index 0000000..1205866
--- /dev/null
+++ b/tools/gnulib/patches/000-bootstrap.patch
@@ -0,0 +1,54 @@
+--- a/build-aux/bootstrap
++++ b/build-aux/bootstrap
+@@ -237,14 +237,14 @@ test -r "$conffile" && . "$conffile"
+
+ check_exists() {
+ if test "$1" = "--verbose"; then
+- ($2 --version </dev/null) >/dev/null 2>&1
++ ($2 $3 $4 --version </dev/null) >/dev/null 2>&1
+ if test $? -ge 126; then
+ # If not found, run with diagnostics as one may be
+ # presented with env variables to set to find the right version
+- ($2 --version </dev/null)
++ ($2 $3 $4 --version </dev/null)
+ fi
+ else
+- ($1 --version </dev/null) >/dev/null 2>&1
++ ($@ --version </dev/null) >/dev/null 2>&1
+ fi
+
+ test $? -lt 126
+@@ -309,7 +309,7 @@ p
+ q'
+
+ get_version() {
+- app=$1
++ app="$@"
+
+ $app --version >/dev/null 2>&1 || { $app --version; return 1; }
+
+@@ -366,13 +366,13 @@ check_versions() {
+ if [ "$req_ver" = "-" ]; then
+ # Merely require app to exist; not all prereq apps are well-behaved
+ # so we have to rely on $? rather than get_version.
+- if ! check_exists --verbose $app; then
++ if ! check_exists --verbose "$app"; then
+ warn_ "Error: '$app' not found"
+ ret=1
+ fi
+ else
+ # Require app to produce a new enough version string.
+- inst_ver=$(get_version $app)
++ inst_ver=$(get_version "$app")
+ if [ ! "$inst_ver" ]; then
+ warn_ "Error: '$app' not found"
+ ret=1
+@@ -1157,7 +1157,7 @@ autogen()
+ # two just-pre-run programs.
+
+ # Import from gettext.
+- with_gettext=yes
++ with_gettext=no
+ grep '^[ ]*AM_GNU_GETTEXT_VERSION(' configure.ac >/dev/null || \
+ with_gettext=no
+
diff --git a/tools/gnulib/patches/010-autoconf-version.patch b/tools/gnulib/patches/010-autoconf-version.patch
new file mode 100644
index 0000000..a091bb2
--- /dev/null
+++ b/tools/gnulib/patches/010-autoconf-version.patch
@@ -0,0 +1,47 @@
+--- a/gnulib-tool
++++ b/gnulib-tool
+@@ -346,6 +346,34 @@ Options for --import, --add/remove-impor
+ Report bugs to <bug-gnulib@gnu.org>."
+ }
+
++get_version_sed='
++# Move version to start of line.
++s/.*[v ]\([0-9]\)/\1/
++
++# Skip lines that do not start with version.
++/^[0-9]/!d
++
++# Remove characters after the version.
++s/[^.a-z0-9-].*//
++
++# The first component must be digits only.
++s/^\([0-9]*\)[a-z-].*/\1/
++
++# The following essentially does s/5.005/5.5/
++s/\.0*\([1-9]\)/.\1/g
++p
++q'
++
++# get_version
++# copied from build-aux/bootstrap
++get_version () {
++ app=$1
++
++ $app --version >/dev/null 2>&1 || { $app --version; return 1; }
++
++ $app --version 2>&1 | sed -n "$get_version_sed"
++}
++
+ # func_version
+ # outputs to stdout the --version message.
+ func_version ()
+@@ -1620,6 +1648,9 @@ func_determine_path_separator
+ fi
+ case "$autoconf_minversion" in
+ 1.* | 2.[0-5]* | 2.6[0-3]*)
++ # if the version of autoconf in use is high enough, do not error
++ case "$(get_version autoconf)" in 1.* | 2.[0-5]* | 2.6[0-3]*) false ;; esac && \
++ func_warning "gnulib requires a newer version of autoconf than configure.ac ( $DEFAULT_AUTOCONF_MINVERSION > AC_PREREQ([$autoconf_minversion]) )" || \
+ func_fatal_error "minimum supported autoconf version is 2.64. Try adding AC_PREREQ([$DEFAULT_AUTOCONF_MINVERSION]) to your configure.ac." ;;
+ esac
+
diff --git a/tools/gnulib/patches/120-unmangle-darwin-fts-h.patch b/tools/gnulib/patches/120-unmangle-darwin-fts-h.patch
new file mode 100644
index 0000000..19e46b9
--- /dev/null
+++ b/tools/gnulib/patches/120-unmangle-darwin-fts-h.patch
@@ -0,0 +1,19 @@
+--- /dev/null
++++ b/lib/fts.h
+@@ -0,0 +1,6 @@
++#ifdef __APPLE__
++# define _FTS_H_ 1
++# include <fts_.h>
++#else
++# include_next <fts.h>
++#endif
+--- a/modules/fts
++++ b/modules/fts
+@@ -2,6 +2,7 @@ Description:
+ Traverse a file hierarchy.
+
+ Files:
++lib/fts.h
+ lib/fts_.h
+ lib/fts.c
+ lib/fts-cycle.c
diff --git a/tools/gnulib/patches/150-portable-tdestroy.patch b/tools/gnulib/patches/150-portable-tdestroy.patch
new file mode 100644
index 0000000..39c291f
--- /dev/null
+++ b/tools/gnulib/patches/150-portable-tdestroy.patch
@@ -0,0 +1,193 @@
+--- a/lib/search.in.h
++++ b/lib/search.in.h
+@@ -112,6 +112,11 @@ _GL_CXXALIASWARN (lsearch);
+ # define twalk rpl_twalk
+ # endif
+ # endif
++# if @REPLACE_TDESTROY@
++# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
++# define tdestroy rpl_tdestroy
++# endif
++# endif
+
+ /* See <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/search.h.html>
+ <https://pubs.opengroup.org/onlinepubs/9699919799/functions/tsearch.html>
+@@ -137,6 +142,7 @@ extern "C" {
+ # if !GNULIB_defined_search_fn_types
+ typedef int (*_gl_search_compar_fn) (const void *, const void *);
+ typedef void (*_gl_search_action_fn) (const void *, VISIT, int);
++typedef void (*_gl_search_free_fn) (void *);
+ # define GNULIB_defined_search_fn_types 1
+ # endif
+ # ifdef __cplusplus
+@@ -252,9 +258,36 @@ _GL_CXXALIAS_SYS (twalk, void,
+ _GL_CXXALIASWARN (twalk);
+ # endif
+
++/* Removes the whole tree pointed to by root,
++ freeing all resources allocated by the tsearch() function.
++ The FREE_NODE function is called:
++ - For the data in each tree node.
++ - Even when no such work is necessary, to a function doing nothing
++ The arguments passed to FREE_NODE are:
++ 1. The pointer to the data. */
++# if @REPLACE_TDESTROY@
++_GL_FUNCDECL_RPL (tdestroy, void,
++ (void *vroot, _gl_search_free_fn freefct)
++ _GL_ARG_NONNULL ((2)));
++_GL_CXXALIAS_RPL (tdestroy, void,
++ (void *vroot, _gl_search_free_fn freefct));
++# else
++# if !@HAVE_TDESTROY@
++_GL_FUNCDECL_SYS (tdestroy, void,
++ (void *vroot, _gl_search_free_fn freefct)
++ _GL_ARG_NONNULL ((2)));
++# endif
++_GL_CXXALIAS_SYS (tdestroy, void,
++ (void *vroot, _gl_search_free_fn freefct));
++# endif
++# if __GLIBC__ >= 2
++_GL_CXXALIASWARN (tdestroy);
++# endif
++
+ /* Flags used by tsearch.c. */
+ # define GNULIB_defined_tsearch (@REPLACE_TSEARCH@ || !@HAVE_TSEARCH@)
+ # define GNULIB_defined_twalk (@REPLACE_TWALK@ || !@HAVE_TWALK@)
++# define GNULIB_defined_tdestroy (@REPLACE_TDESTROY@ || !@HAVE_TDESTROY@)
+
+ #elif defined GNULIB_POSIXCHECK
+ # undef tsearch
+@@ -277,6 +310,11 @@ _GL_WARN_ON_USE (tdelete, "tdelete is un
+ _GL_WARN_ON_USE (twalk, "twalk is unportable - "
+ "use gnulib module tsearch for portability");
+ # endif
++# undef tdestroy
++# if HAVE_RAW_DECL_TDESTROY
++_GL_WARN_ON_USE (tdestroy, "tdestroy is unportable - "
++ "use gnulib module tsearch for portability");
++# endif
+ #endif
+
+
+--- a/lib/tsearch.c
++++ b/lib/tsearch.c
+@@ -98,12 +98,14 @@
+
+ typedef int (*__compar_fn_t) (const void *, const void *);
+ typedef void (*__action_fn_t) (const void *, VISIT, int);
++typedef void (*__free_fn_t) (void *);
+
+ #ifndef weak_alias
+ # define __tsearch tsearch
+ # define __tfind tfind
+ # define __tdelete tdelete
+ # define __twalk twalk
++# define __tdestroy tdestroy
+ #endif
+
+ #ifndef internal_function
+@@ -656,7 +658,7 @@ weak_alias (__twalk, twalk)
+ #endif /* GNULIB_defined_twalk */
+
+
+-#ifdef _LIBC
++#if defined(_LIBC) || GNULIB_defined_tdestroy
+
+ /* The standardized functions miss an important functionality: the
+ tree cannot be removed easily. We provide a function to do this. */
+@@ -683,6 +685,8 @@ __tdestroy (void *vroot, __free_fn_t fre
+ if (root != NULL)
+ tdestroy_recurse (root, freefct);
+ }
++#ifdef weak_alias
+ weak_alias (__tdestroy, tdestroy)
++#endif
+
+-#endif /* _LIBC */
++#endif /* defined(_LIBC) || GNULIB_defined_tdestroy */
+--- a/m4/search_h.m4
++++ b/m4/search_h.m4
+@@ -39,7 +39,7 @@ AC_DEFUN_ONCE([gl_SEARCH_H],
+ dnl Check for declarations of anything we want to poison if the
+ dnl corresponding gnulib module is not in use.
+ gl_WARN_ON_USE_PREPARE([[#include <search.h>
+- ]], [tdelete tfind tsearch twalk])
++ ]], [tdelete tfind tsearch twalk tdestroy])
+
+ AC_REQUIRE([AC_C_RESTRICT])
+ ])
+@@ -75,8 +75,10 @@ AC_DEFUN([gl_SEARCH_H_DEFAULTS],
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_MDA_LFIND], [1])
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_MDA_LSEARCH], [1])
+ dnl Assume proper GNU behavior unless another module says otherwise.
+- HAVE_TSEARCH=1; AC_SUBST([HAVE_TSEARCH])
+- HAVE_TWALK=1; AC_SUBST([HAVE_TWALK])
+- REPLACE_TSEARCH=0; AC_SUBST([REPLACE_TSEARCH])
+- REPLACE_TWALK=0; AC_SUBST([REPLACE_TWALK])
++ HAVE_TSEARCH=1; AC_SUBST([HAVE_TSEARCH])
++ HAVE_TWALK=1; AC_SUBST([HAVE_TWALK])
++ HAVE_TDESTROY=1; AC_SUBST([HAVE_TDESTROY])
++ REPLACE_TSEARCH=0; AC_SUBST([REPLACE_TSEARCH])
++ REPLACE_TWALK=0; AC_SUBST([REPLACE_TWALK])
++ REPLACE_TDESTROY=0; AC_SUBST([REPLACE_TDESTROY])
+ ])
+--- a/m4/tsearch.m4
++++ b/m4/tsearch.m4
+@@ -9,6 +9,7 @@ AC_DEFUN([gl_FUNC_TSEARCH],
+ AC_REQUIRE([gl_SEARCH_H_DEFAULTS])
+ gl_CHECK_FUNCS_ANDROID([tsearch], [[#include <search.h>]])
+ gl_CHECK_FUNCS_ANDROID([twalk], [[#include <search.h>]])
++ gl_CHECK_FUNCS_ANDROID([tdestroy], [[#include <search.h>]])
+ if test $ac_cv_func_tsearch = yes; then
+ dnl On OpenBSD 4.0, the return value of tdelete() is incorrect.
+ AC_REQUIRE([AC_PROG_CC])
+@@ -50,6 +51,7 @@ main ()
+ *no)
+ REPLACE_TSEARCH=1
+ REPLACE_TWALK=1
++ REPLACE_TDESTROY=1
+ ;;
+ esac
+ else
+@@ -64,6 +66,12 @@ main ()
+ future*) REPLACE_TWALK=1 ;;
+ esac
+ fi
++ if test $ac_cv_func_tdestroy != yes; then
++ HAVE_TDESTROY=0
++ case "$gl_cv_onwards_func_tdestroy" in
++ future*) REPLACE_TDESTROY=1 ;;
++ esac
++ fi
+ ])
+
+ # Prerequisites of lib/tsearch.c.
+--- a/modules/search
++++ b/modules/search
+@@ -37,8 +37,10 @@ search.h: search.in.h $(top_builddir)/co
+ -e 's/@''GNULIB_MDA_LSEARCH''@/$(GNULIB_MDA_LSEARCH)/g' \
+ -e 's|@''HAVE_TSEARCH''@|$(HAVE_TSEARCH)|g' \
+ -e 's|@''HAVE_TWALK''@|$(HAVE_TWALK)|g' \
++ -e 's|@''HAVE_TDESTROY''@|$(HAVE_TDESTROY)|g' \
+ -e 's|@''REPLACE_TSEARCH''@|$(REPLACE_TSEARCH)|g' \
+ -e 's|@''REPLACE_TWALK''@|$(REPLACE_TWALK)|g' \
++ -e 's|@''REPLACE_TDESTROY''@|$(REPLACE_TDESTROY)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+--- a/modules/tsearch
++++ b/modules/tsearch
+@@ -11,7 +11,12 @@ search
+ configure.ac:
+ gl_FUNC_TSEARCH
+ gl_CONDITIONAL([GL_COND_OBJ_TSEARCH],
+- [test $HAVE_TSEARCH = 0 || test $HAVE_TWALK = 0 || test $REPLACE_TSEARCH = 1 || test $REPLACE_TWALK = 1])
++ [test $HAVE_TSEARCH = 0 ||
++ test $HAVE_TWALK = 0 ||
++ test $HAVE_TDESTROY = 0 ||
++ test $REPLACE_TSEARCH = 1 ||
++ test $REPLACE_TWALK = 1 ||
++ test $REPLACE_TDESTROY = 1])
+ AM_COND_IF([GL_COND_OBJ_TSEARCH], [
+ gl_PREREQ_TSEARCH
+ ])
diff --git a/tools/gnulib/patches/160-flag-reallocarray.patch b/tools/gnulib/patches/160-flag-reallocarray.patch
new file mode 100644
index 0000000..8ffe273
--- /dev/null
+++ b/tools/gnulib/patches/160-flag-reallocarray.patch
@@ -0,0 +1,115 @@
+--- a/lib/ialloc.h
++++ b/lib/ialloc.h
+@@ -106,6 +106,8 @@ icalloc (idx_t n, idx_t s)
+ return calloc (n, s);
+ }
+
++#if GNULIB_REALLOCARRAY
++
+ /* ireallocarray (ptr, num, size) is like reallocarray (ptr, num, size).
+ It returns a non-NULL pointer to num * size bytes of memory.
+ Upon failure, it returns NULL with errno set. */
+@@ -131,6 +133,8 @@ ireallocarray (void *p, idx_t n, idx_t s
+ return _gl_alloc_nomem ();
+ }
+
++#endif /* GNULIB_REALLOCARRAY */
++
+ #ifdef __cplusplus
+ }
+ #endif
+--- a/lib/xmalloc.c
++++ b/lib/xmalloc.c
+@@ -51,12 +51,16 @@ ximalloc (idx_t s)
+ return nonnull (imalloc (s));
+ }
+
++#if GNULIB_REALLOCARRAY
++
+ char *
+ xcharalloc (size_t n)
+ {
+ return XNMALLOC (n, char);
+ }
+
++#endif /* GNULIB_REALLOCARRAY */
++
+ /* Change the size of an allocated block of memory P to S bytes,
+ with error checking. */
+
+@@ -75,6 +79,8 @@ xirealloc (void *p, idx_t s)
+ return nonnull (irealloc (p, s));
+ }
+
++#if GNULIB_REALLOCARRAY
++
+ /* Change the size of an allocated block of memory P to an array of N
+ objects each of S bytes, with error checking. */
+
+@@ -205,6 +211,8 @@ x2nrealloc (void *p, size_t *pn, size_t
+ return p;
+ }
+
++#endif /* GNULIB_REALLOCARRAY */
++
+ /* Grow PA, which points to an array of *PN items, and return the
+ location of the reallocated array, updating *PN to reflect its
+ new size. The new array will contain at least N_INCR_MIN more
+--- a/lib/xalloc.h
++++ b/lib/xalloc.h
+@@ -129,6 +129,7 @@ char *xstrdup (char const *str)
+ # define XCALLOC(n, t) \
+ ((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t))))
+
++# if GNULIB_REALLOCARRAY
+
+ /* Allocate an array of N objects, each with S bytes of memory,
+ dynamically, with error checking. S must be nonzero. */
+@@ -156,6 +157,8 @@ char *xcharalloc (size_t n)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_DEALLOC_FREE
+ _GL_ATTRIBUTE_ALLOC_SIZE ((1)) _GL_ATTRIBUTE_RETURNS_NONNULL;
+
++# endif /* GNULIB_REALLOCARRAY */
++
+ #endif /* GNULIB_XALLOC */
+
+
+--- a/lib/safe-alloc.h
++++ b/lib/safe-alloc.h
+@@ -36,6 +36,8 @@ _GL_INLINE_HEADER_BEGIN
+ # define SAFE_ALLOC_INLINE _GL_INLINE
+ #endif
+
++#if GNULIB_REALLOCARRAY
++
+ /* Don't call these directly - use the macros below. */
+ SAFE_ALLOC_INLINE void *
+ safe_alloc_realloc_n (void *ptr, size_t count, size_t size)
+@@ -51,6 +53,9 @@ safe_alloc_realloc_n (void *ptr, size_t
+ #endif
+ return ptr;
+ }
++
++#endif /* GNULIB_REALLOCARRAY */
++
+ _GL_ATTRIBUTE_NODISCARD SAFE_ALLOC_INLINE int
+ safe_alloc_check (void *ptr)
+ {
+@@ -84,6 +89,8 @@ safe_alloc_check (void *ptr)
+ #define ALLOC_N(ptr, count) \
+ safe_alloc_check ((ptr) = calloc (count, sizeof *(ptr)))
+
++#if GNULIB_REALLOCARRAY
++
+ /**
+ * ALLOC_N_UNINITIALIZED:
+ * @ptr: pointer to allocated memory
+@@ -112,6 +119,8 @@ safe_alloc_check (void *ptr)
+ #define REALLOC_N(ptr, count) \
+ safe_alloc_check ((ptr) = safe_alloc_realloc_n (ptr, count, sizeof *(ptr)))
+
++#endif /* GNULIB_REALLOCARRAY */
++
+ /**
+ * FREE:
+ * @ptr: pointer holding address to be freed
diff --git a/tools/gnulib/patches/200-force-disable-after-configure.patch b/tools/gnulib/patches/200-force-disable-after-configure.patch
new file mode 100644
index 0000000..55335b2
--- /dev/null
+++ b/tools/gnulib/patches/200-force-disable-after-configure.patch
@@ -0,0 +1,56 @@
+--- a/lib/fcntl.c
++++ b/lib/fcntl.c
+@@ -198,6 +198,8 @@ static int klibc_fcntl (int fd, int acti
+ FD_CLOEXEC is portable, but other flags may be present); otherwise
+ return -1 and set errno. */
+
++#if (GNULIB_defined_fcntl || GNULIB_defined_rpl_fcntl)
++
+ int
+ fcntl (int fd, int action, /* arg */...)
+ #undef fcntl
+@@ -443,6 +445,8 @@ fcntl (int fd, int action, /* arg */...)
+ return result;
+ }
+
++#endif /* (GNULIB_defined_fcntl || GNULIB_defined_rpl_fcntl) */
++
+ static int
+ rpl_fcntl_DUPFD (int fd, int target)
+ {
+--- a/lib/stdlib.in.h
++++ b/lib/stdlib.in.h
+@@ -1447,10 +1447,16 @@ _GL_FUNCDECL_RPL (reallocarray, void *,
+ (void *ptr, size_t nmemb, size_t size));
+ _GL_CXXALIAS_RPL (reallocarray, void *,
+ (void *ptr, size_t nmemb, size_t size));
++# if !GNULIB_defined_rpl_reallocarray
++# define GNULIB_defined_rpl_reallocarray 1
++# endif
+ # else
+ # if ! @HAVE_REALLOCARRAY@
+ _GL_FUNCDECL_SYS (reallocarray, void *,
+ (void *ptr, size_t nmemb, size_t size));
++# if !GNULIB_defined_reallocarray
++# define GNULIB_defined_reallocarray 1
++# endif
+ # endif
+ _GL_CXXALIAS_SYS (reallocarray, void *,
+ (void *ptr, size_t nmemb, size_t size));
+--- a/lib/reallocarray.c
++++ b/lib/reallocarray.c
+@@ -23,6 +23,8 @@
+ #include <stdlib.h>
+ #include <errno.h>
+
++#if (GNULIB_defined_reallocarray || GNULIB_defined_rpl_reallocarray)
++
+ void *
+ reallocarray (void *ptr, size_t nmemb, size_t size)
+ {
+@@ -36,3 +38,5 @@ reallocarray (void *ptr, size_t nmemb, s
+ /* Rely on the semantics of GNU realloc. */
+ return realloc (ptr, nbytes);
+ }
++
++#endif /* (GNULIB_defined_reallocarray || GNULIB_defined_rpl_reallocarray) */
diff --git a/tools/gnulib/patches/320-modules-fallocate-posix.patch b/tools/gnulib/patches/320-modules-fallocate-posix.patch
new file mode 100644
index 0000000..e30a717
--- /dev/null
+++ b/tools/gnulib/patches/320-modules-fallocate-posix.patch
@@ -0,0 +1,326 @@
+--- /dev/null
++++ b/modules/fallocate-posix
+@@ -0,0 +1,43 @@
++Description:
++posix_fallocate function that is glibc compatible.
++
++Files:
++lib/posix_fallocate.c
++m4/fcntl_h.m4
++m4/posix_fallocate.m4
++
++Depends-on:
++errno [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++fcntl [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++fstat [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++ftruncate [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++pread [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++pwrite [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++stdint [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++sys_stat [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++unistd [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1]
++fcntl-h
++
++configure.ac:
++gl_FUNC_POSIX_FALLOCATE
++gl_CONDITIONAL([GL_COND_OBJ_POSIX_FALLOCATE],
++ [test $HAVE_FALLOCATE_POSIX = 0 || test $REPLACE_FALLOCATE_POSIX = 1])
++AM_COND_IF([GL_COND_OBJ_POSIX_FALLOCATE], [
++ gl_PREREQ_POSIX_FALLOCATE
++])
++gl_MODULE_INDICATOR([fallocate-posix])
++gl_FCNTL_MODULE_INDICATOR([fallocate-posix])
++
++Makefile.am:
++if GL_COND_OBJ_POSIX_FALLOCATE
++lib_SOURCES += posix_fallocate.c
++endif
++
++Include:
++<fcntl.h>
++
++License:
++LGPLv2+
++
++Maintainer:
++all
+--- /dev/null
++++ b/m4/posix_fallocate.m4
+@@ -0,0 +1,20 @@
++# posix_fallocate.m4 serial 1
++dnl Copyright (C) 2024 Free Software Foundation, Inc.
++dnl This file is free software; the Free Software Foundation
++dnl gives unlimited permission to copy and/or distribute it,
++dnl with or without modifications, as long as this notice is preserved.
++
++AC_DEFUN([gl_FUNC_POSIX_FALLOCATE],
++[
++ AC_REQUIRE([gl_FCNTL_H_DEFAULTS])
++ gl_CHECK_FUNCS_ANDROID([posix_fallocate], [[#include <fcntl.h>]])
++ if test "$ac_cv_func_posix_fallocate" = no; then
++ HAVE_FALLOCATE_POSIX=0
++ case "$gl_cv_onwards_func_posix_fallocate" in
++ future*) REPLACE_FALLOCATE_POSIX=1 ;;
++ esac
++ fi
++])
++
++# Prerequisites of lib/posix_fallocate.c.
++AC_DEFUN([gl_PREREQ_POSIX_FALLOCATE], [:])
+--- a/m4/fcntl_h.m4
++++ b/m4/fcntl_h.m4
+@@ -23,7 +23,7 @@ AC_DEFUN_ONCE([gl_FCNTL_H],
+ dnl corresponding gnulib module is not in use, if it is not common
+ dnl enough to be declared everywhere.
+ gl_WARN_ON_USE_PREPARE([[#include <fcntl.h>
+- ]], [fcntl openat])
++ ]], [fcntl openat posix_fallocate])
+ ])
+
+ # gl_FCNTL_MODULE_INDICATOR([modulename])
+@@ -50,6 +50,7 @@ AC_DEFUN([gl_FCNTL_H_REQUIRE_DEFAULTS],
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_NONBLOCKING])
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_OPEN])
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_OPENAT])
++ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_FALLOCATE_POSIX])
+ dnl Support Microsoft deprecated alias function names by default.
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_MDA_CREAT], [1])
+ gl_MODULE_INDICATOR_INIT_VARIABLE([GNULIB_MDA_OPEN], [1])
+@@ -61,10 +62,12 @@ AC_DEFUN([gl_FCNTL_H_REQUIRE_DEFAULTS],
+ AC_DEFUN([gl_FCNTL_H_DEFAULTS],
+ [
+ dnl Assume proper GNU behavior unless another module says otherwise.
+- HAVE_FCNTL=1; AC_SUBST([HAVE_FCNTL])
+- HAVE_OPENAT=1; AC_SUBST([HAVE_OPENAT])
+- REPLACE_CREAT=0; AC_SUBST([REPLACE_CREAT])
+- REPLACE_FCNTL=0; AC_SUBST([REPLACE_FCNTL])
+- REPLACE_OPEN=0; AC_SUBST([REPLACE_OPEN])
+- REPLACE_OPENAT=0; AC_SUBST([REPLACE_OPENAT])
++ HAVE_FCNTL=1; AC_SUBST([HAVE_FCNTL])
++ HAVE_OPENAT=1; AC_SUBST([HAVE_OPENAT])
++ HAVE_FALLOCATE_POSIX=1; AC_SUBST([HAVE_FALLOCATE_POSIX])
++ REPLACE_CREAT=0; AC_SUBST([REPLACE_CREAT])
++ REPLACE_FCNTL=0; AC_SUBST([REPLACE_FCNTL])
++ REPLACE_OPEN=0; AC_SUBST([REPLACE_OPEN])
++ REPLACE_OPENAT=0; AC_SUBST([REPLACE_OPENAT])
++ REPLACE_FALLOCATE_POSIX=0; AC_SUBST([REPLACE_FALLOCATE_POSIX])
+ ])
+--- a/modules/fcntl-h
++++ b/modules/fcntl-h
+@@ -40,14 +40,17 @@ fcntl.h: fcntl.in.h $(top_builddir)/conf
+ -e 's/@''GNULIB_NONBLOCKING''@/$(GNULIB_NONBLOCKING)/g' \
+ -e 's/@''GNULIB_OPEN''@/$(GNULIB_OPEN)/g' \
+ -e 's/@''GNULIB_OPENAT''@/$(GNULIB_OPENAT)/g' \
++ -e 's/@''GNULIB_FALLOCATE_POSIX''@/$(GNULIB_FALLOCATE_POSIX)/g' \
+ -e 's/@''GNULIB_MDA_CREAT''@/$(GNULIB_MDA_CREAT)/g' \
+ -e 's/@''GNULIB_MDA_OPEN''@/$(GNULIB_MDA_OPEN)/g' \
+ -e 's|@''HAVE_FCNTL''@|$(HAVE_FCNTL)|g' \
+ -e 's|@''HAVE_OPENAT''@|$(HAVE_OPENAT)|g' \
++ -e 's|@''HAVE_FALLOCATE_POSIX''@|$(HAVE_FALLOCATE_POSIX)|g' \
+ -e 's|@''REPLACE_CREAT''@|$(REPLACE_CREAT)|g' \
+ -e 's|@''REPLACE_FCNTL''@|$(REPLACE_FCNTL)|g' \
+ -e 's|@''REPLACE_OPEN''@|$(REPLACE_OPEN)|g' \
+ -e 's|@''REPLACE_OPENAT''@|$(REPLACE_OPENAT)|g' \
++ -e 's|@''REPLACE_FALLOCATE_POSIX''@|$(REPLACE_FALLOCATE_POSIX)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+--- a/lib/fcntl.in.h
++++ b/lib/fcntl.in.h
+@@ -238,6 +238,33 @@ _GL_WARN_ON_USE (openat, "openat is not
+ # endif
+ #endif
+
++#if @GNULIB_FALLOCATE_POSIX@
++# if @REPLACE_FALLOCATE_POSIX@
++# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
++# undef posix_fallocate
++# define posix_fallocate rpl_posix_fallocate
++# endif
++_GL_FUNCDECL_RPL (posix_fallocate, int,
++ (int fd, off_t offset, off_t len));
++_GL_CXXALIAS_RPL (posix_fallocate, int,
++ (int fd, off_t offset, off_t len));
++# else
++# if !@HAVE_FALLOCATE_POSIX@
++_GL_FUNCDECL_SYS (posix_fallocate, int,
++ (int fd, off_t offset, off_t len));
++# endif
++_GL_CXXALIAS_SYS (posix_fallocate, int,
++ (int fd, off_t offset, off_t len));
++# endif
++_GL_CXXALIASWARN (posix_fallocate);
++#elif defined GNULIB_POSIXCHECK
++# undef posix_fallocate
++# if HAVE_RAW_DECL_POSIX_FALLOCATE
++_GL_WARN_ON_USE (posix_fallocate, "posix_fallocate is not portable - "
++ "use gnulib module fallocate-posix for portability");
++# endif
++#endif
++
+
+ /* Fix up the FD_* macros, only known to be missing on mingw. */
+
+--- /dev/null
++++ b/lib/posix_fallocate.c
+@@ -0,0 +1,150 @@
++/* posix_fallocate function that is glibc compatible.
++
++ Copyright (C) 2024 Free Software Foundation, Inc.
++
++ This file is free software: you can redistribute it and/or modify
++ it under the terms of the GNU Lesser General Public License as
++ published by the Free Software Foundation; either version 2.1 of the
++ License, or (at your option) any later version.
++
++ This file 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 Lesser General Public License for more details.
++
++ You should have received a copy of the GNU Lesser General Public License
++ along with this program. If not, see <https://www.gnu.org/licenses/>. */
++
++#include <config.h>
++
++#include <errno.h>
++#include <fcntl.h>
++#include <unistd.h>
++#include <stdint.h>
++#include <sys/fcntl.h>
++#include <sys/stat.h>
++
++#ifdef __APPLE__
++# include <sys/param.h>
++# include <sys/mount.h>
++#else
++# include <sys/statfs.h>
++#endif
++
++/* Reserve storage for the data of the file associated with FD. This
++ emulation is far from perfect, but the kernel cannot do not much
++ better for network file systems, either. */
++
++int
++posix_fallocate (int fd, off_t offset, off_t len)
++{
++ int ret;
++ struct stat st;
++
++ if (fd < 0 || offset < 0 || len < 0)
++ return EINVAL;
++
++ /* Perform overflow check. The outer cast relies on a GCC
++ extension. */
++ if ((off_t) ((uint64_t) offset + (uint64_t) len) < 0)
++ return EFBIG;
++
++ /* pwrite below will not do the right thing in O_APPEND mode. */
++ {
++ int flags = fcntl (fd, F_GETFL, 0);
++ if (flags < 0 || (flags & O_APPEND) != 0)
++ return EBADF;
++ }
++
++ /* We have to make sure that this is really a regular file. */
++ if (fstat (fd, &st) != 0)
++ return EBADF;
++ if (S_ISFIFO (st.st_mode))
++ return ESPIPE;
++ if (! S_ISREG (st.st_mode))
++ return ENODEV;
++
++ if (len == 0)
++ {
++ /* This is racy, but there is no good way to satisfy a
++ zero-length allocation request. */
++ if (st.st_size < offset)
++ {
++ ret = ftruncate (fd, offset);
++
++ if (ret != 0)
++ ret = errno;
++ return ret;
++ }
++ return ret;
++ }
++
++#ifdef __APPLE__
++ fstore_t sto = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, offset + len, 0};
++ /* allocate continuous */
++ ret = fcntl (fd, F_PREALLOCATE, &sto);
++ if (ret < 0)
++ {
++ /* allocate non-continuous */
++ sto.fst_flags = F_ALLOCATEALL;
++ ret = fcntl (fd, F_PREALLOCATE, &sto);
++ if (ret < 0)
++ {
++ return ret;
++ }
++ }
++ ret = ftruncate(fd, offset + len);
++#else
++
++ /* Minimize data transfer for network file systems, by issuing
++ single-byte write requests spaced by the file system block size.
++ (Most local file systems have fallocate support, so this fallback
++ code is not used there.) */
++
++ unsigned increment;
++ {
++ struct statfs f;
++
++ if (fstatfs (fd, &f) != 0)
++ return errno;
++ if (f.f_bsize == 0)
++ increment = 512;
++ else if (f.f_bsize < 4096)
++ increment = f.f_bsize;
++ else
++ /* NFS does not propagate the block size of the underlying
++ storage and may report a much larger value which would still
++ leave holes after the loop below, so we cap the increment at
++ 4096. */
++ increment = 4096;
++ }
++
++ /* Write a null byte to every block. This is racy; we currently
++ lack a better option. Compare-and-swap against a file mapping
++ might additional local races, but requires interposition of a
++ signal handler to catch SIGBUS. */
++ for (offset += (len - 1) % increment; len > 0; offset += increment)
++ {
++ len -= increment;
++
++ if (offset < st.st_size)
++ {
++ unsigned char c;
++ ssize_t rsize = pread (fd, &c, 1, offset);
++
++ if (rsize < 0)
++ return errno;
++ /* If there is a non-zero byte, the block must have been
++ allocated already. */
++ else if (rsize == 1 && c != 0)
++ continue;
++ }
++
++ if (pwrite (fd, "", 1, offset) != 1)
++ return errno;
++ }
++
++#endif /* __APPLE__ */
++
++ return ret;
++}
+--- a/MODULES.html.sh
++++ b/MODULES.html.sh
+@@ -2552,6 +2552,7 @@ func_all_modules ()
+ func_module execve
+ func_module execvp
+ func_module execvpe
++ func_module fallocate-posix
+ func_module fchdir
+ func_module fclose
+ func_module fcntl-h
diff --git a/tools/include/asm/bitsperlong.h b/tools/include/asm/bitsperlong.h
new file mode 100644
index 0000000..75f320f
--- /dev/null
+++ b/tools/include/asm/bitsperlong.h
@@ -0,0 +1,27 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef __ASM_GENERIC_BITS_PER_LONG
+#define __ASM_GENERIC_BITS_PER_LONG
+
+#ifndef __BITS_PER_LONG
+/*
+ * In order to keep safe and avoid regression, only unify uapi
+ * bitsperlong.h for some archs which are using newer toolchains
+ * that have the definitions of __CHAR_BIT__ and __SIZEOF_LONG__.
+ * See the following link for more info:
+ * https://lore.kernel.org/linux-arch/b9624545-2c80-49a1-ac3c-39264a591f7b@app.fastmail.com/
+ */
+#if defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__)
+#define __BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
+#else
+/*
+ * There seems to be no way of detecting this automatically from user
+ * space, so 64 bit architectures should override this in their
+ * bitsperlong.h. In particular, an architecture that supports
+ * both 32 and 64 bit user space must not rely on CONFIG_64BIT
+ * to decide it, but rather check a compiler provided macro.
+ */
+#define __BITS_PER_LONG 32
+#endif
+#endif
+
+#endif /* __ASM_GENERIC_BITS_PER_LONG */
diff --git a/tools/include/asm/byteorder.h b/tools/include/asm/byteorder.h
new file mode 100644
index 0000000..8e7d779
--- /dev/null
+++ b/tools/include/asm/byteorder.h
@@ -0,0 +1,12 @@
+#ifndef __ASM_BYTEORDER_H
+#define __ASM_BYTEORDER_H
+
+#include <endian.h>
+
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#include <linux/byteorder/little_endian.h>
+#else
+#include <linux/byteorder/big_endian.h>
+#endif
+
+#endif
diff --git a/tools/include/asm/errno-base.h b/tools/include/asm/errno-base.h
new file mode 100644
index 0000000..9653140
--- /dev/null
+++ b/tools/include/asm/errno-base.h
@@ -0,0 +1,40 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _ASM_GENERIC_ERRNO_BASE_H
+#define _ASM_GENERIC_ERRNO_BASE_H
+
+#define EPERM 1 /* Operation not permitted */
+#define ENOENT 2 /* No such file or directory */
+#define ESRCH 3 /* No such process */
+#define EINTR 4 /* Interrupted system call */
+#define EIO 5 /* I/O error */
+#define ENXIO 6 /* No such device or address */
+#define E2BIG 7 /* Argument list too long */
+#define ENOEXEC 8 /* Exec format error */
+#define EBADF 9 /* Bad file number */
+#define ECHILD 10 /* No child processes */
+#define EAGAIN 11 /* Try again */
+#define ENOMEM 12 /* Out of memory */
+#define EACCES 13 /* Permission denied */
+#define EFAULT 14 /* Bad address */
+#define ENOTBLK 15 /* Block device required */
+#define EBUSY 16 /* Device or resource busy */
+#define EEXIST 17 /* File exists */
+#define EXDEV 18 /* Cross-device link */
+#define ENODEV 19 /* No such device */
+#define ENOTDIR 20 /* Not a directory */
+#define EISDIR 21 /* Is a directory */
+#define EINVAL 22 /* Invalid argument */
+#define ENFILE 23 /* File table overflow */
+#define EMFILE 24 /* Too many open files */
+#define ENOTTY 25 /* Not a typewriter */
+#define ETXTBSY 26 /* Text file busy */
+#define EFBIG 27 /* File too large */
+#define ENOSPC 28 /* No space left on device */
+#define ESPIPE 29 /* Illegal seek */
+#define EROFS 30 /* Read-only file system */
+#define EMLINK 31 /* Too many links */
+#define EPIPE 32 /* Broken pipe */
+#define EDOM 33 /* Math argument out of domain of func */
+#define ERANGE 34 /* Math result not representable */
+
+#endif
diff --git a/tools/include/asm/errno.h b/tools/include/asm/errno.h
new file mode 100644
index 0000000..a96d525
--- /dev/null
+++ b/tools/include/asm/errno.h
@@ -0,0 +1,123 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _ASM_GENERIC_ERRNO_H
+#define _ASM_GENERIC_ERRNO_H
+
+#include <asm/errno-base.h>
+
+#define EDEADLK 35 /* Resource deadlock would occur */
+#define ENAMETOOLONG 36 /* File name too long */
+#define ENOLCK 37 /* No record locks available */
+
+/*
+ * This error code is special: arch syscall entry code will return
+ * -ENOSYS if users try to call a syscall that doesn't exist. To keep
+ * failures of syscalls that really do exist distinguishable from
+ * failures due to attempts to use a nonexistent syscall, syscall
+ * implementations should refrain from returning -ENOSYS.
+ */
+#define ENOSYS 38 /* Invalid system call number */
+
+#define ENOTEMPTY 39 /* Directory not empty */
+#define ELOOP 40 /* Too many symbolic links encountered */
+#define EWOULDBLOCK EAGAIN /* Operation would block */
+#define ENOMSG 42 /* No message of desired type */
+#define EIDRM 43 /* Identifier removed */
+#define ECHRNG 44 /* Channel number out of range */
+#define EL2NSYNC 45 /* Level 2 not synchronized */
+#define EL3HLT 46 /* Level 3 halted */
+#define EL3RST 47 /* Level 3 reset */
+#define ELNRNG 48 /* Link number out of range */
+#define EUNATCH 49 /* Protocol driver not attached */
+#define ENOCSI 50 /* No CSI structure available */
+#define EL2HLT 51 /* Level 2 halted */
+#define EBADE 52 /* Invalid exchange */
+#define EBADR 53 /* Invalid request descriptor */
+#define EXFULL 54 /* Exchange full */
+#define ENOANO 55 /* No anode */
+#define EBADRQC 56 /* Invalid request code */
+#define EBADSLT 57 /* Invalid slot */
+
+#define EDEADLOCK EDEADLK
+
+#define EBFONT 59 /* Bad font file format */
+#define ENOSTR 60 /* Device not a stream */
+#define ENODATA 61 /* No data available */
+#define ETIME 62 /* Timer expired */
+#define ENOSR 63 /* Out of streams resources */
+#define ENONET 64 /* Machine is not on the network */
+#define ENOPKG 65 /* Package not installed */
+#define EREMOTE 66 /* Object is remote */
+#define ENOLINK 67 /* Link has been severed */
+#define EADV 68 /* Advertise error */
+#define ESRMNT 69 /* Srmount error */
+#define ECOMM 70 /* Communication error on send */
+#define EPROTO 71 /* Protocol error */
+#define EMULTIHOP 72 /* Multihop attempted */
+#define EDOTDOT 73 /* RFS specific error */
+#define EBADMSG 74 /* Not a data message */
+#define EOVERFLOW 75 /* Value too large for defined data type */
+#define ENOTUNIQ 76 /* Name not unique on network */
+#define EBADFD 77 /* File descriptor in bad state */
+#define EREMCHG 78 /* Remote address changed */
+#define ELIBACC 79 /* Can not access a needed shared library */
+#define ELIBBAD 80 /* Accessing a corrupted shared library */
+#define ELIBSCN 81 /* .lib section in a.out corrupted */
+#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
+#define ELIBEXEC 83 /* Cannot exec a shared library directly */
+#define EILSEQ 84 /* Illegal byte sequence */
+#define ERESTART 85 /* Interrupted system call should be restarted */
+#define ESTRPIPE 86 /* Streams pipe error */
+#define EUSERS 87 /* Too many users */
+#define ENOTSOCK 88 /* Socket operation on non-socket */
+#define EDESTADDRREQ 89 /* Destination address required */
+#define EMSGSIZE 90 /* Message too long */
+#define EPROTOTYPE 91 /* Protocol wrong type for socket */
+#define ENOPROTOOPT 92 /* Protocol not available */
+#define EPROTONOSUPPORT 93 /* Protocol not supported */
+#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
+#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
+#define EPFNOSUPPORT 96 /* Protocol family not supported */
+#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
+#define EADDRINUSE 98 /* Address already in use */
+#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
+#define ENETDOWN 100 /* Network is down */
+#define ENETUNREACH 101 /* Network is unreachable */
+#define ENETRESET 102 /* Network dropped connection because of reset */
+#define ECONNABORTED 103 /* Software caused connection abort */
+#define ECONNRESET 104 /* Connection reset by peer */
+#define ENOBUFS 105 /* No buffer space available */
+#define EISCONN 106 /* Transport endpoint is already connected */
+#define ENOTCONN 107 /* Transport endpoint is not connected */
+#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
+#define ETOOMANYREFS 109 /* Too many references: cannot splice */
+#define ETIMEDOUT 110 /* Connection timed out */
+#define ECONNREFUSED 111 /* Connection refused */
+#define EHOSTDOWN 112 /* Host is down */
+#define EHOSTUNREACH 113 /* No route to host */
+#define EALREADY 114 /* Operation already in progress */
+#define EINPROGRESS 115 /* Operation now in progress */
+#define ESTALE 116 /* Stale file handle */
+#define EUCLEAN 117 /* Structure needs cleaning */
+#define ENOTNAM 118 /* Not a XENIX named type file */
+#define ENAVAIL 119 /* No XENIX semaphores available */
+#define EISNAM 120 /* Is a named type file */
+#define EREMOTEIO 121 /* Remote I/O error */
+#define EDQUOT 122 /* Quota exceeded */
+
+#define ENOMEDIUM 123 /* No medium found */
+#define EMEDIUMTYPE 124 /* Wrong medium type */
+#define ECANCELED 125 /* Operation Canceled */
+#define ENOKEY 126 /* Required key not available */
+#define EKEYEXPIRED 127 /* Key has expired */
+#define EKEYREVOKED 128 /* Key has been revoked */
+#define EKEYREJECTED 129 /* Key was rejected by service */
+
+/* for robust mutexes */
+#define EOWNERDEAD 130 /* Owner died */
+#define ENOTRECOVERABLE 131 /* State not recoverable */
+
+#define ERFKILL 132 /* Operation not possible due to RF-kill */
+
+#define EHWPOISON 133 /* Memory page has hardware error */
+
+#endif
diff --git a/tools/include/asm/posix_types.h b/tools/include/asm/posix_types.h
new file mode 100644
index 0000000..10f5e6e
--- /dev/null
+++ b/tools/include/asm/posix_types.h
@@ -0,0 +1,100 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef __ASM_GENERIC_POSIX_TYPES_H
+#define __ASM_GENERIC_POSIX_TYPES_H
+
+#include <asm/bitsperlong.h>
+
+/*
+ * This file is generally used by user-level software, so you need to
+ * be a little careful about namespace pollution etc.
+ *
+ * First the types that are often defined in different ways across
+ * architectures, so that you can override them.
+ */
+
+#ifndef __kernel_long_t
+typedef long __kernel_long_t;
+typedef unsigned long __kernel_ulong_t;
+#endif
+
+#ifndef __kernel_ino_t
+typedef __kernel_ulong_t __kernel_ino_t;
+#endif
+
+#ifndef __kernel_mode_t
+typedef unsigned int __kernel_mode_t;
+#endif
+
+#ifndef __kernel_pid_t
+typedef int __kernel_pid_t;
+#endif
+
+#ifndef __kernel_ipc_pid_t
+typedef int __kernel_ipc_pid_t;
+#endif
+
+#ifndef __kernel_uid_t
+typedef unsigned int __kernel_uid_t;
+typedef unsigned int __kernel_gid_t;
+#endif
+
+#ifndef __kernel_suseconds_t
+typedef __kernel_long_t __kernel_suseconds_t;
+#endif
+
+#ifndef __kernel_daddr_t
+typedef int __kernel_daddr_t;
+#endif
+
+#ifndef __kernel_uid32_t
+typedef unsigned int __kernel_uid32_t;
+typedef unsigned int __kernel_gid32_t;
+#endif
+
+#ifndef __kernel_old_uid_t
+typedef __kernel_uid_t __kernel_old_uid_t;
+typedef __kernel_gid_t __kernel_old_gid_t;
+#endif
+
+#ifndef __kernel_old_dev_t
+typedef unsigned int __kernel_old_dev_t;
+#endif
+
+/*
+ * Most 32 bit architectures use "unsigned int" size_t,
+ * and all 64 bit architectures use "unsigned long" size_t.
+ */
+#ifndef __kernel_size_t
+#if __BITS_PER_LONG != 64
+typedef unsigned int __kernel_size_t;
+typedef int __kernel_ssize_t;
+typedef int __kernel_ptrdiff_t;
+#else
+typedef __kernel_ulong_t __kernel_size_t;
+typedef __kernel_long_t __kernel_ssize_t;
+typedef __kernel_long_t __kernel_ptrdiff_t;
+#endif
+#endif
+
+#ifndef __kernel_fsid_t
+typedef struct {
+ int val[2];
+} __kernel_fsid_t;
+#endif
+
+/*
+ * anything below here should be completely generic
+ */
+typedef __kernel_long_t __kernel_off_t;
+typedef long long __kernel_loff_t;
+typedef __kernel_long_t __kernel_old_time_t;
+typedef __kernel_long_t __kernel_time_t;
+typedef long long __kernel_time64_t;
+typedef __kernel_long_t __kernel_clock_t;
+typedef int __kernel_timer_t;
+typedef int __kernel_clockid_t;
+typedef char * __kernel_caddr_t;
+typedef unsigned short __kernel_uid16_t;
+typedef unsigned short __kernel_gid16_t;
+
+#endif /* __ASM_GENERIC_POSIX_TYPES_H */
diff --git a/tools/include/asm/swab.h b/tools/include/asm/swab.h
new file mode 100644
index 0000000..f2da4e4
--- /dev/null
+++ b/tools/include/asm/swab.h
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _ASM_GENERIC_SWAB_H
+#define _ASM_GENERIC_SWAB_H
+
+#include <asm/bitsperlong.h>
+
+/*
+ * 32 bit architectures typically (but not always) want to
+ * set __SWAB_64_THRU_32__. In user space, this is only
+ * valid if the compiler supports 64 bit data types.
+ */
+
+#if __BITS_PER_LONG == 32
+#if defined(__GNUC__) && !defined(__STRICT_ANSI__) || defined(__KERNEL__)
+#define __SWAB_64_THRU_32__
+#endif
+#endif
+
+#endif /* _ASM_GENERIC_SWAB_H */
diff --git a/tools/include/asm/types.h b/tools/include/asm/types.h
new file mode 100644
index 0000000..5a12bbe
--- /dev/null
+++ b/tools/include/asm/types.h
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * asm-generic/int-ll64.h
+ *
+ * Integer declarations for architectures which use "long long"
+ * for 64-bit types.
+ */
+
+#ifndef _ASM_GENERIC_INT_LL64_H
+#define _ASM_GENERIC_INT_LL64_H
+
+typedef __signed__ char __s8;
+typedef unsigned char __u8;
+
+typedef __signed__ short __s16;
+typedef unsigned short __u16;
+
+typedef __signed__ int __s32;
+typedef unsigned int __u32;
+
+#ifdef __GNUC__
+__extension__ typedef __signed__ long long __s64;
+__extension__ typedef unsigned long long __u64;
+#else
+typedef __signed__ long long __s64;
+typedef unsigned long long __u64;
+#endif
+
+#endif /* _ASM_GENERIC_INT_LL64_H */
diff --git a/tools/include/byteswap.h b/tools/include/byteswap.h
new file mode 100644
index 0000000..015f097
--- /dev/null
+++ b/tools/include/byteswap.h
@@ -0,0 +1,5 @@
+#if defined(__linux__) || defined(__CYGWIN__)
+#include_next <byteswap.h>
+#else
+#include <endian.h>
+#endif
diff --git a/tools/include/elf.h b/tools/include/elf.h
new file mode 100644
index 0000000..4bc0e42
--- /dev/null
+++ b/tools/include/elf.h
@@ -0,0 +1,4327 @@
+/* This file defines standard ELF types, structures, and macros.
+ Copyright (C) 1995-2023 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+
+ The GNU C Library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ The GNU C Library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with the GNU C Library; if not, see
+ <https://www.gnu.org/licenses/>. */
+
+#ifndef _ELF_H
+#define _ELF_H 1
+
+/* Standard ELF types. */
+
+#include <stdint.h>
+
+/* Type for a 16-bit quantity. */
+typedef uint16_t Elf32_Half;
+typedef uint16_t Elf64_Half;
+
+/* Types for signed and unsigned 32-bit quantities. */
+typedef uint32_t Elf32_Word;
+typedef int32_t Elf32_Sword;
+typedef uint32_t Elf64_Word;
+typedef int32_t Elf64_Sword;
+
+/* Types for signed and unsigned 64-bit quantities. */
+typedef uint64_t Elf32_Xword;
+typedef int64_t Elf32_Sxword;
+typedef uint64_t Elf64_Xword;
+typedef int64_t Elf64_Sxword;
+
+/* Type of addresses. */
+typedef uint32_t Elf32_Addr;
+typedef uint64_t Elf64_Addr;
+
+/* Type of file offsets. */
+typedef uint32_t Elf32_Off;
+typedef uint64_t Elf64_Off;
+
+/* Type for section indices, which are 16-bit quantities. */
+typedef uint16_t Elf32_Section;
+typedef uint16_t Elf64_Section;
+
+/* Type for version symbol information. */
+typedef Elf32_Half Elf32_Versym;
+typedef Elf64_Half Elf64_Versym;
+
+
+/* The ELF file header. This appears at the start of every ELF file. */
+
+#define EI_NIDENT (16)
+
+typedef struct
+{
+ unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
+ Elf32_Half e_type; /* Object file type */
+ Elf32_Half e_machine; /* Architecture */
+ Elf32_Word e_version; /* Object file version */
+ Elf32_Addr e_entry; /* Entry point virtual address */
+ Elf32_Off e_phoff; /* Program header table file offset */
+ Elf32_Off e_shoff; /* Section header table file offset */
+ Elf32_Word e_flags; /* Processor-specific flags */
+ Elf32_Half e_ehsize; /* ELF header size in bytes */
+ Elf32_Half e_phentsize; /* Program header table entry size */
+ Elf32_Half e_phnum; /* Program header table entry count */
+ Elf32_Half e_shentsize; /* Section header table entry size */
+ Elf32_Half e_shnum; /* Section header table entry count */
+ Elf32_Half e_shstrndx; /* Section header string table index */
+} Elf32_Ehdr;
+
+typedef struct
+{
+ unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
+ Elf64_Half e_type; /* Object file type */
+ Elf64_Half e_machine; /* Architecture */
+ Elf64_Word e_version; /* Object file version */
+ Elf64_Addr e_entry; /* Entry point virtual address */
+ Elf64_Off e_phoff; /* Program header table file offset */
+ Elf64_Off e_shoff; /* Section header table file offset */
+ Elf64_Word e_flags; /* Processor-specific flags */
+ Elf64_Half e_ehsize; /* ELF header size in bytes */
+ Elf64_Half e_phentsize; /* Program header table entry size */
+ Elf64_Half e_phnum; /* Program header table entry count */
+ Elf64_Half e_shentsize; /* Section header table entry size */
+ Elf64_Half e_shnum; /* Section header table entry count */
+ Elf64_Half e_shstrndx; /* Section header string table index */
+} Elf64_Ehdr;
+
+/* Fields in the e_ident array. The EI_* macros are indices into the
+ array. The macros under each EI_* macro are the values the byte
+ may have. */
+
+#define EI_MAG0 0 /* File identification byte 0 index */
+#define ELFMAG0 0x7f /* Magic number byte 0 */
+
+#define EI_MAG1 1 /* File identification byte 1 index */
+#define ELFMAG1 'E' /* Magic number byte 1 */
+
+#define EI_MAG2 2 /* File identification byte 2 index */
+#define ELFMAG2 'L' /* Magic number byte 2 */
+
+#define EI_MAG3 3 /* File identification byte 3 index */
+#define ELFMAG3 'F' /* Magic number byte 3 */
+
+/* Conglomeration of the identification bytes, for easy testing as a word. */
+#define ELFMAG "\177ELF"
+#define SELFMAG 4
+
+#define EI_CLASS 4 /* File class byte index */
+#define ELFCLASSNONE 0 /* Invalid class */
+#define ELFCLASS32 1 /* 32-bit objects */
+#define ELFCLASS64 2 /* 64-bit objects */
+#define ELFCLASSNUM 3
+
+#define EI_DATA 5 /* Data encoding byte index */
+#define ELFDATANONE 0 /* Invalid data encoding */
+#define ELFDATA2LSB 1 /* 2's complement, little endian */
+#define ELFDATA2MSB 2 /* 2's complement, big endian */
+#define ELFDATANUM 3
+
+#define EI_VERSION 6 /* File version byte index */
+ /* Value must be EV_CURRENT */
+
+#define EI_OSABI 7 /* OS ABI identification */
+#define ELFOSABI_NONE 0 /* UNIX System V ABI */
+#define ELFOSABI_SYSV 0 /* Alias. */
+#define ELFOSABI_HPUX 1 /* HP-UX */
+#define ELFOSABI_NETBSD 2 /* NetBSD. */
+#define ELFOSABI_GNU 3 /* Object uses GNU ELF extensions. */
+#define ELFOSABI_LINUX ELFOSABI_GNU /* Compatibility alias. */
+#define ELFOSABI_SOLARIS 6 /* Sun Solaris. */
+#define ELFOSABI_AIX 7 /* IBM AIX. */
+#define ELFOSABI_IRIX 8 /* SGI Irix. */
+#define ELFOSABI_FREEBSD 9 /* FreeBSD. */
+#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX. */
+#define ELFOSABI_MODESTO 11 /* Novell Modesto. */
+#define ELFOSABI_OPENBSD 12 /* OpenBSD. */
+#define ELFOSABI_ARM_AEABI 64 /* ARM EABI */
+#define ELFOSABI_ARM 97 /* ARM */
+#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */
+
+#define EI_ABIVERSION 8 /* ABI version */
+
+#define EI_PAD 9 /* Byte index of padding bytes */
+
+/* Legal values for e_type (object file type). */
+
+#define ET_NONE 0 /* No file type */
+#define ET_REL 1 /* Relocatable file */
+#define ET_EXEC 2 /* Executable file */
+#define ET_DYN 3 /* Shared object file */
+#define ET_CORE 4 /* Core file */
+#define ET_NUM 5 /* Number of defined types */
+#define ET_LOOS 0xfe00 /* OS-specific range start */
+#define ET_HIOS 0xfeff /* OS-specific range end */
+#define ET_LOPROC 0xff00 /* Processor-specific range start */
+#define ET_HIPROC 0xffff /* Processor-specific range end */
+
+/* Legal values for e_machine (architecture). */
+
+#define EM_NONE 0 /* No machine */
+#define EM_M32 1 /* AT&T WE 32100 */
+#define EM_SPARC 2 /* SUN SPARC */
+#define EM_386 3 /* Intel 80386 */
+#define EM_68K 4 /* Motorola m68k family */
+#define EM_88K 5 /* Motorola m88k family */
+#define EM_IAMCU 6 /* Intel MCU */
+#define EM_860 7 /* Intel 80860 */
+#define EM_MIPS 8 /* MIPS R3000 big-endian */
+#define EM_S370 9 /* IBM System/370 */
+#define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */
+ /* reserved 11-14 */
+#define EM_PARISC 15 /* HPPA */
+ /* reserved 16 */
+#define EM_VPP500 17 /* Fujitsu VPP500 */
+#define EM_SPARC32PLUS 18 /* Sun's "v8plus" */
+#define EM_960 19 /* Intel 80960 */
+#define EM_PPC 20 /* PowerPC */
+#define EM_PPC64 21 /* PowerPC 64-bit */
+#define EM_S390 22 /* IBM S390 */
+#define EM_SPU 23 /* IBM SPU/SPC */
+ /* reserved 24-35 */
+#define EM_V800 36 /* NEC V800 series */
+#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_FAKE_ALPHA 41 /* Digital Alpha */
+#define EM_SH 42 /* Hitachi SH */
+#define EM_SPARCV9 43 /* SPARC v9 64-bit */
+#define EM_TRICORE 44 /* Siemens Tricore */
+#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 Merced */
+#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 Multimedia Accelerator */
+#define EM_PCP 55 /* Siemens PCP */
+#define EM_NCPU 56 /* Sony nCPU embeeded RISC */
+#define EM_NDR1 57 /* Denso NDR1 microprocessor */
+#define EM_STARCORE 58 /* Motorola Start*Core processor */
+#define EM_ME16 59 /* Toyota ME16 processor */
+#define EM_ST100 60 /* STMicroelectronic ST100 processor */
+#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam */
+#define EM_X86_64 62 /* AMD x86-64 architecture */
+#define EM_PDSP 63 /* Sony DSP Processor */
+#define EM_PDP10 64 /* Digital PDP-10 */
+#define EM_PDP11 65 /* Digital PDP-11 */
+#define EM_FX66 66 /* Siemens FX66 microcontroller */
+#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */
+#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */
+#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 emb.proc */
+#define EM_JAVELIN 77 /* Infineon Technologies 32-bit emb.proc */
+#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_COMPACT 93 /* ARC International ARCompact */
+#define EM_XTENSA 94 /* Tensilica Xtensa Architecture */
+#define EM_VIDEOCORE 95 /* Alphamosaic VideoCore */
+#define EM_TMM_GPP 96 /* Thompson Multimedia General Purpose Proc */
+#define EM_NS32K 97 /* National Semi. 32000 */
+#define EM_TPC 98 /* Tenor Network TPC */
+#define EM_SNP1K 99 /* Trebia SNP 1000 */
+#define EM_ST200 100 /* STMicroelectronics ST200 */
+#define EM_IP2K 101 /* Ubicom IP2xxx */
+#define EM_MAX 102 /* MAX processor */
+#define EM_CR 103 /* National Semi. CompactRISC */
+#define EM_F2MC16 104 /* Fujitsu F2MC16 */
+#define EM_MSP430 105 /* Texas Instruments msp430 */
+#define EM_BLACKFIN 106 /* Analog Devices Blackfin DSP */
+#define EM_SE_C33 107 /* Seiko Epson S1C33 family */
+#define EM_SEP 108 /* Sharp embedded microprocessor */
+#define EM_ARCA 109 /* Arca RISC */
+#define EM_UNICORE 110 /* PKU-Unity & MPRC Peking Uni. mc series */
+#define EM_EXCESS 111 /* eXcess configurable cpu */
+#define EM_DXP 112 /* Icera Semi. Deep Execution Processor */
+#define EM_ALTERA_NIOS2 113 /* Altera Nios II */
+#define EM_CRX 114 /* National Semi. CompactRISC CRX */
+#define EM_XGATE 115 /* Motorola XGATE */
+#define EM_C166 116 /* Infineon C16x/XC16x */
+#define EM_M16C 117 /* Renesas M16C */
+#define EM_DSPIC30F 118 /* Microchip Technology dsPIC30F */
+#define EM_CE 119 /* Freescale Communication Engine RISC */
+#define EM_M32C 120 /* Renesas M32C */
+ /* reserved 121-130 */
+#define EM_TSK3000 131 /* Altium TSK3000 */
+#define EM_RS08 132 /* Freescale RS08 */
+#define EM_SHARC 133 /* Analog Devices SHARC family */
+#define EM_ECOG2 134 /* Cyan Technology eCOG2 */
+#define EM_SCORE7 135 /* Sunplus S+core7 RISC */
+#define EM_DSP24 136 /* New Japan Radio (NJR) 24-bit DSP */
+#define EM_VIDEOCORE3 137 /* Broadcom VideoCore III */
+#define EM_LATTICEMICO32 138 /* RISC for Lattice FPGA */
+#define EM_SE_C17 139 /* Seiko Epson C17 */
+#define EM_TI_C6000 140 /* Texas Instruments TMS320C6000 DSP */
+#define EM_TI_C2000 141 /* Texas Instruments TMS320C2000 DSP */
+#define EM_TI_C5500 142 /* Texas Instruments TMS320C55x DSP */
+#define EM_TI_ARP32 143 /* Texas Instruments App. Specific RISC */
+#define EM_TI_PRU 144 /* Texas Instruments Prog. Realtime Unit */
+ /* reserved 145-159 */
+#define EM_MMDSP_PLUS 160 /* STMicroelectronics 64bit VLIW DSP */
+#define EM_CYPRESS_M8C 161 /* Cypress M8C */
+#define EM_R32C 162 /* Renesas R32C */
+#define EM_TRIMEDIA 163 /* NXP Semi. TriMedia */
+#define EM_QDSP6 164 /* QUALCOMM DSP6 */
+#define EM_8051 165 /* Intel 8051 and variants */
+#define EM_STXP7X 166 /* STMicroelectronics STxP7x */
+#define EM_NDS32 167 /* Andes Tech. compact code emb. RISC */
+#define EM_ECOG1X 168 /* Cyan Technology eCOG1X */
+#define EM_MAXQ30 169 /* Dallas Semi. MAXQ30 mc */
+#define EM_XIMO16 170 /* New Japan Radio (NJR) 16-bit DSP */
+#define EM_MANIK 171 /* M2000 Reconfigurable RISC */
+#define EM_CRAYNV2 172 /* Cray NV2 vector architecture */
+#define EM_RX 173 /* Renesas RX */
+#define EM_METAG 174 /* Imagination Tech. META */
+#define EM_MCST_ELBRUS 175 /* MCST Elbrus */
+#define EM_ECOG16 176 /* Cyan Technology eCOG16 */
+#define EM_CR16 177 /* National Semi. CompactRISC CR16 */
+#define EM_ETPU 178 /* Freescale Extended Time Processing Unit */
+#define EM_SLE9X 179 /* Infineon Tech. SLE9X */
+#define EM_L10M 180 /* Intel L10M */
+#define EM_K10M 181 /* Intel K10M */
+ /* reserved 182 */
+#define EM_AARCH64 183 /* ARM AARCH64 */
+ /* reserved 184 */
+#define EM_AVR32 185 /* Amtel 32-bit microprocessor */
+#define EM_STM8 186 /* STMicroelectronics STM8 */
+#define EM_TILE64 187 /* Tilera TILE64 */
+#define EM_TILEPRO 188 /* Tilera TILEPro */
+#define EM_MICROBLAZE 189 /* Xilinx MicroBlaze */
+#define EM_CUDA 190 /* NVIDIA CUDA */
+#define EM_TILEGX 191 /* Tilera TILE-Gx */
+#define EM_CLOUDSHIELD 192 /* CloudShield */
+#define EM_COREA_1ST 193 /* KIPO-KAIST Core-A 1st gen. */
+#define EM_COREA_2ND 194 /* KIPO-KAIST Core-A 2nd gen. */
+#define EM_ARCV2 195 /* Synopsys ARCv2 ISA. */
+#define EM_OPEN8 196 /* Open8 RISC */
+#define EM_RL78 197 /* Renesas RL78 */
+#define EM_VIDEOCORE5 198 /* Broadcom VideoCore V */
+#define EM_78KOR 199 /* Renesas 78KOR */
+#define EM_56800EX 200 /* Freescale 56800EX DSC */
+#define EM_BA1 201 /* Beyond BA1 */
+#define EM_BA2 202 /* Beyond BA2 */
+#define EM_XCORE 203 /* XMOS xCORE */
+#define EM_MCHP_PIC 204 /* Microchip 8-bit PIC(r) */
+#define EM_INTELGT 205 /* Intel Graphics Technology */
+ /* reserved 206-209 */
+#define EM_KM32 210 /* KM211 KM32 */
+#define EM_KMX32 211 /* KM211 KMX32 */
+#define EM_EMX16 212 /* KM211 KMX16 */
+#define EM_EMX8 213 /* KM211 KMX8 */
+#define EM_KVARC 214 /* KM211 KVARC */
+#define EM_CDP 215 /* Paneve CDP */
+#define EM_COGE 216 /* Cognitive Smart Memory Processor */
+#define EM_COOL 217 /* Bluechip CoolEngine */
+#define EM_NORC 218 /* Nanoradio Optimized RISC */
+#define EM_CSR_KALIMBA 219 /* CSR Kalimba */
+#define EM_Z80 220 /* Zilog Z80 */
+#define EM_VISIUM 221 /* Controls and Data Services VISIUMcore */
+#define EM_FT32 222 /* FTDI Chip FT32 */
+#define EM_MOXIE 223 /* Moxie processor */
+#define EM_AMDGPU 224 /* AMD GPU */
+ /* reserved 225-242 */
+#define EM_RISCV 243 /* RISC-V */
+
+#define EM_BPF 247 /* Linux BPF -- in-kernel virtual machine */
+#define EM_CSKY 252 /* C-SKY */
+#define EM_LOONGARCH 258 /* LoongArch */
+
+#define EM_NUM 259
+
+/* Old spellings/synonyms. */
+
+#define EM_ARC_A5 EM_ARC_COMPACT
+
+/* If it is necessary to assign new unofficial EM_* values, please
+ pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
+ chances of collision with official or non-GNU unofficial values. */
+
+#define EM_ALPHA 0x9026
+
+/* Legal values for e_version (version). */
+
+#define EV_NONE 0 /* Invalid ELF version */
+#define EV_CURRENT 1 /* Current version */
+#define EV_NUM 2
+
+/* Section header. */
+
+typedef struct
+{
+ Elf32_Word sh_name; /* Section name (string tbl index) */
+ Elf32_Word sh_type; /* Section type */
+ Elf32_Word sh_flags; /* Section flags */
+ Elf32_Addr sh_addr; /* Section virtual addr at execution */
+ Elf32_Off sh_offset; /* Section file offset */
+ Elf32_Word sh_size; /* Section size in bytes */
+ Elf32_Word sh_link; /* Link to another section */
+ Elf32_Word sh_info; /* Additional section information */
+ Elf32_Word sh_addralign; /* Section alignment */
+ Elf32_Word sh_entsize; /* Entry size if section holds table */
+} Elf32_Shdr;
+
+typedef struct
+{
+ Elf64_Word sh_name; /* Section name (string tbl index) */
+ Elf64_Word sh_type; /* Section type */
+ Elf64_Xword sh_flags; /* Section flags */
+ Elf64_Addr sh_addr; /* Section virtual addr at execution */
+ Elf64_Off sh_offset; /* Section file offset */
+ Elf64_Xword sh_size; /* Section size in bytes */
+ Elf64_Word sh_link; /* Link to another section */
+ Elf64_Word sh_info; /* Additional section information */
+ Elf64_Xword sh_addralign; /* Section alignment */
+ Elf64_Xword sh_entsize; /* Entry size if section holds table */
+} Elf64_Shdr;
+
+/* Special section indices. */
+
+#define SHN_UNDEF 0 /* Undefined section */
+#define SHN_LORESERVE 0xff00 /* Start of reserved indices */
+#define SHN_LOPROC 0xff00 /* Start of processor-specific */
+#define SHN_BEFORE 0xff00 /* Order section before all others
+ (Solaris). */
+#define SHN_AFTER 0xff01 /* Order section after all others
+ (Solaris). */
+#define SHN_HIPROC 0xff1f /* End of processor-specific */
+#define SHN_LOOS 0xff20 /* Start of OS-specific */
+#define SHN_HIOS 0xff3f /* End of OS-specific */
+#define SHN_ABS 0xfff1 /* Associated symbol is absolute */
+#define SHN_COMMON 0xfff2 /* Associated symbol is common */
+#define SHN_XINDEX 0xffff /* Index is in extra table. */
+#define SHN_HIRESERVE 0xffff /* End of reserved indices */
+
+/* Legal values for sh_type (section type). */
+
+#define SHT_NULL 0 /* Section header table entry unused */
+#define SHT_PROGBITS 1 /* Program data */
+#define SHT_SYMTAB 2 /* Symbol table */
+#define SHT_STRTAB 3 /* String table */
+#define SHT_RELA 4 /* Relocation entries with addends */
+#define SHT_HASH 5 /* Symbol hash table */
+#define SHT_DYNAMIC 6 /* Dynamic linking information */
+#define SHT_NOTE 7 /* Notes */
+#define SHT_NOBITS 8 /* Program space with no data (bss) */
+#define SHT_REL 9 /* Relocation entries, no addends */
+#define SHT_SHLIB 10 /* Reserved */
+#define SHT_DYNSYM 11 /* Dynamic linker symbol table */
+#define SHT_INIT_ARRAY 14 /* Array of constructors */
+#define SHT_FINI_ARRAY 15 /* Array of destructors */
+#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */
+#define SHT_GROUP 17 /* Section group */
+#define SHT_SYMTAB_SHNDX 18 /* Extended section indices */
+#define SHT_RELR 19 /* RELR relative relocations */
+#define SHT_NUM 20 /* Number of defined types. */
+#define SHT_LOOS 0x60000000 /* Start OS-specific. */
+#define SHT_GNU_ATTRIBUTES 0x6ffffff5 /* Object attributes. */
+#define SHT_GNU_HASH 0x6ffffff6 /* GNU-style hash table. */
+#define SHT_GNU_LIBLIST 0x6ffffff7 /* Prelink library list */
+#define SHT_CHECKSUM 0x6ffffff8 /* Checksum for DSO content. */
+#define SHT_LOSUNW 0x6ffffffa /* Sun-specific low bound. */
+#define SHT_SUNW_move 0x6ffffffa
+#define SHT_SUNW_COMDAT 0x6ffffffb
+#define SHT_SUNW_syminfo 0x6ffffffc
+#define SHT_GNU_verdef 0x6ffffffd /* Version definition section. */
+#define SHT_GNU_verneed 0x6ffffffe /* Version needs section. */
+#define SHT_GNU_versym 0x6fffffff /* Version symbol table. */
+#define SHT_HISUNW 0x6fffffff /* Sun-specific high bound. */
+#define SHT_HIOS 0x6fffffff /* End OS-specific type */
+#define SHT_LOPROC 0x70000000 /* Start of processor-specific */
+#define SHT_HIPROC 0x7fffffff /* End of processor-specific */
+#define SHT_LOUSER 0x80000000 /* Start of application-specific */
+#define SHT_HIUSER 0x8fffffff /* End of application-specific */
+
+/* Legal values for sh_flags (section flags). */
+
+#define SHF_WRITE (1 << 0) /* Writable */
+#define SHF_ALLOC (1 << 1) /* Occupies memory during execution */
+#define SHF_EXECINSTR (1 << 2) /* Executable */
+#define SHF_MERGE (1 << 4) /* Might be merged */
+#define SHF_STRINGS (1 << 5) /* Contains nul-terminated strings */
+#define SHF_INFO_LINK (1 << 6) /* `sh_info' contains SHT index */
+#define SHF_LINK_ORDER (1 << 7) /* Preserve order after combining */
+#define SHF_OS_NONCONFORMING (1 << 8) /* Non-standard OS specific handling
+ required */
+#define SHF_GROUP (1 << 9) /* Section is member of a group. */
+#define SHF_TLS (1 << 10) /* Section hold thread-local data. */
+#define SHF_COMPRESSED (1 << 11) /* Section with compressed data. */
+#define SHF_MASKOS 0x0ff00000 /* OS-specific. */
+#define SHF_MASKPROC 0xf0000000 /* Processor-specific */
+#define SHF_GNU_RETAIN (1 << 21) /* Not to be GCed by linker. */
+#define SHF_ORDERED (1 << 30) /* Special ordering requirement
+ (Solaris). */
+#define SHF_EXCLUDE (1U << 31) /* Section is excluded unless
+ referenced or allocated (Solaris).*/
+
+/* Section compression header. Used when SHF_COMPRESSED is set. */
+
+typedef struct
+{
+ Elf32_Word ch_type; /* Compression format. */
+ Elf32_Word ch_size; /* Uncompressed data size. */
+ Elf32_Word ch_addralign; /* Uncompressed data alignment. */
+} Elf32_Chdr;
+
+typedef struct
+{
+ Elf64_Word ch_type; /* Compression format. */
+ Elf64_Word ch_reserved;
+ Elf64_Xword ch_size; /* Uncompressed data size. */
+ Elf64_Xword ch_addralign; /* Uncompressed data alignment. */
+} Elf64_Chdr;
+
+/* Legal values for ch_type (compression algorithm). */
+#define ELFCOMPRESS_ZLIB 1 /* ZLIB/DEFLATE algorithm. */
+#define ELFCOMPRESS_ZSTD 2 /* Zstandard algorithm. */
+#define ELFCOMPRESS_LOOS 0x60000000 /* Start of OS-specific. */
+#define ELFCOMPRESS_HIOS 0x6fffffff /* End of OS-specific. */
+#define ELFCOMPRESS_LOPROC 0x70000000 /* Start of processor-specific. */
+#define ELFCOMPRESS_HIPROC 0x7fffffff /* End of processor-specific. */
+
+/* Section group handling. */
+#define GRP_COMDAT 0x1 /* Mark group as COMDAT. */
+
+/* Symbol table entry. */
+
+typedef struct
+{
+ Elf32_Word st_name; /* Symbol name (string tbl index) */
+ Elf32_Addr st_value; /* Symbol value */
+ Elf32_Word st_size; /* Symbol size */
+ unsigned char st_info; /* Symbol type and binding */
+ unsigned char st_other; /* Symbol visibility */
+ Elf32_Section st_shndx; /* Section index */
+} Elf32_Sym;
+
+typedef struct
+{
+ Elf64_Word st_name; /* Symbol name (string tbl index) */
+ unsigned char st_info; /* Symbol type and binding */
+ unsigned char st_other; /* Symbol visibility */
+ Elf64_Section st_shndx; /* Section index */
+ Elf64_Addr st_value; /* Symbol value */
+ Elf64_Xword st_size; /* Symbol size */
+} Elf64_Sym;
+
+/* The syminfo section if available contains additional information about
+ every dynamic symbol. */
+
+typedef struct
+{
+ Elf32_Half si_boundto; /* Direct bindings, symbol bound to */
+ Elf32_Half si_flags; /* Per symbol flags */
+} Elf32_Syminfo;
+
+typedef struct
+{
+ Elf64_Half si_boundto; /* Direct bindings, symbol bound to */
+ Elf64_Half si_flags; /* Per symbol flags */
+} Elf64_Syminfo;
+
+/* Possible values for si_boundto. */
+#define SYMINFO_BT_SELF 0xffff /* Symbol bound to self */
+#define SYMINFO_BT_PARENT 0xfffe /* Symbol bound to parent */
+#define SYMINFO_BT_LOWRESERVE 0xff00 /* Beginning of reserved entries */
+
+/* Possible bitmasks for si_flags. */
+#define SYMINFO_FLG_DIRECT 0x0001 /* Direct bound symbol */
+#define SYMINFO_FLG_PASSTHRU 0x0002 /* Pass-thru symbol for translator */
+#define SYMINFO_FLG_COPY 0x0004 /* Symbol is a copy-reloc */
+#define SYMINFO_FLG_LAZYLOAD 0x0008 /* Symbol bound to object to be lazy
+ loaded */
+/* Syminfo version values. */
+#define SYMINFO_NONE 0
+#define SYMINFO_CURRENT 1
+#define SYMINFO_NUM 2
+
+
+/* How to extract and insert information held in the st_info field. */
+
+#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4)
+#define ELF32_ST_TYPE(val) ((val) & 0xf)
+#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
+
+/* Both Elf32_Sym and Elf64_Sym use the same one-byte st_info field. */
+#define ELF64_ST_BIND(val) ELF32_ST_BIND (val)
+#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val)
+#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type))
+
+/* Legal values for ST_BIND subfield of st_info (symbol binding). */
+
+#define STB_LOCAL 0 /* Local symbol */
+#define STB_GLOBAL 1 /* Global symbol */
+#define STB_WEAK 2 /* Weak symbol */
+#define STB_NUM 3 /* Number of defined types. */
+#define STB_LOOS 10 /* Start of OS-specific */
+#define STB_GNU_UNIQUE 10 /* Unique symbol. */
+#define STB_HIOS 12 /* End of OS-specific */
+#define STB_LOPROC 13 /* Start of processor-specific */
+#define STB_HIPROC 15 /* End of processor-specific */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_NOTYPE 0 /* Symbol type is unspecified */
+#define STT_OBJECT 1 /* Symbol is a data object */
+#define STT_FUNC 2 /* Symbol is a code object */
+#define STT_SECTION 3 /* Symbol associated with a section */
+#define STT_FILE 4 /* Symbol's name is file name */
+#define STT_COMMON 5 /* Symbol is a common data object */
+#define STT_TLS 6 /* Symbol is thread-local data object*/
+#define STT_NUM 7 /* Number of defined types. */
+#define STT_LOOS 10 /* Start of OS-specific */
+#define STT_GNU_IFUNC 10 /* Symbol is indirect code object */
+#define STT_HIOS 12 /* End of OS-specific */
+#define STT_LOPROC 13 /* Start of processor-specific */
+#define STT_HIPROC 15 /* End of processor-specific */
+
+
+/* Symbol table indices are found in the hash buckets and chain table
+ of a symbol hash table section. This special index value indicates
+ the end of a chain, meaning no further symbols are found in that bucket. */
+
+#define STN_UNDEF 0 /* End of a chain. */
+
+
+/* How to extract and insert information held in the st_other field. */
+
+#define ELF32_ST_VISIBILITY(o) ((o) & 0x03)
+
+/* For ELF64 the definitions are the same. */
+#define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o)
+
+/* Symbol visibility specification encoded in the st_other field. */
+#define STV_DEFAULT 0 /* Default symbol visibility rules */
+#define STV_INTERNAL 1 /* Processor specific hidden class */
+#define STV_HIDDEN 2 /* Sym unavailable in other modules */
+#define STV_PROTECTED 3 /* Not preemptible, not exported */
+
+
+/* Relocation table entry without addend (in section of type SHT_REL). */
+
+typedef struct
+{
+ Elf32_Addr r_offset; /* Address */
+ Elf32_Word r_info; /* Relocation type and symbol index */
+} Elf32_Rel;
+
+/* I have seen two different definitions of the Elf64_Rel and
+ Elf64_Rela structures, so we'll leave them out until Novell (or
+ whoever) gets their act together. */
+/* The following, at least, is used on Sparc v9, MIPS, and Alpha. */
+
+typedef struct
+{
+ Elf64_Addr r_offset; /* Address */
+ Elf64_Xword r_info; /* Relocation type and symbol index */
+} Elf64_Rel;
+
+/* Relocation table entry with addend (in section of type SHT_RELA). */
+
+typedef struct
+{
+ Elf32_Addr r_offset; /* Address */
+ Elf32_Word r_info; /* Relocation type and symbol index */
+ Elf32_Sword r_addend; /* Addend */
+} Elf32_Rela;
+
+typedef struct
+{
+ Elf64_Addr r_offset; /* Address */
+ Elf64_Xword r_info; /* Relocation type and symbol index */
+ Elf64_Sxword r_addend; /* Addend */
+} Elf64_Rela;
+
+/* RELR relocation table entry */
+
+typedef Elf32_Word Elf32_Relr;
+typedef Elf64_Xword Elf64_Relr;
+
+/* How to extract and insert information held in the r_info field. */
+
+#define ELF32_R_SYM(val) ((val) >> 8)
+#define ELF32_R_TYPE(val) ((val) & 0xff)
+#define ELF32_R_INFO(sym, type) (((sym) << 8) + ((type) & 0xff))
+
+#define ELF64_R_SYM(i) ((i) >> 32)
+#define ELF64_R_TYPE(i) ((i) & 0xffffffff)
+#define ELF64_R_INFO(sym,type) ((((Elf64_Xword) (sym)) << 32) + (type))
+
+/* Program segment header. */
+
+typedef struct
+{
+ Elf32_Word p_type; /* Segment type */
+ Elf32_Off p_offset; /* Segment file offset */
+ Elf32_Addr p_vaddr; /* Segment virtual address */
+ Elf32_Addr p_paddr; /* Segment physical address */
+ Elf32_Word p_filesz; /* Segment size in file */
+ Elf32_Word p_memsz; /* Segment size in memory */
+ Elf32_Word p_flags; /* Segment flags */
+ Elf32_Word p_align; /* Segment alignment */
+} Elf32_Phdr;
+
+typedef struct
+{
+ Elf64_Word p_type; /* Segment type */
+ Elf64_Word p_flags; /* Segment flags */
+ Elf64_Off p_offset; /* Segment file offset */
+ Elf64_Addr p_vaddr; /* Segment virtual address */
+ Elf64_Addr p_paddr; /* Segment physical address */
+ Elf64_Xword p_filesz; /* Segment size in file */
+ Elf64_Xword p_memsz; /* Segment size in memory */
+ Elf64_Xword p_align; /* Segment alignment */
+} Elf64_Phdr;
+
+/* Special value for e_phnum. This indicates that the real number of
+ program headers is too large to fit into e_phnum. Instead the real
+ value is in the field sh_info of section 0. */
+
+#define PN_XNUM 0xffff
+
+/* Legal values for p_type (segment type). */
+
+#define PT_NULL 0 /* Program header table entry unused */
+#define PT_LOAD 1 /* Loadable program segment */
+#define PT_DYNAMIC 2 /* Dynamic linking information */
+#define PT_INTERP 3 /* Program interpreter */
+#define PT_NOTE 4 /* Auxiliary information */
+#define PT_SHLIB 5 /* Reserved */
+#define PT_PHDR 6 /* Entry for header table itself */
+#define PT_TLS 7 /* Thread-local storage segment */
+#define PT_NUM 8 /* Number of defined types */
+#define PT_LOOS 0x60000000 /* Start of OS-specific */
+#define PT_GNU_EH_FRAME 0x6474e550 /* GCC .eh_frame_hdr segment */
+#define PT_GNU_STACK 0x6474e551 /* Indicates stack executability */
+#define PT_GNU_RELRO 0x6474e552 /* Read-only after relocation */
+#define PT_GNU_PROPERTY 0x6474e553 /* GNU property */
+#define PT_LOSUNW 0x6ffffffa
+#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */
+#define PT_SUNWSTACK 0x6ffffffb /* Stack segment */
+#define PT_HISUNW 0x6fffffff
+#define PT_HIOS 0x6fffffff /* End of OS-specific */
+#define PT_LOPROC 0x70000000 /* Start of processor-specific */
+#define PT_HIPROC 0x7fffffff /* End of processor-specific */
+
+/* Legal values for p_flags (segment flags). */
+
+#define PF_X (1 << 0) /* Segment is executable */
+#define PF_W (1 << 1) /* Segment is writable */
+#define PF_R (1 << 2) /* Segment is readable */
+#define PF_MASKOS 0x0ff00000 /* OS-specific */
+#define PF_MASKPROC 0xf0000000 /* Processor-specific */
+
+/* Legal values for note segment descriptor types for core files. */
+
+#define NT_PRSTATUS 1 /* Contains copy of prstatus struct */
+#define NT_PRFPREG 2 /* Contains copy of fpregset
+ struct. */
+#define NT_FPREGSET 2 /* Contains copy of fpregset struct */
+#define NT_PRPSINFO 3 /* Contains copy of prpsinfo struct */
+#define NT_PRXREG 4 /* Contains copy of prxregset struct */
+#define NT_TASKSTRUCT 4 /* Contains copy of task structure */
+#define NT_PLATFORM 5 /* String from sysinfo(SI_PLATFORM) */
+#define NT_AUXV 6 /* Contains copy of auxv array */
+#define NT_GWINDOWS 7 /* Contains copy of gwindows struct */
+#define NT_ASRS 8 /* Contains copy of asrset struct */
+#define NT_PSTATUS 10 /* Contains copy of pstatus struct */
+#define NT_PSINFO 13 /* Contains copy of psinfo struct */
+#define NT_PRCRED 14 /* Contains copy of prcred struct */
+#define NT_UTSNAME 15 /* Contains copy of utsname struct */
+#define NT_LWPSTATUS 16 /* Contains copy of lwpstatus struct */
+#define NT_LWPSINFO 17 /* Contains copy of lwpinfo struct */
+#define NT_PRFPXREG 20 /* Contains copy of fprxregset struct */
+#define NT_SIGINFO 0x53494749 /* Contains copy of siginfo_t,
+ size might increase */
+#define NT_FILE 0x46494c45 /* Contains information about mapped
+ files */
+#define NT_PRXFPREG 0x46e62b7f /* Contains copy of user_fxsr_struct */
+#define NT_PPC_VMX 0x100 /* PowerPC Altivec/VMX registers */
+#define NT_PPC_SPE 0x101 /* PowerPC SPE/EVR registers */
+#define NT_PPC_VSX 0x102 /* PowerPC VSX registers */
+#define NT_PPC_TAR 0x103 /* Target Address Register */
+#define NT_PPC_PPR 0x104 /* Program Priority Register */
+#define NT_PPC_DSCR 0x105 /* Data Stream Control Register */
+#define NT_PPC_EBB 0x106 /* Event Based Branch Registers */
+#define NT_PPC_PMU 0x107 /* Performance Monitor Registers */
+#define NT_PPC_TM_CGPR 0x108 /* TM checkpointed GPR Registers */
+#define NT_PPC_TM_CFPR 0x109 /* TM checkpointed FPR Registers */
+#define NT_PPC_TM_CVMX 0x10a /* TM checkpointed VMX Registers */
+#define NT_PPC_TM_CVSX 0x10b /* TM checkpointed VSX Registers */
+#define NT_PPC_TM_SPR 0x10c /* TM Special Purpose Registers */
+#define NT_PPC_TM_CTAR 0x10d /* TM checkpointed Target Address
+ Register */
+#define NT_PPC_TM_CPPR 0x10e /* TM checkpointed Program Priority
+ Register */
+#define NT_PPC_TM_CDSCR 0x10f /* TM checkpointed Data Stream Control
+ Register */
+#define NT_PPC_PKEY 0x110 /* Memory Protection Keys
+ registers. */
+#define NT_386_TLS 0x200 /* i386 TLS slots (struct user_desc) */
+#define NT_386_IOPERM 0x201 /* x86 io permission bitmap (1=deny) */
+#define NT_X86_XSTATE 0x202 /* x86 extended state using xsave */
+#define NT_S390_HIGH_GPRS 0x300 /* s390 upper register halves */
+#define NT_S390_TIMER 0x301 /* s390 timer register */
+#define NT_S390_TODCMP 0x302 /* s390 TOD clock comparator register */
+#define NT_S390_TODPREG 0x303 /* s390 TOD programmable register */
+#define NT_S390_CTRS 0x304 /* s390 control registers */
+#define NT_S390_PREFIX 0x305 /* s390 prefix register */
+#define NT_S390_LAST_BREAK 0x306 /* s390 breaking event address */
+#define NT_S390_SYSTEM_CALL 0x307 /* s390 system call restart data */
+#define NT_S390_TDB 0x308 /* s390 transaction diagnostic block */
+#define NT_S390_VXRS_LOW 0x309 /* s390 vector registers 0-15
+ upper half. */
+#define NT_S390_VXRS_HIGH 0x30a /* s390 vector registers 16-31. */
+#define NT_S390_GS_CB 0x30b /* s390 guarded storage registers. */
+#define NT_S390_GS_BC 0x30c /* s390 guarded storage
+ broadcast control block. */
+#define NT_S390_RI_CB 0x30d /* s390 runtime instrumentation. */
+#define NT_S390_PV_CPU_DATA 0x30e /* s390 protvirt cpu dump data. */
+#define NT_ARM_VFP 0x400 /* ARM VFP/NEON registers */
+#define NT_ARM_TLS 0x401 /* ARM TLS register */
+#define NT_ARM_HW_BREAK 0x402 /* ARM hardware breakpoint registers */
+#define NT_ARM_HW_WATCH 0x403 /* ARM hardware watchpoint registers */
+#define NT_ARM_SYSTEM_CALL 0x404 /* ARM system call number */
+#define NT_ARM_SVE 0x405 /* ARM Scalable Vector Extension
+ registers */
+#define NT_ARM_PAC_MASK 0x406 /* ARM pointer authentication
+ code masks. */
+#define NT_ARM_PACA_KEYS 0x407 /* ARM pointer authentication
+ address keys. */
+#define NT_ARM_PACG_KEYS 0x408 /* ARM pointer authentication
+ generic key. */
+#define NT_ARM_TAGGED_ADDR_CTRL 0x409 /* AArch64 tagged address
+ control. */
+#define NT_ARM_PAC_ENABLED_KEYS 0x40a /* AArch64 pointer authentication
+ enabled keys. */
+#define NT_VMCOREDD 0x700 /* Vmcore Device Dump Note. */
+#define NT_MIPS_DSP 0x800 /* MIPS DSP ASE registers. */
+#define NT_MIPS_FP_MODE 0x801 /* MIPS floating-point mode. */
+#define NT_MIPS_MSA 0x802 /* MIPS SIMD registers. */
+#define NT_LOONGARCH_CPUCFG 0xa00 /* LoongArch CPU config registers. */
+#define NT_LOONGARCH_CSR 0xa01 /* LoongArch control and
+ status registers. */
+#define NT_LOONGARCH_LSX 0xa02 /* LoongArch Loongson SIMD
+ Extension registers. */
+#define NT_LOONGARCH_LASX 0xa03 /* LoongArch Loongson Advanced
+ SIMD Extension registers. */
+#define NT_LOONGARCH_LBT 0xa04 /* LoongArch Loongson Binary
+ Translation registers. */
+
+/* Legal values for the note segment descriptor types for object files. */
+
+#define NT_VERSION 1 /* Contains a version string. */
+
+
+/* Dynamic section entry. */
+
+typedef struct
+{
+ Elf32_Sword d_tag; /* Dynamic entry type */
+ union
+ {
+ Elf32_Word d_val; /* Integer value */
+ Elf32_Addr d_ptr; /* Address value */
+ } d_un;
+} Elf32_Dyn;
+
+typedef struct
+{
+ Elf64_Sxword d_tag; /* Dynamic entry type */
+ union
+ {
+ Elf64_Xword d_val; /* Integer value */
+ Elf64_Addr d_ptr; /* Address value */
+ } d_un;
+} Elf64_Dyn;
+
+/* Legal values for d_tag (dynamic entry type). */
+
+#define DT_NULL 0 /* Marks end of dynamic section */
+#define DT_NEEDED 1 /* Name of needed library */
+#define DT_PLTRELSZ 2 /* Size in bytes of PLT relocs */
+#define DT_PLTGOT 3 /* Processor defined value */
+#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 Rela relocs */
+#define DT_RELASZ 8 /* Total size of Rela relocs */
+#define DT_RELAENT 9 /* Size of one Rela reloc */
+#define DT_STRSZ 10 /* Size of string table */
+#define DT_SYMENT 11 /* Size of one symbol table entry */
+#define DT_INIT 12 /* Address of init function */
+#define DT_FINI 13 /* Address of termination function */
+#define DT_SONAME 14 /* Name of shared object */
+#define DT_RPATH 15 /* Library search path (deprecated) */
+#define DT_SYMBOLIC 16 /* Start symbol search here */
+#define DT_REL 17 /* Address of Rel relocs */
+#define DT_RELSZ 18 /* Total size of Rel relocs */
+#define DT_RELENT 19 /* Size of one Rel reloc */
+#define DT_PLTREL 20 /* Type of reloc in PLT */
+#define DT_DEBUG 21 /* For debugging; unspecified */
+#define DT_TEXTREL 22 /* Reloc might modify .text */
+#define DT_JMPREL 23 /* Address of PLT relocs */
+#define DT_BIND_NOW 24 /* Process relocations of object */
+#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */
+#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */
+#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */
+#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */
+#define DT_RUNPATH 29 /* Library search path */
+#define DT_FLAGS 30 /* Flags for the object being loaded */
+#define DT_ENCODING 32 /* Start of encoded range */
+#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/
+#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */
+#define DT_SYMTAB_SHNDX 34 /* Address of SYMTAB_SHNDX section */
+#define DT_RELRSZ 35 /* Total size of RELR relative relocations */
+#define DT_RELR 36 /* Address of RELR relative relocations */
+#define DT_RELRENT 37 /* Size of one RELR relative relocaction */
+#define DT_NUM 38 /* Number used */
+#define DT_LOOS 0x6000000d /* Start of OS-specific */
+#define DT_HIOS 0x6ffff000 /* End of OS-specific */
+#define DT_LOPROC 0x70000000 /* Start of processor-specific */
+#define DT_HIPROC 0x7fffffff /* End of processor-specific */
+#define DT_PROCNUM DT_MIPS_NUM /* Most used by any processor */
+
+/* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
+ Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's
+ approach. */
+#define DT_VALRNGLO 0x6ffffd00
+#define DT_GNU_PRELINKED 0x6ffffdf5 /* Prelinking timestamp */
+#define DT_GNU_CONFLICTSZ 0x6ffffdf6 /* Size of conflict section */
+#define DT_GNU_LIBLISTSZ 0x6ffffdf7 /* Size of library list */
+#define DT_CHECKSUM 0x6ffffdf8
+#define DT_PLTPADSZ 0x6ffffdf9
+#define DT_MOVEENT 0x6ffffdfa
+#define DT_MOVESZ 0x6ffffdfb
+#define DT_FEATURE_1 0x6ffffdfc /* Feature selection (DTF_*). */
+#define DT_POSFLAG_1 0x6ffffdfd /* Flags for DT_* entries, effecting
+ the following DT_* entry. */
+#define DT_SYMINSZ 0x6ffffdfe /* Size of syminfo table (in bytes) */
+#define DT_SYMINENT 0x6ffffdff /* Entry size of syminfo */
+#define DT_VALRNGHI 0x6ffffdff
+#define DT_VALTAGIDX(tag) (DT_VALRNGHI - (tag)) /* Reverse order! */
+#define DT_VALNUM 12
+
+/* 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_TLSDESC_PLT 0x6ffffef6
+#define DT_TLSDESC_GOT 0x6ffffef7
+#define DT_GNU_CONFLICT 0x6ffffef8 /* Start of conflict section */
+#define DT_GNU_LIBLIST 0x6ffffef9 /* Library list */
+#define DT_CONFIG 0x6ffffefa /* Configuration information. */
+#define DT_DEPAUDIT 0x6ffffefb /* Dependency auditing. */
+#define DT_AUDIT 0x6ffffefc /* Object auditing. */
+#define DT_PLTPAD 0x6ffffefd /* PLT padding. */
+#define DT_MOVETAB 0x6ffffefe /* Move table. */
+#define DT_SYMINFO 0x6ffffeff /* Syminfo table. */
+#define DT_ADDRRNGHI 0x6ffffeff
+#define DT_ADDRTAGIDX(tag) (DT_ADDRRNGHI - (tag)) /* Reverse order! */
+#define DT_ADDRNUM 11
+
+/* The versioning entry types. The next are defined as part of the
+ GNU extension. */
+#define DT_VERSYM 0x6ffffff0
+
+#define DT_RELACOUNT 0x6ffffff9
+#define DT_RELCOUNT 0x6ffffffa
+
+/* These were chosen by Sun. */
+#define DT_FLAGS_1 0x6ffffffb /* State flags, see DF_1_* below. */
+#define DT_VERDEF 0x6ffffffc /* Address of version definition
+ table */
+#define DT_VERDEFNUM 0x6ffffffd /* Number of version definitions */
+#define DT_VERNEED 0x6ffffffe /* Address of table with needed
+ versions */
+#define DT_VERNEEDNUM 0x6fffffff /* Number of needed versions */
+#define DT_VERSIONTAGIDX(tag) (DT_VERNEEDNUM - (tag)) /* Reverse order! */
+#define DT_VERSIONTAGNUM 16
+
+/* Sun added these machine-independent extensions in the "processor-specific"
+ range. Be compatible. */
+#define DT_AUXILIARY 0x7ffffffd /* Shared object to load before self */
+#define DT_FILTER 0x7fffffff /* Shared object to get values from */
+#define DT_EXTRATAGIDX(tag) ((Elf32_Word)-((Elf32_Sword) (tag) <<1>>1)-1)
+#define DT_EXTRANUM 3
+
+/* Values of `d_un.d_val' in the DT_FLAGS entry. */
+#define DF_ORIGIN 0x00000001 /* Object may use DF_ORIGIN */
+#define DF_SYMBOLIC 0x00000002 /* Symbol resolutions starts here */
+#define DF_TEXTREL 0x00000004 /* Object contains text relocations */
+#define DF_BIND_NOW 0x00000008 /* No lazy binding for this object */
+#define DF_STATIC_TLS 0x00000010 /* Module uses the static TLS model */
+
+/* State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1
+ entry in the dynamic section. */
+#define DF_1_NOW 0x00000001 /* Set RTLD_NOW for this object. */
+#define DF_1_GLOBAL 0x00000002 /* Set RTLD_GLOBAL for this object. */
+#define DF_1_GROUP 0x00000004 /* Set RTLD_GROUP for this object. */
+#define DF_1_NODELETE 0x00000008 /* Set RTLD_NODELETE for this object.*/
+#define DF_1_LOADFLTR 0x00000010 /* Trigger filtee loading at runtime.*/
+#define DF_1_INITFIRST 0x00000020 /* Set RTLD_INITFIRST for this object*/
+#define DF_1_NOOPEN 0x00000040 /* Set RTLD_NOOPEN for this object. */
+#define DF_1_ORIGIN 0x00000080 /* $ORIGIN must be handled. */
+#define DF_1_DIRECT 0x00000100 /* Direct binding enabled. */
+#define DF_1_TRANS 0x00000200
+#define DF_1_INTERPOSE 0x00000400 /* Object is used to interpose. */
+#define DF_1_NODEFLIB 0x00000800 /* Ignore default lib search path. */
+#define DF_1_NODUMP 0x00001000 /* Object can't be dldump'ed. */
+#define DF_1_CONFALT 0x00002000 /* Configuration alternative created.*/
+#define DF_1_ENDFILTEE 0x00004000 /* Filtee terminates filters search. */
+#define DF_1_DISPRELDNE 0x00008000 /* Disp reloc applied at build time. */
+#define DF_1_DISPRELPND 0x00010000 /* Disp reloc applied at run-time. */
+#define DF_1_NODIRECT 0x00020000 /* Object has no-direct binding. */
+#define DF_1_IGNMULDEF 0x00040000
+#define DF_1_NOKSYMS 0x00080000
+#define DF_1_NOHDR 0x00100000
+#define DF_1_EDITED 0x00200000 /* Object is modified after built. */
+#define DF_1_NORELOC 0x00400000
+#define DF_1_SYMINTPOSE 0x00800000 /* Object has individual interposers. */
+#define DF_1_GLOBAUDIT 0x01000000 /* Global auditing required. */
+#define DF_1_SINGLETON 0x02000000 /* Singleton symbols are used. */
+#define DF_1_STUB 0x04000000
+#define DF_1_PIE 0x08000000
+#define DF_1_KMOD 0x10000000
+#define DF_1_WEAKFILTER 0x20000000
+#define DF_1_NOCOMMON 0x40000000
+
+/* Flags for the feature selection in DT_FEATURE_1. */
+#define DTF_1_PARINIT 0x00000001
+#define DTF_1_CONFEXP 0x00000002
+
+/* Flags in the DT_POSFLAG_1 entry effecting only the next DT_* entry. */
+#define DF_P1_LAZYLOAD 0x00000001 /* Lazyload following object. */
+#define DF_P1_GROUPPERM 0x00000002 /* Symbols from next object are not
+ generally available. */
+
+/* Version definition sections. */
+
+typedef struct
+{
+ Elf32_Half vd_version; /* Version revision */
+ Elf32_Half vd_flags; /* Version information */
+ Elf32_Half vd_ndx; /* Version Index */
+ Elf32_Half vd_cnt; /* Number of associated aux entries */
+ Elf32_Word vd_hash; /* Version name hash value */
+ Elf32_Word vd_aux; /* Offset in bytes to verdaux array */
+ Elf32_Word vd_next; /* Offset in bytes to next verdef
+ entry */
+} Elf32_Verdef;
+
+typedef struct
+{
+ Elf64_Half vd_version; /* Version revision */
+ Elf64_Half vd_flags; /* Version information */
+ Elf64_Half vd_ndx; /* Version Index */
+ Elf64_Half vd_cnt; /* Number of associated aux entries */
+ Elf64_Word vd_hash; /* Version name hash value */
+ Elf64_Word vd_aux; /* Offset in bytes to verdaux array */
+ Elf64_Word vd_next; /* Offset in bytes to next verdef
+ entry */
+} Elf64_Verdef;
+
+
+/* Legal values for vd_version (version revision). */
+#define VER_DEF_NONE 0 /* No version */
+#define VER_DEF_CURRENT 1 /* Current version */
+#define VER_DEF_NUM 2 /* Given version number */
+
+/* Legal values for vd_flags (version information flags). */
+#define VER_FLG_BASE 0x1 /* Version definition of file itself */
+#define VER_FLG_WEAK 0x2 /* Weak version identifier. Also
+ used by vna_flags below. */
+
+/* Versym symbol index values. */
+#define VER_NDX_LOCAL 0 /* Symbol is local. */
+#define VER_NDX_GLOBAL 1 /* Symbol is global. */
+#define VER_NDX_LORESERVE 0xff00 /* Beginning of reserved entries. */
+#define VER_NDX_ELIMINATE 0xff01 /* Symbol is to be eliminated. */
+
+/* Auxiliary version information. */
+
+typedef struct
+{
+ Elf32_Word vda_name; /* Version or dependency names */
+ Elf32_Word vda_next; /* Offset in bytes to next verdaux
+ entry */
+} Elf32_Verdaux;
+
+typedef struct
+{
+ Elf64_Word vda_name; /* Version or dependency names */
+ Elf64_Word vda_next; /* Offset in bytes to next verdaux
+ entry */
+} Elf64_Verdaux;
+
+
+/* Version dependency section. */
+
+typedef struct
+{
+ Elf32_Half vn_version; /* Version of structure */
+ Elf32_Half vn_cnt; /* Number of associated aux entries */
+ Elf32_Word vn_file; /* Offset of filename for this
+ dependency */
+ Elf32_Word vn_aux; /* Offset in bytes to vernaux array */
+ Elf32_Word vn_next; /* Offset in bytes to next verneed
+ entry */
+} Elf32_Verneed;
+
+typedef struct
+{
+ Elf64_Half vn_version; /* Version of structure */
+ Elf64_Half vn_cnt; /* Number of associated aux entries */
+ Elf64_Word vn_file; /* Offset of filename for this
+ dependency */
+ Elf64_Word vn_aux; /* Offset in bytes to vernaux array */
+ Elf64_Word vn_next; /* Offset in bytes to next verneed
+ entry */
+} Elf64_Verneed;
+
+
+/* Legal values for vn_version (version revision). */
+#define VER_NEED_NONE 0 /* No version */
+#define VER_NEED_CURRENT 1 /* Current version */
+#define VER_NEED_NUM 2 /* Given version number */
+
+/* Auxiliary needed version information. */
+
+typedef struct
+{
+ Elf32_Word vna_hash; /* Hash value of dependency name */
+ Elf32_Half vna_flags; /* Dependency specific information */
+ Elf32_Half vna_other; /* Unused */
+ Elf32_Word vna_name; /* Dependency name string offset */
+ Elf32_Word vna_next; /* Offset in bytes to next vernaux
+ entry */
+} Elf32_Vernaux;
+
+typedef struct
+{
+ Elf64_Word vna_hash; /* Hash value of dependency name */
+ Elf64_Half vna_flags; /* Dependency specific information */
+ Elf64_Half vna_other; /* Unused */
+ Elf64_Word vna_name; /* Dependency name string offset */
+ Elf64_Word vna_next; /* Offset in bytes to next vernaux
+ entry */
+} Elf64_Vernaux;
+
+
+/* Auxiliary vector. */
+
+/* This vector is normally only used by the program interpreter. The
+ usual definition in an ABI supplement uses the name auxv_t. The
+ vector is not usually defined in a standard <elf.h> file, but it
+ can't hurt. We rename it to avoid conflicts. The sizes of these
+ types are an arrangement between the exec server and the program
+ interpreter, so we don't fully specify them here. */
+
+typedef struct
+{
+ uint32_t a_type; /* Entry type */
+ union
+ {
+ uint32_t a_val; /* Integer value */
+ /* We use to have pointer elements added here. We cannot do that,
+ though, since it does not work when using 32-bit definitions
+ on 64-bit platforms and vice versa. */
+ } a_un;
+} Elf32_auxv_t;
+
+typedef struct
+{
+ uint64_t a_type; /* Entry type */
+ union
+ {
+ uint64_t a_val; /* Integer value */
+ /* We use to have pointer elements added here. We cannot do that,
+ though, since it does not work when using 32-bit definitions
+ on 64-bit platforms and vice versa. */
+ } a_un;
+} Elf64_auxv_t;
+
+/* Legal values for a_type (entry type). */
+
+#define AT_NULL 0 /* End of vector */
+#define AT_IGNORE 1 /* Entry should be ignored */
+#define AT_EXECFD 2 /* File descriptor of program */
+#define AT_PHDR 3 /* Program headers for program */
+#define AT_PHENT 4 /* Size of program header entry */
+#define AT_PHNUM 5 /* Number of program headers */
+#define AT_PAGESZ 6 /* System page size */
+#define AT_BASE 7 /* Base address of interpreter */
+#define AT_FLAGS 8 /* Flags */
+#define AT_ENTRY 9 /* Entry point of program */
+#define AT_NOTELF 10 /* Program is not ELF */
+#define AT_UID 11 /* Real uid */
+#define AT_EUID 12 /* Effective uid */
+#define AT_GID 13 /* Real gid */
+#define AT_EGID 14 /* Effective gid */
+#define AT_CLKTCK 17 /* Frequency of times() */
+
+/* Some more special a_type values describing the hardware. */
+#define AT_PLATFORM 15 /* String identifying platform. */
+#define AT_HWCAP 16 /* Machine-dependent hints about
+ processor capabilities. */
+
+/* This entry gives some information about the FPU initialization
+ performed by the kernel. */
+#define AT_FPUCW 18 /* Used FPU control word. */
+
+/* Cache block sizes. */
+#define AT_DCACHEBSIZE 19 /* Data cache block size. */
+#define AT_ICACHEBSIZE 20 /* Instruction cache block size. */
+#define AT_UCACHEBSIZE 21 /* Unified cache block size. */
+
+/* A special ignored value for PPC, used by the kernel to control the
+ interpretation of the AUXV. Must be > 16. */
+#define AT_IGNOREPPC 22 /* Entry should be ignored. */
+
+#define AT_SECURE 23 /* Boolean, was exec setuid-like? */
+
+#define AT_BASE_PLATFORM 24 /* String identifying real platforms.*/
+
+#define AT_RANDOM 25 /* Address of 16 random bytes. */
+
+#define AT_HWCAP2 26 /* More machine-dependent hints about
+ processor capabilities. */
+
+#define AT_EXECFN 31 /* Filename of executable. */
+
+/* Pointer to the global system page used for system calls and other
+ nice things. */
+#define AT_SYSINFO 32
+#define AT_SYSINFO_EHDR 33
+
+/* Shapes of the caches. Bits 0-3 contains associativity; bits 4-7 contains
+ log2 of line size; mask those to get cache size. */
+#define AT_L1I_CACHESHAPE 34
+#define AT_L1D_CACHESHAPE 35
+#define AT_L2_CACHESHAPE 36
+#define AT_L3_CACHESHAPE 37
+
+/* Shapes of the caches, with more room to describe them.
+ *GEOMETRY are comprised of cache line size in bytes in the bottom 16 bits
+ and the cache associativity in the next 16 bits. */
+#define AT_L1I_CACHESIZE 40
+#define AT_L1I_CACHEGEOMETRY 41
+#define AT_L1D_CACHESIZE 42
+#define AT_L1D_CACHEGEOMETRY 43
+#define AT_L2_CACHESIZE 44
+#define AT_L2_CACHEGEOMETRY 45
+#define AT_L3_CACHESIZE 46
+#define AT_L3_CACHEGEOMETRY 47
+
+#define AT_MINSIGSTKSZ 51 /* Stack needed for signal delivery */
+
+/* Note section contents. Each entry in the note section begins with
+ a header of a fixed form. */
+
+typedef struct
+{
+ Elf32_Word n_namesz; /* Length of the note's name. */
+ Elf32_Word n_descsz; /* Length of the note's descriptor. */
+ Elf32_Word n_type; /* Type of the note. */
+} Elf32_Nhdr;
+
+typedef struct
+{
+ Elf64_Word n_namesz; /* Length of the note's name. */
+ Elf64_Word n_descsz; /* Length of the note's descriptor. */
+ Elf64_Word n_type; /* Type of the note. */
+} Elf64_Nhdr;
+
+/* Known names of notes. */
+
+/* Solaris entries in the note section have this name. */
+#define ELF_NOTE_SOLARIS "SUNW Solaris"
+
+/* Note entries for GNU systems have this name. */
+#define ELF_NOTE_GNU "GNU"
+
+/* Note entries for freedesktop.org have this name. */
+#define ELF_NOTE_FDO "FDO"
+
+/* Defined types of notes for Solaris. */
+
+/* Value of descriptor (one word) is desired pagesize for the binary. */
+#define ELF_NOTE_PAGESIZE_HINT 1
+
+
+/* Defined note types for GNU systems. */
+
+/* ABI information. The descriptor consists of words:
+ word 0: OS descriptor
+ word 1: major version of the ABI
+ word 2: minor version of the ABI
+ word 3: subminor version of the ABI
+*/
+#define NT_GNU_ABI_TAG 1
+#define ELF_NOTE_ABI NT_GNU_ABI_TAG /* Old name. */
+
+/* Known OSes. These values can appear in word 0 of an
+ NT_GNU_ABI_TAG note section entry. */
+#define ELF_NOTE_OS_LINUX 0
+#define ELF_NOTE_OS_GNU 1
+#define ELF_NOTE_OS_SOLARIS2 2
+#define ELF_NOTE_OS_FREEBSD 3
+
+/* Synthetic hwcap information. The descriptor begins with two words:
+ word 0: number of entries
+ word 1: bitmask of enabled entries
+ Then follow variable-length entries, one byte followed by a
+ '\0'-terminated hwcap name string. The byte gives the bit
+ number to test if enabled, (1U << bit) & bitmask. */
+#define NT_GNU_HWCAP 2
+
+/* Build ID bits as generated by ld --build-id.
+ The descriptor consists of any nonzero number of bytes. */
+#define NT_GNU_BUILD_ID 3
+
+/* Version note generated by GNU gold containing a version string. */
+#define NT_GNU_GOLD_VERSION 4
+
+/* Program property. */
+#define NT_GNU_PROPERTY_TYPE_0 5
+
+/* Packaging metadata as defined on
+ https://systemd.io/COREDUMP_PACKAGE_METADATA/ */
+#define NT_FDO_PACKAGING_METADATA 0xcafe1a7e
+
+/* Note section name of program property. */
+#define NOTE_GNU_PROPERTY_SECTION_NAME ".note.gnu.property"
+
+/* Values used in GNU .note.gnu.property notes (NT_GNU_PROPERTY_TYPE_0). */
+
+/* Stack size. */
+#define GNU_PROPERTY_STACK_SIZE 1
+/* No copy relocation on protected data symbol. */
+#define GNU_PROPERTY_NO_COPY_ON_PROTECTED 2
+
+/* A 4-byte unsigned integer property: A bit is set if it is set in all
+ relocatable inputs. */
+#define GNU_PROPERTY_UINT32_AND_LO 0xb0000000
+#define GNU_PROPERTY_UINT32_AND_HI 0xb0007fff
+
+/* A 4-byte unsigned integer property: A bit is set if it is set in any
+ relocatable inputs. */
+#define GNU_PROPERTY_UINT32_OR_LO 0xb0008000
+#define GNU_PROPERTY_UINT32_OR_HI 0xb000ffff
+
+/* The needed properties by the object file. */
+#define GNU_PROPERTY_1_NEEDED GNU_PROPERTY_UINT32_OR_LO
+
+/* Set if the object file requires canonical function pointers and
+ cannot be used with copy relocation. */
+#define GNU_PROPERTY_1_NEEDED_INDIRECT_EXTERN_ACCESS (1U << 0)
+
+/* Processor-specific semantics, lo */
+#define GNU_PROPERTY_LOPROC 0xc0000000
+/* Processor-specific semantics, hi */
+#define GNU_PROPERTY_HIPROC 0xdfffffff
+/* Application-specific semantics, lo */
+#define GNU_PROPERTY_LOUSER 0xe0000000
+/* Application-specific semantics, hi */
+#define GNU_PROPERTY_HIUSER 0xffffffff
+
+/* AArch64 specific GNU properties. */
+#define GNU_PROPERTY_AARCH64_FEATURE_1_AND 0xc0000000
+
+#define GNU_PROPERTY_AARCH64_FEATURE_1_BTI (1U << 0)
+#define GNU_PROPERTY_AARCH64_FEATURE_1_PAC (1U << 1)
+
+/* The x86 instruction sets indicated by the corresponding bits are
+ used in program. Their support in the hardware is optional. */
+#define GNU_PROPERTY_X86_ISA_1_USED 0xc0010002
+/* The x86 instruction sets indicated by the corresponding bits are
+ used in program and they must be supported by the hardware. */
+#define GNU_PROPERTY_X86_ISA_1_NEEDED 0xc0008002
+/* X86 processor-specific features used in program. */
+#define GNU_PROPERTY_X86_FEATURE_1_AND 0xc0000002
+
+/* GNU_PROPERTY_X86_ISA_1_BASELINE: CMOV, CX8 (cmpxchg8b), FPU (fld),
+ MMX, OSFXSR (fxsave), SCE (syscall), SSE and SSE2. */
+#define GNU_PROPERTY_X86_ISA_1_BASELINE (1U << 0)
+/* GNU_PROPERTY_X86_ISA_1_V2: GNU_PROPERTY_X86_ISA_1_BASELINE,
+ CMPXCHG16B (cmpxchg16b), LAHF-SAHF (lahf), POPCNT (popcnt), SSE3,
+ SSSE3, SSE4.1 and SSE4.2. */
+#define GNU_PROPERTY_X86_ISA_1_V2 (1U << 1)
+/* GNU_PROPERTY_X86_ISA_1_V3: GNU_PROPERTY_X86_ISA_1_V2, AVX, AVX2, BMI1,
+ BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE. */
+#define GNU_PROPERTY_X86_ISA_1_V3 (1U << 2)
+/* GNU_PROPERTY_X86_ISA_1_V4: GNU_PROPERTY_X86_ISA_1_V3, AVX512F,
+ AVX512BW, AVX512CD, AVX512DQ and AVX512VL. */
+#define GNU_PROPERTY_X86_ISA_1_V4 (1U << 3)
+
+/* This indicates that all executable sections are compatible with
+ IBT. */
+#define GNU_PROPERTY_X86_FEATURE_1_IBT (1U << 0)
+/* This indicates that all executable sections are compatible with
+ SHSTK. */
+#define GNU_PROPERTY_X86_FEATURE_1_SHSTK (1U << 1)
+
+/* Move records. */
+typedef struct
+{
+ Elf32_Xword m_value; /* Symbol value. */
+ Elf32_Word m_info; /* Size and index. */
+ Elf32_Word m_poffset; /* Symbol offset. */
+ Elf32_Half m_repeat; /* Repeat count. */
+ Elf32_Half m_stride; /* Stride info. */
+} Elf32_Move;
+
+typedef struct
+{
+ Elf64_Xword m_value; /* Symbol value. */
+ Elf64_Xword m_info; /* Size and index. */
+ Elf64_Xword m_poffset; /* Symbol offset. */
+ Elf64_Half m_repeat; /* Repeat count. */
+ Elf64_Half m_stride; /* Stride info. */
+} Elf64_Move;
+
+/* Macro to construct move records. */
+#define ELF32_M_SYM(info) ((info) >> 8)
+#define ELF32_M_SIZE(info) ((unsigned char) (info))
+#define ELF32_M_INFO(sym, size) (((sym) << 8) + (unsigned char) (size))
+
+#define ELF64_M_SYM(info) ELF32_M_SYM (info)
+#define ELF64_M_SIZE(info) ELF32_M_SIZE (info)
+#define ELF64_M_INFO(sym, size) ELF32_M_INFO (sym, size)
+
+
+/* Motorola 68k specific definitions. */
+
+/* Values for Elf32_Ehdr.e_flags. */
+#define EF_CPU32 0x00810000
+
+/* m68k relocs. */
+
+#define R_68K_NONE 0 /* No reloc */
+#define R_68K_32 1 /* Direct 32 bit */
+#define R_68K_16 2 /* Direct 16 bit */
+#define R_68K_8 3 /* Direct 8 bit */
+#define R_68K_PC32 4 /* PC relative 32 bit */
+#define R_68K_PC16 5 /* PC relative 16 bit */
+#define R_68K_PC8 6 /* PC relative 8 bit */
+#define R_68K_GOT32 7 /* 32 bit PC relative GOT entry */
+#define R_68K_GOT16 8 /* 16 bit PC relative GOT entry */
+#define R_68K_GOT8 9 /* 8 bit PC relative GOT entry */
+#define R_68K_GOT32O 10 /* 32 bit GOT offset */
+#define R_68K_GOT16O 11 /* 16 bit GOT offset */
+#define R_68K_GOT8O 12 /* 8 bit GOT offset */
+#define R_68K_PLT32 13 /* 32 bit PC relative PLT address */
+#define R_68K_PLT16 14 /* 16 bit PC relative PLT address */
+#define R_68K_PLT8 15 /* 8 bit PC relative PLT address */
+#define R_68K_PLT32O 16 /* 32 bit PLT offset */
+#define R_68K_PLT16O 17 /* 16 bit PLT offset */
+#define R_68K_PLT8O 18 /* 8 bit PLT offset */
+#define R_68K_COPY 19 /* Copy symbol at runtime */
+#define R_68K_GLOB_DAT 20 /* Create GOT entry */
+#define R_68K_JMP_SLOT 21 /* Create PLT entry */
+#define R_68K_RELATIVE 22 /* Adjust by program base */
+#define R_68K_TLS_GD32 25 /* 32 bit GOT offset for GD */
+#define R_68K_TLS_GD16 26 /* 16 bit GOT offset for GD */
+#define R_68K_TLS_GD8 27 /* 8 bit GOT offset for GD */
+#define R_68K_TLS_LDM32 28 /* 32 bit GOT offset for LDM */
+#define R_68K_TLS_LDM16 29 /* 16 bit GOT offset for LDM */
+#define R_68K_TLS_LDM8 30 /* 8 bit GOT offset for LDM */
+#define R_68K_TLS_LDO32 31 /* 32 bit module-relative offset */
+#define R_68K_TLS_LDO16 32 /* 16 bit module-relative offset */
+#define R_68K_TLS_LDO8 33 /* 8 bit module-relative offset */
+#define R_68K_TLS_IE32 34 /* 32 bit GOT offset for IE */
+#define R_68K_TLS_IE16 35 /* 16 bit GOT offset for IE */
+#define R_68K_TLS_IE8 36 /* 8 bit GOT offset for IE */
+#define R_68K_TLS_LE32 37 /* 32 bit offset relative to
+ static TLS block */
+#define R_68K_TLS_LE16 38 /* 16 bit offset relative to
+ static TLS block */
+#define R_68K_TLS_LE8 39 /* 8 bit offset relative to
+ static TLS block */
+#define R_68K_TLS_DTPMOD32 40 /* 32 bit module number */
+#define R_68K_TLS_DTPREL32 41 /* 32 bit module-relative offset */
+#define R_68K_TLS_TPREL32 42 /* 32 bit TP-relative offset */
+/* Keep this the last entry. */
+#define R_68K_NUM 43
+
+/* Intel 80386 specific definitions. */
+
+/* i386 relocs. */
+
+#define R_386_NONE 0 /* No reloc */
+#define R_386_32 1 /* Direct 32 bit */
+#define R_386_PC32 2 /* PC relative 32 bit */
+#define R_386_GOT32 3 /* 32 bit GOT entry */
+#define R_386_PLT32 4 /* 32 bit PLT address */
+#define R_386_COPY 5 /* Copy symbol at runtime */
+#define R_386_GLOB_DAT 6 /* Create GOT entry */
+#define R_386_JMP_SLOT 7 /* Create PLT entry */
+#define R_386_RELATIVE 8 /* Adjust by program base */
+#define R_386_GOTOFF 9 /* 32 bit offset to GOT */
+#define R_386_GOTPC 10 /* 32 bit PC relative offset to GOT */
+#define R_386_32PLT 11
+#define R_386_TLS_TPOFF 14 /* Offset in static TLS block */
+#define R_386_TLS_IE 15 /* Address of GOT entry for static TLS
+ block offset */
+#define R_386_TLS_GOTIE 16 /* GOT entry for static TLS block
+ offset */
+#define R_386_TLS_LE 17 /* Offset relative to static TLS
+ block */
+#define R_386_TLS_GD 18 /* Direct 32 bit for GNU version of
+ general dynamic thread local data */
+#define R_386_TLS_LDM 19 /* Direct 32 bit for GNU version of
+ local dynamic thread local data
+ in LE code */
+#define R_386_16 20
+#define R_386_PC16 21
+#define R_386_8 22
+#define R_386_PC8 23
+#define R_386_TLS_GD_32 24 /* Direct 32 bit for general dynamic
+ thread local data */
+#define R_386_TLS_GD_PUSH 25 /* Tag for pushl in GD TLS code */
+#define R_386_TLS_GD_CALL 26 /* Relocation for call to
+ __tls_get_addr() */
+#define R_386_TLS_GD_POP 27 /* Tag for popl in GD TLS code */
+#define R_386_TLS_LDM_32 28 /* Direct 32 bit for local dynamic
+ thread local data in LE code */
+#define R_386_TLS_LDM_PUSH 29 /* Tag for pushl in LDM TLS code */
+#define R_386_TLS_LDM_CALL 30 /* Relocation for call to
+ __tls_get_addr() in LDM code */
+#define R_386_TLS_LDM_POP 31 /* Tag for popl in LDM TLS code */
+#define R_386_TLS_LDO_32 32 /* Offset relative to TLS block */
+#define R_386_TLS_IE_32 33 /* GOT entry for negated static TLS
+ block offset */
+#define R_386_TLS_LE_32 34 /* Negated offset relative to static
+ TLS block */
+#define R_386_TLS_DTPMOD32 35 /* ID of module containing symbol */
+#define R_386_TLS_DTPOFF32 36 /* Offset in TLS block */
+#define R_386_TLS_TPOFF32 37 /* Negated offset in static TLS block */
+#define R_386_SIZE32 38 /* 32-bit symbol size */
+#define R_386_TLS_GOTDESC 39 /* GOT offset for TLS descriptor. */
+#define R_386_TLS_DESC_CALL 40 /* Marker of call through TLS
+ descriptor for
+ relaxation. */
+#define R_386_TLS_DESC 41 /* TLS descriptor containing
+ pointer to code and to
+ argument, returning the TLS
+ offset for the symbol. */
+#define R_386_IRELATIVE 42 /* Adjust indirectly by program base */
+#define R_386_GOT32X 43 /* Load from 32 bit GOT entry,
+ relaxable. */
+/* Keep this the last entry. */
+#define R_386_NUM 44
+
+/* SUN SPARC specific definitions. */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_SPARC_REGISTER 13 /* Global register reserved to app. */
+
+/* Values for Elf64_Ehdr.e_flags. */
+
+#define EF_SPARCV9_MM 3
+#define EF_SPARCV9_TSO 0
+#define EF_SPARCV9_PSO 1
+#define EF_SPARCV9_RMO 2
+#define EF_SPARC_LEDATA 0x800000 /* little endian data */
+#define EF_SPARC_EXT_MASK 0xFFFF00
+#define EF_SPARC_32PLUS 0x000100 /* generic V8+ features */
+#define EF_SPARC_SUN_US1 0x000200 /* Sun UltraSPARC1 extensions */
+#define EF_SPARC_HAL_R1 0x000400 /* HAL R1 extensions */
+#define EF_SPARC_SUN_US3 0x000800 /* Sun UltraSPARCIII extensions */
+
+/* SPARC relocs. */
+
+#define R_SPARC_NONE 0 /* No reloc */
+#define R_SPARC_8 1 /* Direct 8 bit */
+#define R_SPARC_16 2 /* Direct 16 bit */
+#define R_SPARC_32 3 /* Direct 32 bit */
+#define R_SPARC_DISP8 4 /* PC relative 8 bit */
+#define R_SPARC_DISP16 5 /* PC relative 16 bit */
+#define R_SPARC_DISP32 6 /* PC relative 32 bit */
+#define R_SPARC_WDISP30 7 /* PC relative 30 bit shifted */
+#define R_SPARC_WDISP22 8 /* PC relative 22 bit shifted */
+#define R_SPARC_HI22 9 /* High 22 bit */
+#define R_SPARC_22 10 /* Direct 22 bit */
+#define R_SPARC_13 11 /* Direct 13 bit */
+#define R_SPARC_LO10 12 /* Truncated 10 bit */
+#define R_SPARC_GOT10 13 /* Truncated 10 bit GOT entry */
+#define R_SPARC_GOT13 14 /* 13 bit GOT entry */
+#define R_SPARC_GOT22 15 /* 22 bit GOT entry shifted */
+#define R_SPARC_PC10 16 /* PC relative 10 bit truncated */
+#define R_SPARC_PC22 17 /* PC relative 22 bit shifted */
+#define R_SPARC_WPLT30 18 /* 30 bit PC relative PLT address */
+#define R_SPARC_COPY 19 /* Copy symbol at runtime */
+#define R_SPARC_GLOB_DAT 20 /* Create GOT entry */
+#define R_SPARC_JMP_SLOT 21 /* Create PLT entry */
+#define R_SPARC_RELATIVE 22 /* Adjust by program base */
+#define R_SPARC_UA32 23 /* Direct 32 bit unaligned */
+
+/* Additional Sparc64 relocs. */
+
+#define R_SPARC_PLT32 24 /* Direct 32 bit ref to PLT entry */
+#define R_SPARC_HIPLT22 25 /* High 22 bit PLT entry */
+#define R_SPARC_LOPLT10 26 /* Truncated 10 bit PLT entry */
+#define R_SPARC_PCPLT32 27 /* PC rel 32 bit ref to PLT entry */
+#define R_SPARC_PCPLT22 28 /* PC rel high 22 bit PLT entry */
+#define R_SPARC_PCPLT10 29 /* PC rel trunc 10 bit PLT entry */
+#define R_SPARC_10 30 /* Direct 10 bit */
+#define R_SPARC_11 31 /* Direct 11 bit */
+#define R_SPARC_64 32 /* Direct 64 bit */
+#define R_SPARC_OLO10 33 /* 10bit with secondary 13bit addend */
+#define R_SPARC_HH22 34 /* Top 22 bits of direct 64 bit */
+#define R_SPARC_HM10 35 /* High middle 10 bits of ... */
+#define R_SPARC_LM22 36 /* Low middle 22 bits of ... */
+#define R_SPARC_PC_HH22 37 /* Top 22 bits of pc rel 64 bit */
+#define R_SPARC_PC_HM10 38 /* High middle 10 bit of ... */
+#define R_SPARC_PC_LM22 39 /* Low miggle 22 bits of ... */
+#define R_SPARC_WDISP16 40 /* PC relative 16 bit shifted */
+#define R_SPARC_WDISP19 41 /* PC relative 19 bit shifted */
+#define R_SPARC_GLOB_JMP 42 /* was part of v9 ABI but was removed */
+#define R_SPARC_7 43 /* Direct 7 bit */
+#define R_SPARC_5 44 /* Direct 5 bit */
+#define R_SPARC_6 45 /* Direct 6 bit */
+#define R_SPARC_DISP64 46 /* PC relative 64 bit */
+#define R_SPARC_PLT64 47 /* Direct 64 bit ref to PLT entry */
+#define R_SPARC_HIX22 48 /* High 22 bit complemented */
+#define R_SPARC_LOX10 49 /* Truncated 11 bit complemented */
+#define R_SPARC_H44 50 /* Direct high 12 of 44 bit */
+#define R_SPARC_M44 51 /* Direct mid 22 of 44 bit */
+#define R_SPARC_L44 52 /* Direct low 10 of 44 bit */
+#define R_SPARC_REGISTER 53 /* Global register usage */
+#define R_SPARC_UA64 54 /* Direct 64 bit unaligned */
+#define R_SPARC_UA16 55 /* Direct 16 bit unaligned */
+#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_SPARC_GOTDATA_HIX22 80
+#define R_SPARC_GOTDATA_LOX10 81
+#define R_SPARC_GOTDATA_OP_HIX22 82
+#define R_SPARC_GOTDATA_OP_LOX10 83
+#define R_SPARC_GOTDATA_OP 84
+#define R_SPARC_H34 85
+#define R_SPARC_SIZE32 86
+#define R_SPARC_SIZE64 87
+#define R_SPARC_WDISP10 88
+#define R_SPARC_JMP_IREL 248
+#define R_SPARC_IRELATIVE 249
+#define R_SPARC_GNU_VTINHERIT 250
+#define R_SPARC_GNU_VTENTRY 251
+#define R_SPARC_REV32 252
+/* Keep this the last entry. */
+#define R_SPARC_NUM 253
+
+/* For Sparc64, legal values for d_tag of Elf64_Dyn. */
+
+#define DT_SPARC_REGISTER 0x70000001
+#define DT_SPARC_NUM 2
+
+/* MIPS R3000 specific definitions. */
+
+/* Legal values for e_flags field of Elf32_Ehdr. */
+
+#define EF_MIPS_NOREORDER 1 /* A .noreorder directive was used. */
+#define EF_MIPS_PIC 2 /* Contains PIC code. */
+#define EF_MIPS_CPIC 4 /* Uses PIC calling sequence. */
+#define EF_MIPS_XGOT 8
+#define EF_MIPS_64BIT_WHIRL 16
+#define EF_MIPS_ABI2 32
+#define EF_MIPS_ABI_ON32 64
+#define EF_MIPS_FP64 512 /* Uses FP64 (12 callee-saved). */
+#define EF_MIPS_NAN2008 1024 /* Uses IEEE 754-2008 NaN encoding. */
+#define EF_MIPS_ARCH 0xf0000000 /* MIPS architecture level. */
+
+/* Legal values for MIPS architecture level. */
+
+#define EF_MIPS_ARCH_1 0x00000000 /* -mips1 code. */
+#define EF_MIPS_ARCH_2 0x10000000 /* -mips2 code. */
+#define EF_MIPS_ARCH_3 0x20000000 /* -mips3 code. */
+#define EF_MIPS_ARCH_4 0x30000000 /* -mips4 code. */
+#define EF_MIPS_ARCH_5 0x40000000 /* -mips5 code. */
+#define EF_MIPS_ARCH_32 0x50000000 /* MIPS32 code. */
+#define EF_MIPS_ARCH_64 0x60000000 /* MIPS64 code. */
+#define EF_MIPS_ARCH_32R2 0x70000000 /* MIPS32r2 code. */
+#define EF_MIPS_ARCH_64R2 0x80000000 /* MIPS64r2 code. */
+
+/* The following are unofficial names and should not be used. */
+
+#define E_MIPS_ARCH_1 EF_MIPS_ARCH_1
+#define E_MIPS_ARCH_2 EF_MIPS_ARCH_2
+#define E_MIPS_ARCH_3 EF_MIPS_ARCH_3
+#define E_MIPS_ARCH_4 EF_MIPS_ARCH_4
+#define E_MIPS_ARCH_5 EF_MIPS_ARCH_5
+#define E_MIPS_ARCH_32 EF_MIPS_ARCH_32
+#define E_MIPS_ARCH_64 EF_MIPS_ARCH_64
+
+/* Special section indices. */
+
+#define SHN_MIPS_ACOMMON 0xff00 /* Allocated common symbols. */
+#define SHN_MIPS_TEXT 0xff01 /* Allocated test symbols. */
+#define SHN_MIPS_DATA 0xff02 /* Allocated data symbols. */
+#define SHN_MIPS_SCOMMON 0xff03 /* Small common symbols. */
+#define SHN_MIPS_SUNDEFINED 0xff04 /* Small undefined symbols. */
+
+/* Legal values for sh_type field of Elf32_Shdr. */
+
+#define SHT_MIPS_LIBLIST 0x70000000 /* Shared objects used in link. */
+#define SHT_MIPS_MSYM 0x70000001
+#define SHT_MIPS_CONFLICT 0x70000002 /* Conflicting symbols. */
+#define SHT_MIPS_GPTAB 0x70000003 /* Global data area sizes. */
+#define SHT_MIPS_UCODE 0x70000004 /* Reserved for SGI/MIPS compilers */
+#define SHT_MIPS_DEBUG 0x70000005 /* MIPS ECOFF debugging info. */
+#define SHT_MIPS_REGINFO 0x70000006 /* Register usage information. */
+#define SHT_MIPS_PACKAGE 0x70000007
+#define SHT_MIPS_PACKSYM 0x70000008
+#define SHT_MIPS_RELD 0x70000009
+#define SHT_MIPS_IFACE 0x7000000b
+#define SHT_MIPS_CONTENT 0x7000000c
+#define SHT_MIPS_OPTIONS 0x7000000d /* Miscellaneous options. */
+#define SHT_MIPS_SHDR 0x70000010
+#define SHT_MIPS_FDESC 0x70000011
+#define SHT_MIPS_EXTSYM 0x70000012
+#define SHT_MIPS_DENSE 0x70000013
+#define SHT_MIPS_PDESC 0x70000014
+#define SHT_MIPS_LOCSYM 0x70000015
+#define SHT_MIPS_AUXSYM 0x70000016
+#define SHT_MIPS_OPTSYM 0x70000017
+#define SHT_MIPS_LOCSTR 0x70000018
+#define SHT_MIPS_LINE 0x70000019
+#define SHT_MIPS_RFDESC 0x7000001a
+#define SHT_MIPS_DELTASYM 0x7000001b
+#define SHT_MIPS_DELTAINST 0x7000001c
+#define SHT_MIPS_DELTACLASS 0x7000001d
+#define SHT_MIPS_DWARF 0x7000001e /* DWARF debugging information. */
+#define SHT_MIPS_DELTADECL 0x7000001f
+#define SHT_MIPS_SYMBOL_LIB 0x70000020
+#define SHT_MIPS_EVENTS 0x70000021 /* Event section. */
+#define SHT_MIPS_TRANSLATE 0x70000022
+#define SHT_MIPS_PIXIE 0x70000023
+#define SHT_MIPS_XLATE 0x70000024
+#define SHT_MIPS_XLATE_DEBUG 0x70000025
+#define SHT_MIPS_WHIRL 0x70000026
+#define SHT_MIPS_EH_REGION 0x70000027
+#define SHT_MIPS_XLATE_OLD 0x70000028
+#define SHT_MIPS_PDR_EXCEPTION 0x70000029
+#define SHT_MIPS_XHASH 0x7000002b
+
+/* Legal values for sh_flags field of Elf32_Shdr. */
+
+#define SHF_MIPS_GPREL 0x10000000 /* Must be in global data area. */
+#define SHF_MIPS_MERGE 0x20000000
+#define SHF_MIPS_ADDR 0x40000000
+#define SHF_MIPS_STRINGS 0x80000000
+#define SHF_MIPS_NOSTRIP 0x08000000
+#define SHF_MIPS_LOCAL 0x04000000
+#define SHF_MIPS_NAMES 0x02000000
+#define SHF_MIPS_NODUPE 0x01000000
+
+
+/* Symbol tables. */
+
+/* MIPS specific values for `st_other'. */
+#define STO_MIPS_DEFAULT 0x0
+#define STO_MIPS_INTERNAL 0x1
+#define STO_MIPS_HIDDEN 0x2
+#define STO_MIPS_PROTECTED 0x3
+#define STO_MIPS_PLT 0x8
+#define STO_MIPS_SC_ALIGN_UNUSED 0xff
+
+/* MIPS specific values for `st_info'. */
+#define STB_MIPS_SPLIT_COMMON 13
+
+/* Entries found in sections of type SHT_MIPS_GPTAB. */
+
+typedef union
+{
+ struct
+ {
+ Elf32_Word gt_current_g_value; /* -G value used for compilation. */
+ Elf32_Word gt_unused; /* Not used. */
+ } gt_header; /* First entry in section. */
+ struct
+ {
+ Elf32_Word gt_g_value; /* If this value were used for -G. */
+ Elf32_Word gt_bytes; /* This many bytes would be used. */
+ } gt_entry; /* Subsequent entries in section. */
+} Elf32_gptab;
+
+/* Entry found in sections of type SHT_MIPS_REGINFO. */
+
+typedef struct
+{
+ Elf32_Word ri_gprmask; /* General registers used. */
+ Elf32_Word ri_cprmask[4]; /* Coprocessor registers used. */
+ Elf32_Sword ri_gp_value; /* $gp register value. */
+} Elf32_RegInfo;
+
+/* Entries found in sections of type SHT_MIPS_OPTIONS. */
+
+typedef struct
+{
+ unsigned char kind; /* Determines interpretation of the
+ variable part of descriptor. */
+ unsigned char size; /* Size of descriptor, including header. */
+ Elf32_Section section; /* Section header index of section affected,
+ 0 for global options. */
+ Elf32_Word info; /* Kind-specific information. */
+} Elf_Options;
+
+/* Values for `kind' field in Elf_Options. */
+
+#define ODK_NULL 0 /* Undefined. */
+#define ODK_REGINFO 1 /* Register usage information. */
+#define ODK_EXCEPTIONS 2 /* Exception processing options. */
+#define ODK_PAD 3 /* Section padding options. */
+#define ODK_HWPATCH 4 /* Hardware workarounds performed */
+#define ODK_FILL 5 /* record the fill value used by the linker. */
+#define ODK_TAGS 6 /* reserve space for desktop tools to write. */
+#define ODK_HWAND 7 /* HW workarounds. 'AND' bits when merging. */
+#define ODK_HWOR 8 /* HW workarounds. 'OR' bits when merging. */
+
+/* Values for `info' in Elf_Options for ODK_EXCEPTIONS entries. */
+
+#define OEX_FPU_MIN 0x1f /* FPE's which MUST be enabled. */
+#define OEX_FPU_MAX 0x1f00 /* FPE's which MAY be enabled. */
+#define OEX_PAGE0 0x10000 /* page zero must be mapped. */
+#define OEX_SMM 0x20000 /* Force sequential memory mode? */
+#define OEX_FPDBUG 0x40000 /* Force floating point debug mode? */
+#define OEX_PRECISEFP OEX_FPDBUG
+#define OEX_DISMISS 0x80000 /* Dismiss invalid address faults? */
+
+#define OEX_FPU_INVAL 0x10
+#define OEX_FPU_DIV0 0x08
+#define OEX_FPU_OFLO 0x04
+#define OEX_FPU_UFLO 0x02
+#define OEX_FPU_INEX 0x01
+
+/* Masks for `info' in Elf_Options for an ODK_HWPATCH entry. */
+
+#define OHW_R4KEOP 0x1 /* R4000 end-of-page patch. */
+#define OHW_R8KPFETCH 0x2 /* may need R8000 prefetch patch. */
+#define OHW_R5KEOP 0x4 /* R5000 end-of-page patch. */
+#define OHW_R5KCVTL 0x8 /* R5000 cvt.[ds].l bug. clean=1. */
+
+#define OPAD_PREFIX 0x1
+#define OPAD_POSTFIX 0x2
+#define OPAD_SYMBOL 0x4
+
+/* Entry found in `.options' section. */
+
+typedef struct
+{
+ Elf32_Word hwp_flags1; /* Extra flags. */
+ Elf32_Word hwp_flags2; /* Extra flags. */
+} Elf_Options_Hw;
+
+/* Masks for `info' in ElfOptions for ODK_HWAND and ODK_HWOR entries. */
+
+#define OHWA0_R4KEOP_CHECKED 0x00000001
+#define OHWA1_R4KEOP_CLEAN 0x00000002
+
+/* MIPS relocs. */
+
+#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_SHIFT5 16
+#define R_MIPS_SHIFT6 17
+#define R_MIPS_64 18
+#define R_MIPS_GOT_DISP 19
+#define R_MIPS_GOT_PAGE 20
+#define R_MIPS_GOT_OFST 21
+#define R_MIPS_GOT_HI16 22
+#define R_MIPS_GOT_LO16 23
+#define R_MIPS_SUB 24
+#define R_MIPS_INSERT_A 25
+#define R_MIPS_INSERT_B 26
+#define R_MIPS_DELETE 27
+#define R_MIPS_HIGHER 28
+#define R_MIPS_HIGHEST 29
+#define R_MIPS_CALL_HI16 30
+#define R_MIPS_CALL_LO16 31
+#define R_MIPS_SCN_DISP 32
+#define R_MIPS_REL16 33
+#define R_MIPS_ADD_IMMEDIATE 34
+#define R_MIPS_PJUMP 35
+#define R_MIPS_RELGOT 36
+#define R_MIPS_JALR 37
+#define R_MIPS_TLS_DTPMOD32 38 /* Module number 32 bit */
+#define R_MIPS_TLS_DTPREL32 39 /* Module-relative offset 32 bit */
+#define R_MIPS_TLS_DTPMOD64 40 /* Module number 64 bit */
+#define R_MIPS_TLS_DTPREL64 41 /* Module-relative offset 64 bit */
+#define R_MIPS_TLS_GD 42 /* 16 bit GOT offset for GD */
+#define R_MIPS_TLS_LDM 43 /* 16 bit GOT offset for LDM */
+#define R_MIPS_TLS_DTPREL_HI16 44 /* Module-relative offset, high 16 bits */
+#define R_MIPS_TLS_DTPREL_LO16 45 /* Module-relative offset, low 16 bits */
+#define R_MIPS_TLS_GOTTPREL 46 /* 16 bit GOT offset for IE */
+#define R_MIPS_TLS_TPREL32 47 /* TP-relative offset, 32 bit */
+#define R_MIPS_TLS_TPREL64 48 /* TP-relative offset, 64 bit */
+#define R_MIPS_TLS_TPREL_HI16 49 /* TP-relative offset, high 16 bits */
+#define R_MIPS_TLS_TPREL_LO16 50 /* TP-relative offset, low 16 bits */
+#define R_MIPS_GLOB_DAT 51
+#define R_MIPS_COPY 126
+#define R_MIPS_JUMP_SLOT 127
+/* Keep this the last entry. */
+#define R_MIPS_NUM 128
+
+/* Legal values for p_type field of Elf32_Phdr. */
+
+#define PT_MIPS_REGINFO 0x70000000 /* Register usage information. */
+#define PT_MIPS_RTPROC 0x70000001 /* Runtime procedure table. */
+#define PT_MIPS_OPTIONS 0x70000002
+#define PT_MIPS_ABIFLAGS 0x70000003 /* FP mode requirement. */
+
+/* Special program header types. */
+
+#define PF_MIPS_LOCAL 0x10000000
+
+/* Legal values for d_tag field of Elf32_Dyn. */
+
+#define DT_MIPS_RLD_VERSION 0x70000001 /* Runtime linker interface version */
+#define DT_MIPS_TIME_STAMP 0x70000002 /* Timestamp */
+#define DT_MIPS_ICHECKSUM 0x70000003 /* Checksum */
+#define DT_MIPS_IVERSION 0x70000004 /* Version string (string tbl index) */
+#define DT_MIPS_FLAGS 0x70000005 /* Flags */
+#define DT_MIPS_BASE_ADDRESS 0x70000006 /* Base address */
+#define DT_MIPS_MSYM 0x70000007
+#define DT_MIPS_CONFLICT 0x70000008 /* Address of CONFLICT section */
+#define DT_MIPS_LIBLIST 0x70000009 /* Address of LIBLIST section */
+#define DT_MIPS_LOCAL_GOTNO 0x7000000a /* Number of local GOT entries */
+#define DT_MIPS_CONFLICTNO 0x7000000b /* Number of CONFLICT entries */
+#define DT_MIPS_LIBLISTNO 0x70000010 /* Number of LIBLIST entries */
+#define DT_MIPS_SYMTABNO 0x70000011 /* Number of DYNSYM entries */
+#define DT_MIPS_UNREFEXTNO 0x70000012 /* First external DYNSYM */
+#define DT_MIPS_GOTSYM 0x70000013 /* First GOT entry in DYNSYM */
+#define DT_MIPS_HIPAGENO 0x70000014 /* Number of GOT page table entries */
+#define DT_MIPS_RLD_MAP 0x70000016 /* Address of run time loader map. */
+#define DT_MIPS_DELTA_CLASS 0x70000017 /* Delta C++ class definition. */
+#define DT_MIPS_DELTA_CLASS_NO 0x70000018 /* Number of entries in
+ DT_MIPS_DELTA_CLASS. */
+#define DT_MIPS_DELTA_INSTANCE 0x70000019 /* Delta C++ class instances. */
+#define DT_MIPS_DELTA_INSTANCE_NO 0x7000001a /* Number of entries in
+ DT_MIPS_DELTA_INSTANCE. */
+#define DT_MIPS_DELTA_RELOC 0x7000001b /* Delta relocations. */
+#define DT_MIPS_DELTA_RELOC_NO 0x7000001c /* Number of entries in
+ DT_MIPS_DELTA_RELOC. */
+#define DT_MIPS_DELTA_SYM 0x7000001d /* Delta symbols that Delta
+ relocations refer to. */
+#define DT_MIPS_DELTA_SYM_NO 0x7000001e /* Number of entries in
+ DT_MIPS_DELTA_SYM. */
+#define DT_MIPS_DELTA_CLASSSYM 0x70000020 /* Delta symbols that hold the
+ class declaration. */
+#define DT_MIPS_DELTA_CLASSSYM_NO 0x70000021 /* Number of entries in
+ DT_MIPS_DELTA_CLASSSYM. */
+#define DT_MIPS_CXX_FLAGS 0x70000022 /* Flags indicating for C++ flavor. */
+#define DT_MIPS_PIXIE_INIT 0x70000023
+#define DT_MIPS_SYMBOL_LIB 0x70000024
+#define DT_MIPS_LOCALPAGE_GOTIDX 0x70000025
+#define DT_MIPS_LOCAL_GOTIDX 0x70000026
+#define DT_MIPS_HIDDEN_GOTIDX 0x70000027
+#define DT_MIPS_PROTECTED_GOTIDX 0x70000028
+#define DT_MIPS_OPTIONS 0x70000029 /* Address of .options. */
+#define DT_MIPS_INTERFACE 0x7000002a /* Address of .interface. */
+#define DT_MIPS_DYNSTR_ALIGN 0x7000002b
+#define DT_MIPS_INTERFACE_SIZE 0x7000002c /* Size of the .interface section. */
+#define DT_MIPS_RLD_TEXT_RESOLVE_ADDR 0x7000002d /* Address of rld_text_rsolve
+ function stored in GOT. */
+#define DT_MIPS_PERF_SUFFIX 0x7000002e /* Default suffix of dso to be added
+ by rld on dlopen() calls. */
+#define DT_MIPS_COMPACT_SIZE 0x7000002f /* (O32)Size of compact rel section. */
+#define DT_MIPS_GP_VALUE 0x70000030 /* GP value for aux GOTs. */
+#define DT_MIPS_AUX_DYNAMIC 0x70000031 /* Address of aux .dynamic. */
+/* The address of .got.plt in an executable using the new non-PIC ABI. */
+#define DT_MIPS_PLTGOT 0x70000032
+/* The base of the PLT in an executable using the new non-PIC ABI if that
+ PLT is writable. For a non-writable PLT, this is omitted or has a zero
+ value. */
+#define DT_MIPS_RWPLT 0x70000034
+/* An alternative description of the classic MIPS RLD_MAP that is usable
+ in a PIE as it stores a relative offset from the address of the tag
+ rather than an absolute address. */
+#define DT_MIPS_RLD_MAP_REL 0x70000035
+/* GNU-style hash table with xlat. */
+#define DT_MIPS_XHASH 0x70000036
+#define DT_MIPS_NUM 0x37
+
+/* Legal values for DT_MIPS_FLAGS Elf32_Dyn entry. */
+
+#define RHF_NONE 0 /* No flags */
+#define RHF_QUICKSTART (1 << 0) /* Use quickstart */
+#define RHF_NOTPOT (1 << 1) /* Hash size not power of 2 */
+#define RHF_NO_LIBRARY_REPLACEMENT (1 << 2) /* Ignore LD_LIBRARY_PATH */
+#define RHF_NO_MOVE (1 << 3)
+#define RHF_SGI_ONLY (1 << 4)
+#define RHF_GUARANTEE_INIT (1 << 5)
+#define RHF_DELTA_C_PLUS_PLUS (1 << 6)
+#define RHF_GUARANTEE_START_INIT (1 << 7)
+#define RHF_PIXIE (1 << 8)
+#define RHF_DEFAULT_DELAY_LOAD (1 << 9)
+#define RHF_REQUICKSTART (1 << 10)
+#define RHF_REQUICKSTARTED (1 << 11)
+#define RHF_CORD (1 << 12)
+#define RHF_NO_UNRES_UNDEF (1 << 13)
+#define RHF_RLD_ORDER_SAFE (1 << 14)
+
+/* Entries found in sections of type SHT_MIPS_LIBLIST. */
+
+typedef struct
+{
+ Elf32_Word l_name; /* Name (string table index) */
+ Elf32_Word l_time_stamp; /* Timestamp */
+ Elf32_Word l_checksum; /* Checksum */
+ Elf32_Word l_version; /* Interface version */
+ Elf32_Word l_flags; /* Flags */
+} Elf32_Lib;
+
+typedef struct
+{
+ Elf64_Word l_name; /* Name (string table index) */
+ Elf64_Word l_time_stamp; /* Timestamp */
+ Elf64_Word l_checksum; /* Checksum */
+ Elf64_Word l_version; /* Interface version */
+ Elf64_Word l_flags; /* Flags */
+} Elf64_Lib;
+
+
+/* Legal values for l_flags. */
+
+#define LL_NONE 0
+#define LL_EXACT_MATCH (1 << 0) /* Require exact match */
+#define LL_IGNORE_INT_VER (1 << 1) /* Ignore interface version */
+#define LL_REQUIRE_MINOR (1 << 2)
+#define LL_EXPORTS (1 << 3)
+#define LL_DELAY_LOAD (1 << 4)
+#define LL_DELTA (1 << 5)
+
+/* Entries found in sections of type SHT_MIPS_CONFLICT. */
+
+typedef Elf32_Addr Elf32_Conflict;
+
+typedef struct
+{
+ /* Version of flags structure. */
+ Elf32_Half version;
+ /* The level of the ISA: 1-5, 32, 64. */
+ unsigned char isa_level;
+ /* The revision of ISA: 0 for MIPS V and below, 1-n otherwise. */
+ unsigned char isa_rev;
+ /* The size of general purpose registers. */
+ unsigned char gpr_size;
+ /* The size of co-processor 1 registers. */
+ unsigned char cpr1_size;
+ /* The size of co-processor 2 registers. */
+ unsigned char cpr2_size;
+ /* The floating-point ABI. */
+ unsigned char fp_abi;
+ /* Processor-specific extension. */
+ Elf32_Word isa_ext;
+ /* Mask of ASEs used. */
+ Elf32_Word ases;
+ /* Mask of general flags. */
+ Elf32_Word flags1;
+ Elf32_Word flags2;
+} Elf_MIPS_ABIFlags_v0;
+
+/* Values for the register size bytes of an abi flags structure. */
+
+#define MIPS_AFL_REG_NONE 0x00 /* No registers. */
+#define MIPS_AFL_REG_32 0x01 /* 32-bit registers. */
+#define MIPS_AFL_REG_64 0x02 /* 64-bit registers. */
+#define MIPS_AFL_REG_128 0x03 /* 128-bit registers. */
+
+/* Masks for the ases word of an ABI flags structure. */
+
+#define MIPS_AFL_ASE_DSP 0x00000001 /* DSP ASE. */
+#define MIPS_AFL_ASE_DSPR2 0x00000002 /* DSP R2 ASE. */
+#define MIPS_AFL_ASE_EVA 0x00000004 /* Enhanced VA Scheme. */
+#define MIPS_AFL_ASE_MCU 0x00000008 /* MCU (MicroController) ASE. */
+#define MIPS_AFL_ASE_MDMX 0x00000010 /* MDMX ASE. */
+#define MIPS_AFL_ASE_MIPS3D 0x00000020 /* MIPS-3D ASE. */
+#define MIPS_AFL_ASE_MT 0x00000040 /* MT ASE. */
+#define MIPS_AFL_ASE_SMARTMIPS 0x00000080 /* SmartMIPS ASE. */
+#define MIPS_AFL_ASE_VIRT 0x00000100 /* VZ ASE. */
+#define MIPS_AFL_ASE_MSA 0x00000200 /* MSA ASE. */
+#define MIPS_AFL_ASE_MIPS16 0x00000400 /* MIPS16 ASE. */
+#define MIPS_AFL_ASE_MICROMIPS 0x00000800 /* MICROMIPS ASE. */
+#define MIPS_AFL_ASE_XPA 0x00001000 /* XPA ASE. */
+#define MIPS_AFL_ASE_MASK 0x00001fff /* All ASEs. */
+
+/* Values for the isa_ext word of an ABI flags structure. */
+
+#define MIPS_AFL_EXT_XLR 1 /* RMI Xlr instruction. */
+#define MIPS_AFL_EXT_OCTEON2 2 /* Cavium Networks Octeon2. */
+#define MIPS_AFL_EXT_OCTEONP 3 /* Cavium Networks OcteonP. */
+#define MIPS_AFL_EXT_LOONGSON_3A 4 /* Loongson 3A. */
+#define MIPS_AFL_EXT_OCTEON 5 /* Cavium Networks Octeon. */
+#define MIPS_AFL_EXT_5900 6 /* MIPS R5900 instruction. */
+#define MIPS_AFL_EXT_4650 7 /* MIPS R4650 instruction. */
+#define MIPS_AFL_EXT_4010 8 /* LSI R4010 instruction. */
+#define MIPS_AFL_EXT_4100 9 /* NEC VR4100 instruction. */
+#define MIPS_AFL_EXT_3900 10 /* Toshiba R3900 instruction. */
+#define MIPS_AFL_EXT_10000 11 /* MIPS R10000 instruction. */
+#define MIPS_AFL_EXT_SB1 12 /* Broadcom SB-1 instruction. */
+#define MIPS_AFL_EXT_4111 13 /* NEC VR4111/VR4181 instruction. */
+#define MIPS_AFL_EXT_4120 14 /* NEC VR4120 instruction. */
+#define MIPS_AFL_EXT_5400 15 /* NEC VR5400 instruction. */
+#define MIPS_AFL_EXT_5500 16 /* NEC VR5500 instruction. */
+#define MIPS_AFL_EXT_LOONGSON_2E 17 /* ST Microelectronics Loongson 2E. */
+#define MIPS_AFL_EXT_LOONGSON_2F 18 /* ST Microelectronics Loongson 2F. */
+
+/* Masks for the flags1 word of an ABI flags structure. */
+#define MIPS_AFL_FLAGS1_ODDSPREG 1 /* Uses odd single-precision registers. */
+
+/* Object attribute values. */
+enum
+{
+ /* Not tagged or not using any ABIs affected by the differences. */
+ Val_GNU_MIPS_ABI_FP_ANY = 0,
+ /* Using hard-float -mdouble-float. */
+ Val_GNU_MIPS_ABI_FP_DOUBLE = 1,
+ /* Using hard-float -msingle-float. */
+ Val_GNU_MIPS_ABI_FP_SINGLE = 2,
+ /* Using soft-float. */
+ Val_GNU_MIPS_ABI_FP_SOFT = 3,
+ /* Using -mips32r2 -mfp64. */
+ Val_GNU_MIPS_ABI_FP_OLD_64 = 4,
+ /* Using -mfpxx. */
+ Val_GNU_MIPS_ABI_FP_XX = 5,
+ /* Using -mips32r2 -mfp64. */
+ Val_GNU_MIPS_ABI_FP_64 = 6,
+ /* Using -mips32r2 -mfp64 -mno-odd-spreg. */
+ Val_GNU_MIPS_ABI_FP_64A = 7,
+ /* Maximum allocated FP ABI value. */
+ Val_GNU_MIPS_ABI_FP_MAX = 7
+};
+
+/* HPPA specific definitions. */
+
+/* Legal values for e_flags field of Elf32_Ehdr. */
+
+#define EF_PARISC_TRAPNIL 0x00010000 /* Trap nil pointer dereference. */
+#define EF_PARISC_EXT 0x00020000 /* Program uses arch. extensions. */
+#define EF_PARISC_LSB 0x00040000 /* Program expects little endian. */
+#define EF_PARISC_WIDE 0x00080000 /* Program expects wide mode. */
+#define EF_PARISC_NO_KABP 0x00100000 /* No kernel assisted branch
+ prediction. */
+#define EF_PARISC_LAZYSWAP 0x00400000 /* Allow lazy swapping. */
+#define EF_PARISC_ARCH 0x0000ffff /* Architecture version. */
+
+/* Defined values for `e_flags & EF_PARISC_ARCH' are: */
+
+#define EFA_PARISC_1_0 0x020b /* PA-RISC 1.0 big-endian. */
+#define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */
+#define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */
+
+/* Additional section indices. */
+
+#define SHN_PARISC_ANSI_COMMON 0xff00 /* Section for tentatively declared
+ symbols in ANSI C. */
+#define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */
+
+/* Legal values for sh_type field of Elf32_Shdr. */
+
+#define SHT_PARISC_EXT 0x70000000 /* Contains product specific ext. */
+#define SHT_PARISC_UNWIND 0x70000001 /* Unwind information. */
+#define SHT_PARISC_DOC 0x70000002 /* Debug info for optimized code. */
+
+/* Legal values for sh_flags field of Elf32_Shdr. */
+
+#define SHF_PARISC_SHORT 0x20000000 /* Section with short addressing. */
+#define SHF_PARISC_HUGE 0x40000000 /* Section far from gp. */
+#define SHF_PARISC_SBP 0x80000000 /* Static branch prediction code. */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_PARISC_MILLICODE 13 /* Millicode function entry point. */
+
+#define STT_HP_OPAQUE (STT_LOOS + 0x1)
+#define STT_HP_STUB (STT_LOOS + 0x2)
+
+/* HPPA relocs. */
+
+#define R_PARISC_NONE 0 /* No reloc. */
+#define R_PARISC_DIR32 1 /* Direct 32-bit reference. */
+#define R_PARISC_DIR21L 2 /* Left 21 bits of eff. address. */
+#define R_PARISC_DIR17R 3 /* Right 17 bits of eff. address. */
+#define R_PARISC_DIR17F 4 /* 17 bits of eff. address. */
+#define R_PARISC_DIR14R 6 /* Right 14 bits of eff. address. */
+#define R_PARISC_PCREL32 9 /* 32-bit rel. address. */
+#define R_PARISC_PCREL21L 10 /* Left 21 bits of rel. address. */
+#define R_PARISC_PCREL17R 11 /* Right 17 bits of rel. address. */
+#define R_PARISC_PCREL17F 12 /* 17 bits of rel. address. */
+#define R_PARISC_PCREL14R 14 /* Right 14 bits of rel. address. */
+#define R_PARISC_DPREL21L 18 /* Left 21 bits of rel. address. */
+#define R_PARISC_DPREL14R 22 /* Right 14 bits of rel. address. */
+#define R_PARISC_GPREL21L 26 /* GP-relative, left 21 bits. */
+#define R_PARISC_GPREL14R 30 /* GP-relative, right 14 bits. */
+#define R_PARISC_LTOFF21L 34 /* LT-relative, left 21 bits. */
+#define R_PARISC_LTOFF14R 38 /* LT-relative, right 14 bits. */
+#define R_PARISC_SECREL32 41 /* 32 bits section rel. address. */
+#define R_PARISC_SEGBASE 48 /* No relocation, set segment base. */
+#define R_PARISC_SEGREL32 49 /* 32 bits segment rel. address. */
+#define R_PARISC_PLTOFF21L 50 /* PLT rel. address, left 21 bits. */
+#define R_PARISC_PLTOFF14R 54 /* PLT rel. address, right 14 bits. */
+#define R_PARISC_LTOFF_FPTR32 57 /* 32 bits LT-rel. function pointer. */
+#define R_PARISC_LTOFF_FPTR21L 58 /* LT-rel. fct ptr, left 21 bits. */
+#define R_PARISC_LTOFF_FPTR14R 62 /* LT-rel. fct ptr, right 14 bits. */
+#define R_PARISC_FPTR64 64 /* 64 bits function address. */
+#define R_PARISC_PLABEL32 65 /* 32 bits function address. */
+#define R_PARISC_PLABEL21L 66 /* Left 21 bits of fdesc address. */
+#define R_PARISC_PLABEL14R 70 /* Right 14 bits of fdesc address. */
+#define R_PARISC_PCREL64 72 /* 64 bits PC-rel. address. */
+#define R_PARISC_PCREL22F 74 /* 22 bits PC-rel. address. */
+#define R_PARISC_PCREL14WR 75 /* PC-rel. address, right 14 bits. */
+#define R_PARISC_PCREL14DR 76 /* PC rel. address, right 14 bits. */
+#define R_PARISC_PCREL16F 77 /* 16 bits PC-rel. address. */
+#define R_PARISC_PCREL16WF 78 /* 16 bits PC-rel. address. */
+#define R_PARISC_PCREL16DF 79 /* 16 bits PC-rel. address. */
+#define R_PARISC_DIR64 80 /* 64 bits of eff. address. */
+#define R_PARISC_DIR14WR 83 /* 14 bits of eff. address. */
+#define R_PARISC_DIR14DR 84 /* 14 bits of eff. address. */
+#define R_PARISC_DIR16F 85 /* 16 bits of eff. address. */
+#define R_PARISC_DIR16WF 86 /* 16 bits of eff. address. */
+#define R_PARISC_DIR16DF 87 /* 16 bits of eff. address. */
+#define R_PARISC_GPREL64 88 /* 64 bits of GP-rel. address. */
+#define R_PARISC_GPREL14WR 91 /* GP-rel. address, right 14 bits. */
+#define R_PARISC_GPREL14DR 92 /* GP-rel. address, right 14 bits. */
+#define R_PARISC_GPREL16F 93 /* 16 bits GP-rel. address. */
+#define R_PARISC_GPREL16WF 94 /* 16 bits GP-rel. address. */
+#define R_PARISC_GPREL16DF 95 /* 16 bits GP-rel. address. */
+#define R_PARISC_LTOFF64 96 /* 64 bits LT-rel. address. */
+#define R_PARISC_LTOFF14WR 99 /* LT-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF14DR 100 /* LT-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF16F 101 /* 16 bits LT-rel. address. */
+#define R_PARISC_LTOFF16WF 102 /* 16 bits LT-rel. address. */
+#define R_PARISC_LTOFF16DF 103 /* 16 bits LT-rel. address. */
+#define R_PARISC_SECREL64 104 /* 64 bits section rel. address. */
+#define R_PARISC_SEGREL64 112 /* 64 bits segment rel. address. */
+#define R_PARISC_PLTOFF14WR 115 /* PLT-rel. address, right 14 bits. */
+#define R_PARISC_PLTOFF14DR 116 /* PLT-rel. address, right 14 bits. */
+#define R_PARISC_PLTOFF16F 117 /* 16 bits LT-rel. address. */
+#define R_PARISC_PLTOFF16WF 118 /* 16 bits PLT-rel. address. */
+#define R_PARISC_PLTOFF16DF 119 /* 16 bits PLT-rel. address. */
+#define R_PARISC_LTOFF_FPTR64 120 /* 64 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR14WR 123 /* LT-rel. fct. ptr., right 14 bits. */
+#define R_PARISC_LTOFF_FPTR14DR 124 /* LT-rel. fct. ptr., right 14 bits. */
+#define R_PARISC_LTOFF_FPTR16F 125 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR16WF 126 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR16DF 127 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LORESERVE 128
+#define R_PARISC_COPY 128 /* Copy relocation. */
+#define R_PARISC_IPLT 129 /* Dynamic reloc, imported PLT */
+#define R_PARISC_EPLT 130 /* Dynamic reloc, exported PLT */
+#define R_PARISC_TPREL32 153 /* 32 bits TP-rel. address. */
+#define R_PARISC_TPREL21L 154 /* TP-rel. address, left 21 bits. */
+#define R_PARISC_TPREL14R 158 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF_TP21L 162 /* LT-TP-rel. address, left 21 bits. */
+#define R_PARISC_LTOFF_TP14R 166 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP14F 167 /* 14 bits LT-TP-rel. address. */
+#define R_PARISC_TPREL64 216 /* 64 bits TP-rel. address. */
+#define R_PARISC_TPREL14WR 219 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_TPREL14DR 220 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_TPREL16F 221 /* 16 bits TP-rel. address. */
+#define R_PARISC_TPREL16WF 222 /* 16 bits TP-rel. address. */
+#define R_PARISC_TPREL16DF 223 /* 16 bits TP-rel. address. */
+#define R_PARISC_LTOFF_TP64 224 /* 64 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP14WR 227 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP14DR 228 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP16F 229 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP16WF 230 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP16DF 231 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_GNU_VTENTRY 232
+#define R_PARISC_GNU_VTINHERIT 233
+#define R_PARISC_TLS_GD21L 234 /* GD 21-bit left. */
+#define R_PARISC_TLS_GD14R 235 /* GD 14-bit right. */
+#define R_PARISC_TLS_GDCALL 236 /* GD call to __t_g_a. */
+#define R_PARISC_TLS_LDM21L 237 /* LD module 21-bit left. */
+#define R_PARISC_TLS_LDM14R 238 /* LD module 14-bit right. */
+#define R_PARISC_TLS_LDMCALL 239 /* LD module call to __t_g_a. */
+#define R_PARISC_TLS_LDO21L 240 /* LD offset 21-bit left. */
+#define R_PARISC_TLS_LDO14R 241 /* LD offset 14-bit right. */
+#define R_PARISC_TLS_DTPMOD32 242 /* DTP module 32-bit. */
+#define R_PARISC_TLS_DTPMOD64 243 /* DTP module 64-bit. */
+#define R_PARISC_TLS_DTPOFF32 244 /* DTP offset 32-bit. */
+#define R_PARISC_TLS_DTPOFF64 245 /* DTP offset 32-bit. */
+#define R_PARISC_TLS_LE21L R_PARISC_TPREL21L
+#define R_PARISC_TLS_LE14R R_PARISC_TPREL14R
+#define R_PARISC_TLS_IE21L R_PARISC_LTOFF_TP21L
+#define R_PARISC_TLS_IE14R R_PARISC_LTOFF_TP14R
+#define R_PARISC_TLS_TPREL32 R_PARISC_TPREL32
+#define R_PARISC_TLS_TPREL64 R_PARISC_TPREL64
+#define R_PARISC_HIRESERVE 255
+
+/* Legal values for p_type field of Elf32_Phdr/Elf64_Phdr. */
+
+#define PT_HP_TLS (PT_LOOS + 0x0)
+#define PT_HP_CORE_NONE (PT_LOOS + 0x1)
+#define PT_HP_CORE_VERSION (PT_LOOS + 0x2)
+#define PT_HP_CORE_KERNEL (PT_LOOS + 0x3)
+#define PT_HP_CORE_COMM (PT_LOOS + 0x4)
+#define PT_HP_CORE_PROC (PT_LOOS + 0x5)
+#define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6)
+#define PT_HP_CORE_STACK (PT_LOOS + 0x7)
+#define PT_HP_CORE_SHM (PT_LOOS + 0x8)
+#define PT_HP_CORE_MMF (PT_LOOS + 0x9)
+#define PT_HP_PARALLEL (PT_LOOS + 0x10)
+#define PT_HP_FASTBIND (PT_LOOS + 0x11)
+#define PT_HP_OPT_ANNOT (PT_LOOS + 0x12)
+#define PT_HP_HSL_ANNOT (PT_LOOS + 0x13)
+#define PT_HP_STACK (PT_LOOS + 0x14)
+
+#define PT_PARISC_ARCHEXT 0x70000000
+#define PT_PARISC_UNWIND 0x70000001
+
+/* Legal values for p_flags field of Elf32_Phdr/Elf64_Phdr. */
+
+#define PF_PARISC_SBP 0x08000000
+
+#define PF_HP_PAGE_SIZE 0x00100000
+#define PF_HP_FAR_SHARED 0x00200000
+#define PF_HP_NEAR_SHARED 0x00400000
+#define PF_HP_CODE 0x01000000
+#define PF_HP_MODIFY 0x02000000
+#define PF_HP_LAZYSWAP 0x04000000
+#define PF_HP_SBP 0x08000000
+
+
+/* Alpha specific definitions. */
+
+/* Legal values for e_flags field of Elf64_Ehdr. */
+
+#define EF_ALPHA_32BIT 1 /* All addresses must be < 2GB. */
+#define EF_ALPHA_CANRELAX 2 /* Relocations for relaxing exist. */
+
+/* Legal values for sh_type field of Elf64_Shdr. */
+
+/* These two are primerily concerned with ECOFF debugging info. */
+#define SHT_ALPHA_DEBUG 0x70000001
+#define SHT_ALPHA_REGINFO 0x70000002
+
+/* Legal values for sh_flags field of Elf64_Shdr. */
+
+#define SHF_ALPHA_GPREL 0x10000000
+
+/* Legal values for st_other field of Elf64_Sym. */
+#define STO_ALPHA_NOPV 0x80 /* No PV required. */
+#define STO_ALPHA_STD_GPLOAD 0x88 /* PV only used for initial ldgp. */
+
+/* Alpha relocs. */
+
+#define R_ALPHA_NONE 0 /* No reloc */
+#define R_ALPHA_REFLONG 1 /* Direct 32 bit */
+#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */
+#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */
+#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */
+#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */
+#define R_ALPHA_GPDISP 6 /* Add displacement to GP */
+#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */
+#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */
+#define R_ALPHA_SREL16 9 /* PC relative 16 bit */
+#define R_ALPHA_SREL32 10 /* PC relative 32 bit */
+#define R_ALPHA_SREL64 11 /* PC relative 64 bit */
+#define R_ALPHA_GPRELHIGH 17 /* GP relative 32 bit, high 16 bits */
+#define R_ALPHA_GPRELLOW 18 /* GP relative 32 bit, low 16 bits */
+#define R_ALPHA_GPREL16 19 /* GP relative 16 bit */
+#define R_ALPHA_COPY 24 /* Copy symbol at runtime */
+#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */
+#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */
+#define R_ALPHA_RELATIVE 27 /* Adjust by program base */
+#define R_ALPHA_TLS_GD_HI 28
+#define R_ALPHA_TLSGD 29
+#define R_ALPHA_TLS_LDM 30
+#define R_ALPHA_DTPMOD64 31
+#define R_ALPHA_GOTDTPREL 32
+#define R_ALPHA_DTPREL64 33
+#define R_ALPHA_DTPRELHI 34
+#define R_ALPHA_DTPRELLO 35
+#define R_ALPHA_DTPREL16 36
+#define R_ALPHA_GOTTPREL 37
+#define R_ALPHA_TPREL64 38
+#define R_ALPHA_TPRELHI 39
+#define R_ALPHA_TPRELLO 40
+#define R_ALPHA_TPREL16 41
+/* Keep this the last entry. */
+#define R_ALPHA_NUM 46
+
+/* Magic values of the LITUSE relocation addend. */
+#define LITUSE_ALPHA_ADDR 0
+#define LITUSE_ALPHA_BASE 1
+#define LITUSE_ALPHA_BYTOFF 2
+#define LITUSE_ALPHA_JSR 3
+#define LITUSE_ALPHA_TLS_GD 4
+#define LITUSE_ALPHA_TLS_LDM 5
+
+/* Legal values for d_tag of Elf64_Dyn. */
+#define DT_ALPHA_PLTRO (DT_LOPROC + 0)
+#define DT_ALPHA_NUM 1
+
+/* PowerPC specific declarations */
+
+/* Values for Elf32/64_Ehdr.e_flags. */
+#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */
+
+/* Cygnus local bits below */
+#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/
+#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib
+ flag */
+
+/* PowerPC relocations defined by the ABIs */
+#define R_PPC_NONE 0
+#define R_PPC_ADDR32 1 /* 32bit absolute address */
+#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */
+#define R_PPC_ADDR16 3 /* 16bit absolute address */
+#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */
+#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */
+#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */
+#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */
+#define R_PPC_ADDR14_BRTAKEN 8
+#define R_PPC_ADDR14_BRNTAKEN 9
+#define R_PPC_REL24 10 /* PC relative 26 bit */
+#define R_PPC_REL14 11 /* PC relative 16 bit */
+#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
+
+/* PowerPC relocations defined for the TLS access ABI. */
+#define R_PPC_TLS 67 /* none (sym+add)@tls */
+#define R_PPC_DTPMOD32 68 /* word32 (sym+add)@dtpmod */
+#define R_PPC_TPREL16 69 /* half16* (sym+add)@tprel */
+#define R_PPC_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */
+#define R_PPC_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */
+#define R_PPC_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */
+#define R_PPC_TPREL32 73 /* word32 (sym+add)@tprel */
+#define R_PPC_DTPREL16 74 /* half16* (sym+add)@dtprel */
+#define R_PPC_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */
+#define R_PPC_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */
+#define R_PPC_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */
+#define R_PPC_DTPREL32 78 /* word32 (sym+add)@dtprel */
+#define R_PPC_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */
+#define R_PPC_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */
+#define R_PPC_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */
+#define R_PPC_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */
+#define R_PPC_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */
+#define R_PPC_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */
+#define R_PPC_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */
+#define R_PPC_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */
+#define R_PPC_GOT_TPREL16 87 /* half16* (sym+add)@got@tprel */
+#define R_PPC_GOT_TPREL16_LO 88 /* half16 (sym+add)@got@tprel@l */
+#define R_PPC_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */
+#define R_PPC_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */
+#define R_PPC_GOT_DTPREL16 91 /* half16* (sym+add)@got@dtprel */
+#define R_PPC_GOT_DTPREL16_LO 92 /* half16* (sym+add)@got@dtprel@l */
+#define R_PPC_GOT_DTPREL16_HI 93 /* half16* (sym+add)@got@dtprel@h */
+#define R_PPC_GOT_DTPREL16_HA 94 /* half16* (sym+add)@got@dtprel@ha */
+#define R_PPC_TLSGD 95 /* none (sym+add)@tlsgd */
+#define R_PPC_TLSLD 96 /* none (sym+add)@tlsld */
+
+/* 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 /* 16 bit offset in SDA */
+#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 /* 16 bit relative offset in SDA */
+
+/* Diab tool relocations. */
+#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */
+#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */
+#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */
+#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */
+#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */
+#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */
+
+/* GNU extension to support local ifunc. */
+#define R_PPC_IRELATIVE 248
+
+/* GNU relocs used in PIC code sequences. */
+#define R_PPC_REL16 249 /* half16 (sym+add-.) */
+#define R_PPC_REL16_LO 250 /* half16 (sym+add-.)@l */
+#define R_PPC_REL16_HI 251 /* half16 (sym+add-.)@h */
+#define R_PPC_REL16_HA 252 /* half16 (sym+add-.)@ha */
+
+/* This is a phony reloc to handle any old fashioned TOC16 references
+ that may still be in object files. */
+#define R_PPC_TOC16 255
+
+/* PowerPC specific values for the Dyn d_tag field. */
+#define DT_PPC_GOT (DT_LOPROC + 0)
+#define DT_PPC_OPT (DT_LOPROC + 1)
+#define DT_PPC_NUM 2
+
+/* PowerPC specific values for the DT_PPC_OPT Dyn entry. */
+#define PPC_OPT_TLS 1
+
+/* PowerPC64 relocations defined by the ABIs */
+#define R_PPC64_NONE R_PPC_NONE
+#define R_PPC64_ADDR32 R_PPC_ADDR32 /* 32bit absolute address */
+#define R_PPC64_ADDR24 R_PPC_ADDR24 /* 26bit address, word aligned */
+#define R_PPC64_ADDR16 R_PPC_ADDR16 /* 16bit absolute address */
+#define R_PPC64_ADDR16_LO R_PPC_ADDR16_LO /* lower 16bits of address */
+#define R_PPC64_ADDR16_HI R_PPC_ADDR16_HI /* high 16bits of address. */
+#define R_PPC64_ADDR16_HA R_PPC_ADDR16_HA /* adjusted high 16bits. */
+#define R_PPC64_ADDR14 R_PPC_ADDR14 /* 16bit address, word aligned */
+#define R_PPC64_ADDR14_BRTAKEN R_PPC_ADDR14_BRTAKEN
+#define R_PPC64_ADDR14_BRNTAKEN R_PPC_ADDR14_BRNTAKEN
+#define R_PPC64_REL24 R_PPC_REL24 /* PC-rel. 26 bit, word aligned */
+#define R_PPC64_REL14 R_PPC_REL14 /* PC relative 16 bit */
+#define R_PPC64_REL14_BRTAKEN R_PPC_REL14_BRTAKEN
+#define R_PPC64_REL14_BRNTAKEN R_PPC_REL14_BRNTAKEN
+#define R_PPC64_GOT16 R_PPC_GOT16
+#define R_PPC64_GOT16_LO R_PPC_GOT16_LO
+#define R_PPC64_GOT16_HI R_PPC_GOT16_HI
+#define R_PPC64_GOT16_HA R_PPC_GOT16_HA
+
+#define R_PPC64_COPY R_PPC_COPY
+#define R_PPC64_GLOB_DAT R_PPC_GLOB_DAT
+#define R_PPC64_JMP_SLOT R_PPC_JMP_SLOT
+#define R_PPC64_RELATIVE R_PPC_RELATIVE
+
+#define R_PPC64_UADDR32 R_PPC_UADDR32
+#define R_PPC64_UADDR16 R_PPC_UADDR16
+#define R_PPC64_REL32 R_PPC_REL32
+#define R_PPC64_PLT32 R_PPC_PLT32
+#define R_PPC64_PLTREL32 R_PPC_PLTREL32
+#define R_PPC64_PLT16_LO R_PPC_PLT16_LO
+#define R_PPC64_PLT16_HI R_PPC_PLT16_HI
+#define R_PPC64_PLT16_HA R_PPC_PLT16_HA
+
+#define R_PPC64_SECTOFF R_PPC_SECTOFF
+#define R_PPC64_SECTOFF_LO R_PPC_SECTOFF_LO
+#define R_PPC64_SECTOFF_HI R_PPC_SECTOFF_HI
+#define R_PPC64_SECTOFF_HA R_PPC_SECTOFF_HA
+#define R_PPC64_ADDR30 37 /* word30 (S + A - P) >> 2 */
+#define R_PPC64_ADDR64 38 /* doubleword64 S + A */
+#define R_PPC64_ADDR16_HIGHER 39 /* half16 #higher(S + A) */
+#define R_PPC64_ADDR16_HIGHERA 40 /* half16 #highera(S + A) */
+#define R_PPC64_ADDR16_HIGHEST 41 /* half16 #highest(S + A) */
+#define R_PPC64_ADDR16_HIGHESTA 42 /* half16 #highesta(S + A) */
+#define R_PPC64_UADDR64 43 /* doubleword64 S + A */
+#define R_PPC64_REL64 44 /* doubleword64 S + A - P */
+#define R_PPC64_PLT64 45 /* doubleword64 L + A */
+#define R_PPC64_PLTREL64 46 /* doubleword64 L + A - P */
+#define R_PPC64_TOC16 47 /* half16* S + A - .TOC */
+#define R_PPC64_TOC16_LO 48 /* half16 #lo(S + A - .TOC.) */
+#define R_PPC64_TOC16_HI 49 /* half16 #hi(S + A - .TOC.) */
+#define R_PPC64_TOC16_HA 50 /* half16 #ha(S + A - .TOC.) */
+#define R_PPC64_TOC 51 /* doubleword64 .TOC */
+#define R_PPC64_PLTGOT16 52 /* half16* M + A */
+#define R_PPC64_PLTGOT16_LO 53 /* half16 #lo(M + A) */
+#define R_PPC64_PLTGOT16_HI 54 /* half16 #hi(M + A) */
+#define R_PPC64_PLTGOT16_HA 55 /* half16 #ha(M + A) */
+
+#define R_PPC64_ADDR16_DS 56 /* half16ds* (S + A) >> 2 */
+#define R_PPC64_ADDR16_LO_DS 57 /* half16ds #lo(S + A) >> 2 */
+#define R_PPC64_GOT16_DS 58 /* half16ds* (G + A) >> 2 */
+#define R_PPC64_GOT16_LO_DS 59 /* half16ds #lo(G + A) >> 2 */
+#define R_PPC64_PLT16_LO_DS 60 /* half16ds #lo(L + A) >> 2 */
+#define R_PPC64_SECTOFF_DS 61 /* half16ds* (R + A) >> 2 */
+#define R_PPC64_SECTOFF_LO_DS 62 /* half16ds #lo(R + A) >> 2 */
+#define R_PPC64_TOC16_DS 63 /* half16ds* (S + A - .TOC.) >> 2 */
+#define R_PPC64_TOC16_LO_DS 64 /* half16ds #lo(S + A - .TOC.) >> 2 */
+#define R_PPC64_PLTGOT16_DS 65 /* half16ds* (M + A) >> 2 */
+#define R_PPC64_PLTGOT16_LO_DS 66 /* half16ds #lo(M + A) >> 2 */
+
+/* PowerPC64 relocations defined for the TLS access ABI. */
+#define R_PPC64_TLS 67 /* none (sym+add)@tls */
+#define R_PPC64_DTPMOD64 68 /* doubleword64 (sym+add)@dtpmod */
+#define R_PPC64_TPREL16 69 /* half16* (sym+add)@tprel */
+#define R_PPC64_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */
+#define R_PPC64_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */
+#define R_PPC64_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */
+#define R_PPC64_TPREL64 73 /* doubleword64 (sym+add)@tprel */
+#define R_PPC64_DTPREL16 74 /* half16* (sym+add)@dtprel */
+#define R_PPC64_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */
+#define R_PPC64_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */
+#define R_PPC64_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */
+#define R_PPC64_DTPREL64 78 /* doubleword64 (sym+add)@dtprel */
+#define R_PPC64_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */
+#define R_PPC64_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */
+#define R_PPC64_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */
+#define R_PPC64_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */
+#define R_PPC64_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */
+#define R_PPC64_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */
+#define R_PPC64_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */
+#define R_PPC64_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */
+#define R_PPC64_GOT_TPREL16_DS 87 /* half16ds* (sym+add)@got@tprel */
+#define R_PPC64_GOT_TPREL16_LO_DS 88 /* half16ds (sym+add)@got@tprel@l */
+#define R_PPC64_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */
+#define R_PPC64_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */
+#define R_PPC64_GOT_DTPREL16_DS 91 /* half16ds* (sym+add)@got@dtprel */
+#define R_PPC64_GOT_DTPREL16_LO_DS 92 /* half16ds (sym+add)@got@dtprel@l */
+#define R_PPC64_GOT_DTPREL16_HI 93 /* half16 (sym+add)@got@dtprel@h */
+#define R_PPC64_GOT_DTPREL16_HA 94 /* half16 (sym+add)@got@dtprel@ha */
+#define R_PPC64_TPREL16_DS 95 /* half16ds* (sym+add)@tprel */
+#define R_PPC64_TPREL16_LO_DS 96 /* half16ds (sym+add)@tprel@l */
+#define R_PPC64_TPREL16_HIGHER 97 /* half16 (sym+add)@tprel@higher */
+#define R_PPC64_TPREL16_HIGHERA 98 /* half16 (sym+add)@tprel@highera */
+#define R_PPC64_TPREL16_HIGHEST 99 /* half16 (sym+add)@tprel@highest */
+#define R_PPC64_TPREL16_HIGHESTA 100 /* half16 (sym+add)@tprel@highesta */
+#define R_PPC64_DTPREL16_DS 101 /* half16ds* (sym+add)@dtprel */
+#define R_PPC64_DTPREL16_LO_DS 102 /* half16ds (sym+add)@dtprel@l */
+#define R_PPC64_DTPREL16_HIGHER 103 /* half16 (sym+add)@dtprel@higher */
+#define R_PPC64_DTPREL16_HIGHERA 104 /* half16 (sym+add)@dtprel@highera */
+#define R_PPC64_DTPREL16_HIGHEST 105 /* half16 (sym+add)@dtprel@highest */
+#define R_PPC64_DTPREL16_HIGHESTA 106 /* half16 (sym+add)@dtprel@highesta */
+#define R_PPC64_TLSGD 107 /* none (sym+add)@tlsgd */
+#define R_PPC64_TLSLD 108 /* none (sym+add)@tlsld */
+#define R_PPC64_TOCSAVE 109 /* none */
+
+/* Added when HA and HI relocs were changed to report overflows. */
+#define R_PPC64_ADDR16_HIGH 110
+#define R_PPC64_ADDR16_HIGHA 111
+#define R_PPC64_TPREL16_HIGH 112
+#define R_PPC64_TPREL16_HIGHA 113
+#define R_PPC64_DTPREL16_HIGH 114
+#define R_PPC64_DTPREL16_HIGHA 115
+
+/* GNU extension to support local ifunc. */
+#define R_PPC64_JMP_IREL 247
+#define R_PPC64_IRELATIVE 248
+#define R_PPC64_REL16 249 /* half16 (sym+add-.) */
+#define R_PPC64_REL16_LO 250 /* half16 (sym+add-.)@l */
+#define R_PPC64_REL16_HI 251 /* half16 (sym+add-.)@h */
+#define R_PPC64_REL16_HA 252 /* half16 (sym+add-.)@ha */
+
+/* e_flags bits specifying ABI.
+ 1 for original function descriptor using ABI,
+ 2 for revised ABI without function descriptors,
+ 0 for unspecified or not using any features affected by the differences. */
+#define EF_PPC64_ABI 3
+
+/* PowerPC64 specific values for the Dyn d_tag field. */
+#define DT_PPC64_GLINK (DT_LOPROC + 0)
+#define DT_PPC64_OPD (DT_LOPROC + 1)
+#define DT_PPC64_OPDSZ (DT_LOPROC + 2)
+#define DT_PPC64_OPT (DT_LOPROC + 3)
+#define DT_PPC64_NUM 4
+
+/* PowerPC64 specific bits in the DT_PPC64_OPT Dyn entry. */
+#define PPC64_OPT_TLS 1
+#define PPC64_OPT_MULTI_TOC 2
+#define PPC64_OPT_LOCALENTRY 4
+
+/* PowerPC64 specific values for the Elf64_Sym st_other field. */
+#define STO_PPC64_LOCAL_BIT 5
+#define STO_PPC64_LOCAL_MASK (7 << STO_PPC64_LOCAL_BIT)
+#define PPC64_LOCAL_ENTRY_OFFSET(other) \
+ (((1 << (((other) & STO_PPC64_LOCAL_MASK) >> STO_PPC64_LOCAL_BIT)) >> 2) << 2)
+
+
+/* ARM specific declarations */
+
+/* Processor specific flags for the ELF header e_flags field. */
+#define EF_ARM_RELEXEC 0x01
+#define EF_ARM_HASENTRY 0x02
+#define EF_ARM_INTERWORK 0x04
+#define EF_ARM_APCS_26 0x08
+#define EF_ARM_APCS_FLOAT 0x10
+#define EF_ARM_PIC 0x20
+#define EF_ARM_ALIGN8 0x40 /* 8-bit structure alignment is in use */
+#define EF_ARM_NEW_ABI 0x80
+#define EF_ARM_OLD_ABI 0x100
+#define EF_ARM_SOFT_FLOAT 0x200
+#define EF_ARM_VFP_FLOAT 0x400
+#define EF_ARM_MAVERICK_FLOAT 0x800
+
+#define EF_ARM_ABI_FLOAT_SOFT 0x200 /* NB conflicts with EF_ARM_SOFT_FLOAT */
+#define EF_ARM_ABI_FLOAT_HARD 0x400 /* NB conflicts with EF_ARM_VFP_FLOAT */
+
+
+/* Other constants defined in the ARM ELF spec. version B-01. */
+/* NB. These conflict with values defined above. */
+#define EF_ARM_SYMSARESORTED 0x04
+#define EF_ARM_DYNSYMSUSESEGIDX 0x08
+#define EF_ARM_MAPSYMSFIRST 0x10
+#define EF_ARM_EABIMASK 0XFF000000
+
+/* Constants defined in AAELF. */
+#define EF_ARM_BE8 0x00800000
+#define EF_ARM_LE8 0x00400000
+
+#define EF_ARM_EABI_VERSION(flags) ((flags) & EF_ARM_EABIMASK)
+#define EF_ARM_EABI_UNKNOWN 0x00000000
+#define EF_ARM_EABI_VER1 0x01000000
+#define EF_ARM_EABI_VER2 0x02000000
+#define EF_ARM_EABI_VER3 0x03000000
+#define EF_ARM_EABI_VER4 0x04000000
+#define EF_ARM_EABI_VER5 0x05000000
+
+/* Additional symbol types for Thumb. */
+#define STT_ARM_TFUNC STT_LOPROC /* A Thumb function. */
+#define STT_ARM_16BIT STT_HIPROC /* A Thumb label. */
+
+/* ARM-specific values for sh_flags */
+#define SHF_ARM_ENTRYSECT 0x10000000 /* Section contains an entry point */
+#define SHF_ARM_COMDEF 0x80000000 /* Section may be multiply defined
+ in the input to a link step. */
+
+/* ARM-specific program header flags */
+#define PF_ARM_SB 0x10000000 /* Segment contains the location
+ addressed by the static base. */
+#define PF_ARM_PI 0x20000000 /* Position-independent segment. */
+#define PF_ARM_ABS 0x40000000 /* Absolute segment. */
+
+/* Processor specific values for the Phdr p_type field. */
+#define PT_ARM_EXIDX (PT_LOPROC + 1) /* ARM unwind segment. */
+
+/* Processor specific values for the Shdr sh_type field. */
+#define SHT_ARM_EXIDX (SHT_LOPROC + 1) /* ARM unwind section. */
+#define SHT_ARM_PREEMPTMAP (SHT_LOPROC + 2) /* Preemption details. */
+#define SHT_ARM_ATTRIBUTES (SHT_LOPROC + 3) /* ARM attributes section. */
+
+
+/* AArch64 relocs. */
+
+#define R_AARCH64_NONE 0 /* No relocation. */
+
+/* ILP32 AArch64 relocs. */
+#define R_AARCH64_P32_ABS32 1 /* Direct 32 bit. */
+#define R_AARCH64_P32_COPY 180 /* Copy symbol at runtime. */
+#define R_AARCH64_P32_GLOB_DAT 181 /* Create GOT entry. */
+#define R_AARCH64_P32_JUMP_SLOT 182 /* Create PLT entry. */
+#define R_AARCH64_P32_RELATIVE 183 /* Adjust by program base. */
+#define R_AARCH64_P32_TLS_DTPMOD 184 /* Module number, 32 bit. */
+#define R_AARCH64_P32_TLS_DTPREL 185 /* Module-relative offset, 32 bit. */
+#define R_AARCH64_P32_TLS_TPREL 186 /* TP-relative offset, 32 bit. */
+#define R_AARCH64_P32_TLSDESC 187 /* TLS Descriptor. */
+#define R_AARCH64_P32_IRELATIVE 188 /* STT_GNU_IFUNC relocation. */
+
+/* LP64 AArch64 relocs. */
+#define R_AARCH64_ABS64 257 /* Direct 64 bit. */
+#define R_AARCH64_ABS32 258 /* Direct 32 bit. */
+#define R_AARCH64_ABS16 259 /* Direct 16-bit. */
+#define R_AARCH64_PREL64 260 /* PC-relative 64-bit. */
+#define R_AARCH64_PREL32 261 /* PC-relative 32-bit. */
+#define R_AARCH64_PREL16 262 /* PC-relative 16-bit. */
+#define R_AARCH64_MOVW_UABS_G0 263 /* Dir. MOVZ imm. from bits 15:0. */
+#define R_AARCH64_MOVW_UABS_G0_NC 264 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_UABS_G1 265 /* Dir. MOVZ imm. from bits 31:16. */
+#define R_AARCH64_MOVW_UABS_G1_NC 266 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_UABS_G2 267 /* Dir. MOVZ imm. from bits 47:32. */
+#define R_AARCH64_MOVW_UABS_G2_NC 268 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_UABS_G3 269 /* Dir. MOV{K,Z} imm. from 63:48. */
+#define R_AARCH64_MOVW_SABS_G0 270 /* Dir. MOV{N,Z} imm. from 15:0. */
+#define R_AARCH64_MOVW_SABS_G1 271 /* Dir. MOV{N,Z} imm. from 31:16. */
+#define R_AARCH64_MOVW_SABS_G2 272 /* Dir. MOV{N,Z} imm. from 47:32. */
+#define R_AARCH64_LD_PREL_LO19 273 /* PC-rel. LD imm. from bits 20:2. */
+#define R_AARCH64_ADR_PREL_LO21 274 /* PC-rel. ADR imm. from bits 20:0. */
+#define R_AARCH64_ADR_PREL_PG_HI21 275 /* Page-rel. ADRP imm. from 32:12. */
+#define R_AARCH64_ADR_PREL_PG_HI21_NC 276 /* Likewise; no overflow check. */
+#define R_AARCH64_ADD_ABS_LO12_NC 277 /* Dir. ADD imm. from bits 11:0. */
+#define R_AARCH64_LDST8_ABS_LO12_NC 278 /* Likewise for LD/ST; no check. */
+#define R_AARCH64_TSTBR14 279 /* PC-rel. TBZ/TBNZ imm. from 15:2. */
+#define R_AARCH64_CONDBR19 280 /* PC-rel. cond. br. imm. from 20:2. */
+#define R_AARCH64_JUMP26 282 /* PC-rel. B imm. from bits 27:2. */
+#define R_AARCH64_CALL26 283 /* Likewise for CALL. */
+#define R_AARCH64_LDST16_ABS_LO12_NC 284 /* Dir. ADD imm. from bits 11:1. */
+#define R_AARCH64_LDST32_ABS_LO12_NC 285 /* Likewise for bits 11:2. */
+#define R_AARCH64_LDST64_ABS_LO12_NC 286 /* Likewise for bits 11:3. */
+#define R_AARCH64_MOVW_PREL_G0 287 /* PC-rel. MOV{N,Z} imm. from 15:0. */
+#define R_AARCH64_MOVW_PREL_G0_NC 288 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_PREL_G1 289 /* PC-rel. MOV{N,Z} imm. from 31:16. */
+#define R_AARCH64_MOVW_PREL_G1_NC 290 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_PREL_G2 291 /* PC-rel. MOV{N,Z} imm. from 47:32. */
+#define R_AARCH64_MOVW_PREL_G2_NC 292 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_PREL_G3 293 /* PC-rel. MOV{N,Z} imm. from 63:48. */
+#define R_AARCH64_LDST128_ABS_LO12_NC 299 /* Dir. ADD imm. from bits 11:4. */
+#define R_AARCH64_MOVW_GOTOFF_G0 300 /* GOT-rel. off. MOV{N,Z} imm. 15:0. */
+#define R_AARCH64_MOVW_GOTOFF_G0_NC 301 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_GOTOFF_G1 302 /* GOT-rel. o. MOV{N,Z} imm. 31:16. */
+#define R_AARCH64_MOVW_GOTOFF_G1_NC 303 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_GOTOFF_G2 304 /* GOT-rel. o. MOV{N,Z} imm. 47:32. */
+#define R_AARCH64_MOVW_GOTOFF_G2_NC 305 /* Likewise for MOVK; no check. */
+#define R_AARCH64_MOVW_GOTOFF_G3 306 /* GOT-rel. o. MOV{N,Z} imm. 63:48. */
+#define R_AARCH64_GOTREL64 307 /* GOT-relative 64-bit. */
+#define R_AARCH64_GOTREL32 308 /* GOT-relative 32-bit. */
+#define R_AARCH64_GOT_LD_PREL19 309 /* PC-rel. GOT off. load imm. 20:2. */
+#define R_AARCH64_LD64_GOTOFF_LO15 310 /* GOT-rel. off. LD/ST imm. 14:3. */
+#define R_AARCH64_ADR_GOT_PAGE 311 /* P-page-rel. GOT off. ADRP 32:12. */
+#define R_AARCH64_LD64_GOT_LO12_NC 312 /* Dir. GOT off. LD/ST imm. 11:3. */
+#define R_AARCH64_LD64_GOTPAGE_LO15 313 /* GOT-page-rel. GOT off. LD/ST 14:3 */
+#define R_AARCH64_TLSGD_ADR_PREL21 512 /* PC-relative ADR imm. 20:0. */
+#define R_AARCH64_TLSGD_ADR_PAGE21 513 /* page-rel. ADRP imm. 32:12. */
+#define R_AARCH64_TLSGD_ADD_LO12_NC 514 /* direct ADD imm. from 11:0. */
+#define R_AARCH64_TLSGD_MOVW_G1 515 /* GOT-rel. MOV{N,Z} 31:16. */
+#define R_AARCH64_TLSGD_MOVW_G0_NC 516 /* GOT-rel. MOVK imm. 15:0. */
+#define R_AARCH64_TLSLD_ADR_PREL21 517 /* Like 512; local dynamic model. */
+#define R_AARCH64_TLSLD_ADR_PAGE21 518 /* Like 513; local dynamic model. */
+#define R_AARCH64_TLSLD_ADD_LO12_NC 519 /* Like 514; local dynamic model. */
+#define R_AARCH64_TLSLD_MOVW_G1 520 /* Like 515; local dynamic model. */
+#define R_AARCH64_TLSLD_MOVW_G0_NC 521 /* Like 516; local dynamic model. */
+#define R_AARCH64_TLSLD_LD_PREL19 522 /* TLS PC-rel. load imm. 20:2. */
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G2 523 /* TLS DTP-rel. MOV{N,Z} 47:32. */
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G1 524 /* TLS DTP-rel. MOV{N,Z} 31:16. */
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G1_NC 525 /* Likewise; MOVK; no check. */
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G0 526 /* TLS DTP-rel. MOV{N,Z} 15:0. */
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC 527 /* Likewise; MOVK; no check. */
+#define R_AARCH64_TLSLD_ADD_DTPREL_HI12 528 /* DTP-rel. ADD imm. from 23:12. */
+#define R_AARCH64_TLSLD_ADD_DTPREL_LO12 529 /* DTP-rel. ADD imm. from 11:0. */
+#define R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC 530 /* Likewise; no ovfl. check. */
+#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12 531 /* DTP-rel. LD/ST imm. 11:0. */
+#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC 532 /* Likewise; no check. */
+#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12 533 /* DTP-rel. LD/ST imm. 11:1. */
+#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC 534 /* Likewise; no check. */
+#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12 535 /* DTP-rel. LD/ST imm. 11:2. */
+#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC 536 /* Likewise; no check. */
+#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12 537 /* DTP-rel. LD/ST imm. 11:3. */
+#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC 538 /* Likewise; no check. */
+#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 539 /* GOT-rel. MOV{N,Z} 31:16. */
+#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC 540 /* GOT-rel. MOVK 15:0. */
+#define R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 541 /* Page-rel. ADRP 32:12. */
+#define R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC 542 /* Direct LD off. 11:3. */
+#define R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 543 /* PC-rel. load imm. 20:2. */
+#define R_AARCH64_TLSLE_MOVW_TPREL_G2 544 /* TLS TP-rel. MOV{N,Z} 47:32. */
+#define R_AARCH64_TLSLE_MOVW_TPREL_G1 545 /* TLS TP-rel. MOV{N,Z} 31:16. */
+#define R_AARCH64_TLSLE_MOVW_TPREL_G1_NC 546 /* Likewise; MOVK; no check. */
+#define R_AARCH64_TLSLE_MOVW_TPREL_G0 547 /* TLS TP-rel. MOV{N,Z} 15:0. */
+#define R_AARCH64_TLSLE_MOVW_TPREL_G0_NC 548 /* Likewise; MOVK; no check. */
+#define R_AARCH64_TLSLE_ADD_TPREL_HI12 549 /* TP-rel. ADD imm. 23:12. */
+#define R_AARCH64_TLSLE_ADD_TPREL_LO12 550 /* TP-rel. ADD imm. 11:0. */
+#define R_AARCH64_TLSLE_ADD_TPREL_LO12_NC 551 /* Likewise; no ovfl. check. */
+#define R_AARCH64_TLSLE_LDST8_TPREL_LO12 552 /* TP-rel. LD/ST off. 11:0. */
+#define R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC 553 /* Likewise; no ovfl. check. */
+#define R_AARCH64_TLSLE_LDST16_TPREL_LO12 554 /* TP-rel. LD/ST off. 11:1. */
+#define R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC 555 /* Likewise; no check. */
+#define R_AARCH64_TLSLE_LDST32_TPREL_LO12 556 /* TP-rel. LD/ST off. 11:2. */
+#define R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC 557 /* Likewise; no check. */
+#define R_AARCH64_TLSLE_LDST64_TPREL_LO12 558 /* TP-rel. LD/ST off. 11:3. */
+#define R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC 559 /* Likewise; no check. */
+#define R_AARCH64_TLSDESC_LD_PREL19 560 /* PC-rel. load immediate 20:2. */
+#define R_AARCH64_TLSDESC_ADR_PREL21 561 /* PC-rel. ADR immediate 20:0. */
+#define R_AARCH64_TLSDESC_ADR_PAGE21 562 /* Page-rel. ADRP imm. 32:12. */
+#define R_AARCH64_TLSDESC_LD64_LO12 563 /* Direct LD off. from 11:3. */
+#define R_AARCH64_TLSDESC_ADD_LO12 564 /* Direct ADD imm. from 11:0. */
+#define R_AARCH64_TLSDESC_OFF_G1 565 /* GOT-rel. MOV{N,Z} imm. 31:16. */
+#define R_AARCH64_TLSDESC_OFF_G0_NC 566 /* GOT-rel. MOVK imm. 15:0; no ck. */
+#define R_AARCH64_TLSDESC_LDR 567 /* Relax LDR. */
+#define R_AARCH64_TLSDESC_ADD 568 /* Relax ADD. */
+#define R_AARCH64_TLSDESC_CALL 569 /* Relax BLR. */
+#define R_AARCH64_TLSLE_LDST128_TPREL_LO12 570 /* TP-rel. LD/ST off. 11:4. */
+#define R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC 571 /* Likewise; no check. */
+#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12 572 /* DTP-rel. LD/ST imm. 11:4. */
+#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC 573 /* Likewise; no check. */
+#define R_AARCH64_COPY 1024 /* Copy symbol at runtime. */
+#define R_AARCH64_GLOB_DAT 1025 /* Create GOT entry. */
+#define R_AARCH64_JUMP_SLOT 1026 /* Create PLT entry. */
+#define R_AARCH64_RELATIVE 1027 /* Adjust by program base. */
+#define R_AARCH64_TLS_DTPMOD 1028 /* Module number, 64 bit. */
+#define R_AARCH64_TLS_DTPREL 1029 /* Module-relative offset, 64 bit. */
+#define R_AARCH64_TLS_TPREL 1030 /* TP-relative offset, 64 bit. */
+#define R_AARCH64_TLSDESC 1031 /* TLS Descriptor. */
+#define R_AARCH64_IRELATIVE 1032 /* STT_GNU_IFUNC relocation. */
+
+/* MTE memory tag segment type. */
+#define PT_AARCH64_MEMTAG_MTE (PT_LOPROC + 2)
+
+/* AArch64 specific values for the Dyn d_tag field. */
+#define DT_AARCH64_BTI_PLT (DT_LOPROC + 1)
+#define DT_AARCH64_PAC_PLT (DT_LOPROC + 3)
+#define DT_AARCH64_VARIANT_PCS (DT_LOPROC + 5)
+#define DT_AARCH64_NUM 6
+
+/* AArch64 specific values for the st_other field. */
+#define STO_AARCH64_VARIANT_PCS 0x80
+
+/* ARM relocs. */
+
+#define R_ARM_NONE 0 /* No reloc */
+#define R_ARM_PC24 1 /* Deprecated PC relative 26
+ bit branch. */
+#define R_ARM_ABS32 2 /* Direct 32 bit */
+#define R_ARM_REL32 3 /* PC relative 32 bit */
+#define R_ARM_PC13 4
+#define R_ARM_ABS16 5 /* Direct 16 bit */
+#define R_ARM_ABS12 6 /* Direct 12 bit */
+#define R_ARM_THM_ABS5 7 /* Direct & 0x7C (LDR, STR). */
+#define R_ARM_ABS8 8 /* Direct 8 bit */
+#define R_ARM_SBREL32 9
+#define R_ARM_THM_PC22 10 /* PC relative 24 bit (Thumb32 BL). */
+#define R_ARM_THM_PC8 11 /* PC relative & 0x3FC
+ (Thumb16 LDR, ADD, ADR). */
+#define R_ARM_AMP_VCALL9 12
+#define R_ARM_SWI24 13 /* Obsolete static relocation. */
+#define R_ARM_TLS_DESC 13 /* Dynamic relocation. */
+#define R_ARM_THM_SWI8 14 /* Reserved. */
+#define R_ARM_XPC25 15 /* Reserved. */
+#define R_ARM_THM_XPC22 16 /* Reserved. */
+#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 symbol at runtime */
+#define R_ARM_GLOB_DAT 21 /* Create GOT entry */
+#define R_ARM_JUMP_SLOT 22 /* Create PLT entry */
+#define R_ARM_RELATIVE 23 /* Adjust by program base */
+#define R_ARM_GOTOFF 24 /* 32 bit offset to GOT */
+#define R_ARM_GOTPC 25 /* 32 bit PC relative offset to GOT */
+#define R_ARM_GOT32 26 /* 32 bit GOT entry */
+#define R_ARM_PLT32 27 /* Deprecated, 32 bit PLT address. */
+#define R_ARM_CALL 28 /* PC relative 24 bit (BL, BLX). */
+#define R_ARM_JUMP24 29 /* PC relative 24 bit
+ (B, BL<cond>). */
+#define R_ARM_THM_JUMP24 30 /* PC relative 24 bit (Thumb32 B.W). */
+#define R_ARM_BASE_ABS 31 /* Adjust by program base. */
+#define R_ARM_ALU_PCREL_7_0 32 /* Obsolete. */
+#define R_ARM_ALU_PCREL_15_8 33 /* Obsolete. */
+#define R_ARM_ALU_PCREL_23_15 34 /* Obsolete. */
+#define R_ARM_LDR_SBREL_11_0 35 /* Deprecated, prog. base relative. */
+#define R_ARM_ALU_SBREL_19_12 36 /* Deprecated, prog. base relative. */
+#define R_ARM_ALU_SBREL_27_20 37 /* Deprecated, prog. base relative. */
+#define R_ARM_TARGET1 38
+#define R_ARM_SBREL31 39 /* Program base relative. */
+#define R_ARM_V4BX 40
+#define R_ARM_TARGET2 41
+#define R_ARM_PREL31 42 /* 32 bit PC relative. */
+#define R_ARM_MOVW_ABS_NC 43 /* Direct 16-bit (MOVW). */
+#define R_ARM_MOVT_ABS 44 /* Direct high 16-bit (MOVT). */
+#define R_ARM_MOVW_PREL_NC 45 /* PC relative 16-bit (MOVW). */
+#define R_ARM_MOVT_PREL 46 /* PC relative (MOVT). */
+#define R_ARM_THM_MOVW_ABS_NC 47 /* Direct 16 bit (Thumb32 MOVW). */
+#define R_ARM_THM_MOVT_ABS 48 /* Direct high 16 bit
+ (Thumb32 MOVT). */
+#define R_ARM_THM_MOVW_PREL_NC 49 /* PC relative 16 bit
+ (Thumb32 MOVW). */
+#define R_ARM_THM_MOVT_PREL 50 /* PC relative high 16 bit
+ (Thumb32 MOVT). */
+#define R_ARM_THM_JUMP19 51 /* PC relative 20 bit
+ (Thumb32 B<cond>.W). */
+#define R_ARM_THM_JUMP6 52 /* PC relative X & 0x7E
+ (Thumb16 CBZ, CBNZ). */
+#define R_ARM_THM_ALU_PREL_11_0 53 /* PC relative 12 bit
+ (Thumb32 ADR.W). */
+#define R_ARM_THM_PC12 54 /* PC relative 12 bit
+ (Thumb32 LDR{D,SB,H,SH}). */
+#define R_ARM_ABS32_NOI 55 /* Direct 32-bit. */
+#define R_ARM_REL32_NOI 56 /* PC relative 32-bit. */
+#define R_ARM_ALU_PC_G0_NC 57 /* PC relative (ADD, SUB). */
+#define R_ARM_ALU_PC_G0 58 /* PC relative (ADD, SUB). */
+#define R_ARM_ALU_PC_G1_NC 59 /* PC relative (ADD, SUB). */
+#define R_ARM_ALU_PC_G1 60 /* PC relative (ADD, SUB). */
+#define R_ARM_ALU_PC_G2 61 /* PC relative (ADD, SUB). */
+#define R_ARM_LDR_PC_G1 62 /* PC relative (LDR,STR,LDRB,STRB). */
+#define R_ARM_LDR_PC_G2 63 /* PC relative (LDR,STR,LDRB,STRB). */
+#define R_ARM_LDRS_PC_G0 64 /* PC relative (STR{D,H},
+ LDR{D,SB,H,SH}). */
+#define R_ARM_LDRS_PC_G1 65 /* PC relative (STR{D,H},
+ LDR{D,SB,H,SH}). */
+#define R_ARM_LDRS_PC_G2 66 /* PC relative (STR{D,H},
+ LDR{D,SB,H,SH}). */
+#define R_ARM_LDC_PC_G0 67 /* PC relative (LDC, STC). */
+#define R_ARM_LDC_PC_G1 68 /* PC relative (LDC, STC). */
+#define R_ARM_LDC_PC_G2 69 /* PC relative (LDC, STC). */
+#define R_ARM_ALU_SB_G0_NC 70 /* Program base relative (ADD,SUB). */
+#define R_ARM_ALU_SB_G0 71 /* Program base relative (ADD,SUB). */
+#define R_ARM_ALU_SB_G1_NC 72 /* Program base relative (ADD,SUB). */
+#define R_ARM_ALU_SB_G1 73 /* Program base relative (ADD,SUB). */
+#define R_ARM_ALU_SB_G2 74 /* Program base relative (ADD,SUB). */
+#define R_ARM_LDR_SB_G0 75 /* Program base relative (LDR,
+ STR, LDRB, STRB). */
+#define R_ARM_LDR_SB_G1 76 /* Program base relative
+ (LDR, STR, LDRB, STRB). */
+#define R_ARM_LDR_SB_G2 77 /* Program base relative
+ (LDR, STR, LDRB, STRB). */
+#define R_ARM_LDRS_SB_G0 78 /* Program base relative
+ (LDR, STR, LDRB, STRB). */
+#define R_ARM_LDRS_SB_G1 79 /* Program base relative
+ (LDR, STR, LDRB, STRB). */
+#define R_ARM_LDRS_SB_G2 80 /* Program base relative
+ (LDR, STR, LDRB, STRB). */
+#define R_ARM_LDC_SB_G0 81 /* Program base relative (LDC,STC). */
+#define R_ARM_LDC_SB_G1 82 /* Program base relative (LDC,STC). */
+#define R_ARM_LDC_SB_G2 83 /* Program base relative (LDC,STC). */
+#define R_ARM_MOVW_BREL_NC 84 /* Program base relative 16
+ bit (MOVW). */
+#define R_ARM_MOVT_BREL 85 /* Program base relative high
+ 16 bit (MOVT). */
+#define R_ARM_MOVW_BREL 86 /* Program base relative 16
+ bit (MOVW). */
+#define R_ARM_THM_MOVW_BREL_NC 87 /* Program base relative 16
+ bit (Thumb32 MOVW). */
+#define R_ARM_THM_MOVT_BREL 88 /* Program base relative high
+ 16 bit (Thumb32 MOVT). */
+#define R_ARM_THM_MOVW_BREL 89 /* Program base relative 16
+ bit (Thumb32 MOVW). */
+#define R_ARM_TLS_GOTDESC 90
+#define R_ARM_TLS_CALL 91
+#define R_ARM_TLS_DESCSEQ 92 /* TLS relaxation. */
+#define R_ARM_THM_TLS_CALL 93
+#define R_ARM_PLT32_ABS 94
+#define R_ARM_GOT_ABS 95 /* GOT entry. */
+#define R_ARM_GOT_PREL 96 /* PC relative GOT entry. */
+#define R_ARM_GOT_BREL12 97 /* GOT entry relative to GOT
+ origin (LDR). */
+#define R_ARM_GOTOFF12 98 /* 12 bit, GOT entry relative
+ to GOT origin (LDR, STR). */
+#define R_ARM_GOTRELAX 99
+#define R_ARM_GNU_VTENTRY 100
+#define R_ARM_GNU_VTINHERIT 101
+#define R_ARM_THM_PC11 102 /* PC relative & 0xFFE (Thumb16 B). */
+#define R_ARM_THM_PC9 103 /* PC relative & 0x1FE
+ (Thumb16 B/B<cond>). */
+#define R_ARM_TLS_GD32 104 /* PC-rel 32 bit for global dynamic
+ thread local data */
+#define R_ARM_TLS_LDM32 105 /* PC-rel 32 bit for local dynamic
+ thread local data */
+#define R_ARM_TLS_LDO32 106 /* 32 bit offset relative to TLS
+ block */
+#define R_ARM_TLS_IE32 107 /* PC-rel 32 bit for GOT entry of
+ static TLS block offset */
+#define R_ARM_TLS_LE32 108 /* 32 bit offset relative to static
+ TLS block */
+#define R_ARM_TLS_LDO12 109 /* 12 bit relative to TLS
+ block (LDR, STR). */
+#define R_ARM_TLS_LE12 110 /* 12 bit relative to static
+ TLS block (LDR, STR). */
+#define R_ARM_TLS_IE12GP 111 /* 12 bit GOT entry relative
+ to GOT origin (LDR). */
+#define R_ARM_ME_TOO 128 /* Obsolete. */
+#define R_ARM_THM_TLS_DESCSEQ 129
+#define R_ARM_THM_TLS_DESCSEQ16 129
+#define R_ARM_THM_TLS_DESCSEQ32 130
+#define R_ARM_THM_GOT_BREL12 131 /* GOT entry relative to GOT
+ origin, 12 bit (Thumb32 LDR). */
+#define R_ARM_IRELATIVE 160
+#define R_ARM_RXPC25 249
+#define R_ARM_RSBREL32 250
+#define R_ARM_THM_RPC22 251
+#define R_ARM_RREL32 252
+#define R_ARM_RABS22 253
+#define R_ARM_RPC24 254
+#define R_ARM_RBASE 255
+/* Keep this the last entry. */
+#define R_ARM_NUM 256
+
+/* C-SKY */
+#define R_CKCORE_NONE 0 /* no reloc */
+#define R_CKCORE_ADDR32 1 /* direct 32 bit (S + A) */
+#define R_CKCORE_PCRELIMM8BY4 2 /* disp ((S + A - P) >> 2) & 0xff */
+#define R_CKCORE_PCRELIMM11BY2 3 /* disp ((S + A - P) >> 1) & 0x7ff */
+#define R_CKCORE_PCREL32 5 /* 32-bit rel (S + A - P) */
+#define R_CKCORE_PCRELJSR_IMM11BY2 6 /* disp ((S + A - P) >>1) & 0x7ff */
+#define R_CKCORE_RELATIVE 9 /* 32 bit adjust program base(B + A)*/
+#define R_CKCORE_COPY 10 /* 32 bit adjust by program base */
+#define R_CKCORE_GLOB_DAT 11 /* off between got and sym (S) */
+#define R_CKCORE_JUMP_SLOT 12 /* PLT entry (S) */
+#define R_CKCORE_GOTOFF 13 /* offset to GOT (S + A - GOT) */
+#define R_CKCORE_GOTPC 14 /* PC offset to GOT (GOT + A - P) */
+#define R_CKCORE_GOT32 15 /* 32 bit GOT entry (G) */
+#define R_CKCORE_PLT32 16 /* 32 bit PLT entry (G) */
+#define R_CKCORE_ADDRGOT 17 /* GOT entry in GLOB_DAT (GOT + G) */
+#define R_CKCORE_ADDRPLT 18 /* PLT entry in GLOB_DAT (GOT + G) */
+#define R_CKCORE_PCREL_IMM26BY2 19 /* ((S + A - P) >> 1) & 0x3ffffff */
+#define R_CKCORE_PCREL_IMM16BY2 20 /* disp ((S + A - P) >> 1) & 0xffff */
+#define R_CKCORE_PCREL_IMM16BY4 21 /* disp ((S + A - P) >> 2) & 0xffff */
+#define R_CKCORE_PCREL_IMM10BY2 22 /* disp ((S + A - P) >> 1) & 0x3ff */
+#define R_CKCORE_PCREL_IMM10BY4 23 /* disp ((S + A - P) >> 2) & 0x3ff */
+#define R_CKCORE_ADDR_HI16 24 /* high & low 16 bit ADDR */
+ /* ((S + A) >> 16) & 0xffff */
+#define R_CKCORE_ADDR_LO16 25 /* (S + A) & 0xffff */
+#define R_CKCORE_GOTPC_HI16 26 /* high & low 16 bit GOTPC */
+ /* ((GOT + A - P) >> 16) & 0xffff */
+#define R_CKCORE_GOTPC_LO16 27 /* (GOT + A - P) & 0xffff */
+#define R_CKCORE_GOTOFF_HI16 28 /* high & low 16 bit GOTOFF */
+ /* ((S + A - GOT) >> 16) & 0xffff */
+#define R_CKCORE_GOTOFF_LO16 29 /* (S + A - GOT) & 0xffff */
+#define R_CKCORE_GOT12 30 /* 12 bit disp GOT entry (G) */
+#define R_CKCORE_GOT_HI16 31 /* high & low 16 bit GOT */
+ /* (G >> 16) & 0xffff */
+#define R_CKCORE_GOT_LO16 32 /* (G & 0xffff) */
+#define R_CKCORE_PLT12 33 /* 12 bit disp PLT entry (G) */
+#define R_CKCORE_PLT_HI16 34 /* high & low 16 bit PLT */
+ /* (G >> 16) & 0xffff */
+#define R_CKCORE_PLT_LO16 35 /* G & 0xffff */
+#define R_CKCORE_ADDRGOT_HI16 36 /* high & low 16 bit ADDRGOT */
+ /* (GOT + G * 4) & 0xffff */
+#define R_CKCORE_ADDRGOT_LO16 37 /* (GOT + G * 4) & 0xffff */
+#define R_CKCORE_ADDRPLT_HI16 38 /* high & low 16 bit ADDRPLT */
+ /* ((GOT + G * 4) >> 16) & 0xFFFF */
+#define R_CKCORE_ADDRPLT_LO16 39 /* (GOT+G*4) & 0xffff */
+#define R_CKCORE_PCREL_JSR_IMM26BY2 40 /* disp ((S+A-P) >>1) & x3ffffff */
+#define R_CKCORE_TOFFSET_LO16 41 /* (S+A-BTEXT) & 0xffff */
+#define R_CKCORE_DOFFSET_LO16 42 /* (S+A-BTEXT) & 0xffff */
+#define R_CKCORE_PCREL_IMM18BY2 43 /* disp ((S+A-P) >>1) & 0x3ffff */
+#define R_CKCORE_DOFFSET_IMM18 44 /* disp (S+A-BDATA) & 0x3ffff */
+#define R_CKCORE_DOFFSET_IMM18BY2 45 /* disp ((S+A-BDATA)>>1) & 0x3ffff */
+#define R_CKCORE_DOFFSET_IMM18BY4 46 /* disp ((S+A-BDATA)>>2) & 0x3ffff */
+#define R_CKCORE_GOT_IMM18BY4 48 /* disp (G >> 2) */
+#define R_CKCORE_PLT_IMM18BY4 49 /* disp (G >> 2) */
+#define R_CKCORE_PCREL_IMM7BY4 50 /* disp ((S+A-P) >>2) & 0x7f */
+#define R_CKCORE_TLS_LE32 51 /* 32 bit offset to TLS block */
+#define R_CKCORE_TLS_IE32 52
+#define R_CKCORE_TLS_GD32 53
+#define R_CKCORE_TLS_LDM32 54
+#define R_CKCORE_TLS_LDO32 55
+#define R_CKCORE_TLS_DTPMOD32 56
+#define R_CKCORE_TLS_DTPOFF32 57
+#define R_CKCORE_TLS_TPOFF32 58
+
+/* C-SKY elf header definition. */
+#define EF_CSKY_ABIMASK 0XF0000000
+#define EF_CSKY_OTHER 0X0FFF0000
+#define EF_CSKY_PROCESSOR 0X0000FFFF
+
+#define EF_CSKY_ABIV1 0X10000000
+#define EF_CSKY_ABIV2 0X20000000
+
+/* C-SKY attributes section. */
+#define SHT_CSKY_ATTRIBUTES (SHT_LOPROC + 1)
+
+/* IA-64 specific declarations. */
+
+/* Processor specific flags for the Ehdr e_flags field. */
+#define EF_IA_64_MASKOS 0x0000000f /* os-specific flags */
+#define EF_IA_64_ABI64 0x00000010 /* 64-bit ABI */
+#define EF_IA_64_ARCH 0xff000000 /* arch. version mask */
+
+/* Processor specific values for the Phdr p_type field. */
+#define PT_IA_64_ARCHEXT (PT_LOPROC + 0) /* arch extension bits */
+#define PT_IA_64_UNWIND (PT_LOPROC + 1) /* ia64 unwind bits */
+#define PT_IA_64_HP_OPT_ANOT (PT_LOOS + 0x12)
+#define PT_IA_64_HP_HSL_ANOT (PT_LOOS + 0x13)
+#define PT_IA_64_HP_STACK (PT_LOOS + 0x14)
+
+/* Processor specific flags for the Phdr p_flags field. */
+#define PF_IA_64_NORECOV 0x80000000 /* spec insns w/o recovery */
+
+/* Processor specific values for the Shdr sh_type field. */
+#define SHT_IA_64_EXT (SHT_LOPROC + 0) /* extension bits */
+#define SHT_IA_64_UNWIND (SHT_LOPROC + 1) /* unwind bits */
+
+/* Processor specific flags for the Shdr sh_flags field. */
+#define SHF_IA_64_SHORT 0x10000000 /* section near gp */
+#define SHF_IA_64_NORECOV 0x20000000 /* spec insns w/o recovery */
+
+/* Processor specific values for the Dyn d_tag field. */
+#define DT_IA_64_PLT_RESERVE (DT_LOPROC + 0)
+#define DT_IA_64_NUM 1
+
+/* IA-64 relocations. */
+#define R_IA64_NONE 0x00 /* none */
+#define R_IA64_IMM14 0x21 /* symbol + addend, add imm14 */
+#define R_IA64_IMM22 0x22 /* symbol + addend, add imm22 */
+#define R_IA64_IMM64 0x23 /* symbol + addend, mov imm64 */
+#define R_IA64_DIR32MSB 0x24 /* symbol + addend, data4 MSB */
+#define R_IA64_DIR32LSB 0x25 /* symbol + addend, data4 LSB */
+#define R_IA64_DIR64MSB 0x26 /* symbol + addend, data8 MSB */
+#define R_IA64_DIR64LSB 0x27 /* symbol + addend, data8 LSB */
+#define R_IA64_GPREL22 0x2a /* @gprel(sym + add), add imm22 */
+#define R_IA64_GPREL64I 0x2b /* @gprel(sym + add), mov imm64 */
+#define R_IA64_GPREL32MSB 0x2c /* @gprel(sym + add), data4 MSB */
+#define R_IA64_GPREL32LSB 0x2d /* @gprel(sym + add), data4 LSB */
+#define R_IA64_GPREL64MSB 0x2e /* @gprel(sym + add), data8 MSB */
+#define R_IA64_GPREL64LSB 0x2f /* @gprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF22 0x32 /* @ltoff(sym + add), add imm22 */
+#define R_IA64_LTOFF64I 0x33 /* @ltoff(sym + add), mov imm64 */
+#define R_IA64_PLTOFF22 0x3a /* @pltoff(sym + add), add imm22 */
+#define R_IA64_PLTOFF64I 0x3b /* @pltoff(sym + add), mov imm64 */
+#define R_IA64_PLTOFF64MSB 0x3e /* @pltoff(sym + add), data8 MSB */
+#define R_IA64_PLTOFF64LSB 0x3f /* @pltoff(sym + add), data8 LSB */
+#define R_IA64_FPTR64I 0x43 /* @fptr(sym + add), mov imm64 */
+#define R_IA64_FPTR32MSB 0x44 /* @fptr(sym + add), data4 MSB */
+#define R_IA64_FPTR32LSB 0x45 /* @fptr(sym + add), data4 LSB */
+#define R_IA64_FPTR64MSB 0x46 /* @fptr(sym + add), data8 MSB */
+#define R_IA64_FPTR64LSB 0x47 /* @fptr(sym + add), data8 LSB */
+#define R_IA64_PCREL60B 0x48 /* @pcrel(sym + add), brl */
+#define R_IA64_PCREL21B 0x49 /* @pcrel(sym + add), ptb, call */
+#define R_IA64_PCREL21M 0x4a /* @pcrel(sym + add), chk.s */
+#define R_IA64_PCREL21F 0x4b /* @pcrel(sym + add), fchkf */
+#define R_IA64_PCREL32MSB 0x4c /* @pcrel(sym + add), data4 MSB */
+#define R_IA64_PCREL32LSB 0x4d /* @pcrel(sym + add), data4 LSB */
+#define R_IA64_PCREL64MSB 0x4e /* @pcrel(sym + add), data8 MSB */
+#define R_IA64_PCREL64LSB 0x4f /* @pcrel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_FPTR22 0x52 /* @ltoff(@fptr(s+a)), imm22 */
+#define R_IA64_LTOFF_FPTR64I 0x53 /* @ltoff(@fptr(s+a)), imm64 */
+#define R_IA64_LTOFF_FPTR32MSB 0x54 /* @ltoff(@fptr(s+a)), data4 MSB */
+#define R_IA64_LTOFF_FPTR32LSB 0x55 /* @ltoff(@fptr(s+a)), data4 LSB */
+#define R_IA64_LTOFF_FPTR64MSB 0x56 /* @ltoff(@fptr(s+a)), data8 MSB */
+#define R_IA64_LTOFF_FPTR64LSB 0x57 /* @ltoff(@fptr(s+a)), data8 LSB */
+#define R_IA64_SEGREL32MSB 0x5c /* @segrel(sym + add), data4 MSB */
+#define R_IA64_SEGREL32LSB 0x5d /* @segrel(sym + add), data4 LSB */
+#define R_IA64_SEGREL64MSB 0x5e /* @segrel(sym + add), data8 MSB */
+#define R_IA64_SEGREL64LSB 0x5f /* @segrel(sym + add), data8 LSB */
+#define R_IA64_SECREL32MSB 0x64 /* @secrel(sym + add), data4 MSB */
+#define R_IA64_SECREL32LSB 0x65 /* @secrel(sym + add), data4 LSB */
+#define R_IA64_SECREL64MSB 0x66 /* @secrel(sym + add), data8 MSB */
+#define R_IA64_SECREL64LSB 0x67 /* @secrel(sym + add), data8 LSB */
+#define R_IA64_REL32MSB 0x6c /* data 4 + REL */
+#define R_IA64_REL32LSB 0x6d /* data 4 + REL */
+#define R_IA64_REL64MSB 0x6e /* data 8 + REL */
+#define R_IA64_REL64LSB 0x6f /* data 8 + REL */
+#define R_IA64_LTV32MSB 0x74 /* symbol + addend, data4 MSB */
+#define R_IA64_LTV32LSB 0x75 /* symbol + addend, data4 LSB */
+#define R_IA64_LTV64MSB 0x76 /* symbol + addend, data8 MSB */
+#define R_IA64_LTV64LSB 0x77 /* symbol + addend, data8 LSB */
+#define R_IA64_PCREL21BI 0x79 /* @pcrel(sym + add), 21bit inst */
+#define R_IA64_PCREL22 0x7a /* @pcrel(sym + add), 22bit inst */
+#define R_IA64_PCREL64I 0x7b /* @pcrel(sym + add), 64bit inst */
+#define R_IA64_IPLTMSB 0x80 /* dynamic reloc, imported PLT, MSB */
+#define R_IA64_IPLTLSB 0x81 /* dynamic reloc, imported PLT, LSB */
+#define R_IA64_COPY 0x84 /* copy relocation */
+#define R_IA64_SUB 0x85 /* Addend and symbol difference */
+#define R_IA64_LTOFF22X 0x86 /* LTOFF22, relaxable. */
+#define R_IA64_LDXMOV 0x87 /* Use of LTOFF22X. */
+#define R_IA64_TPREL14 0x91 /* @tprel(sym + add), imm14 */
+#define R_IA64_TPREL22 0x92 /* @tprel(sym + add), imm22 */
+#define R_IA64_TPREL64I 0x93 /* @tprel(sym + add), imm64 */
+#define R_IA64_TPREL64MSB 0x96 /* @tprel(sym + add), data8 MSB */
+#define R_IA64_TPREL64LSB 0x97 /* @tprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_TPREL22 0x9a /* @ltoff(@tprel(s+a)), imm2 */
+#define R_IA64_DTPMOD64MSB 0xa6 /* @dtpmod(sym + add), data8 MSB */
+#define R_IA64_DTPMOD64LSB 0xa7 /* @dtpmod(sym + add), data8 LSB */
+#define R_IA64_LTOFF_DTPMOD22 0xaa /* @ltoff(@dtpmod(sym + add)), imm22 */
+#define R_IA64_DTPREL14 0xb1 /* @dtprel(sym + add), imm14 */
+#define R_IA64_DTPREL22 0xb2 /* @dtprel(sym + add), imm22 */
+#define R_IA64_DTPREL64I 0xb3 /* @dtprel(sym + add), imm64 */
+#define R_IA64_DTPREL32MSB 0xb4 /* @dtprel(sym + add), data4 MSB */
+#define R_IA64_DTPREL32LSB 0xb5 /* @dtprel(sym + add), data4 LSB */
+#define R_IA64_DTPREL64MSB 0xb6 /* @dtprel(sym + add), data8 MSB */
+#define R_IA64_DTPREL64LSB 0xb7 /* @dtprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_DTPREL22 0xba /* @ltoff(@dtprel(s+a)), imm22 */
+
+/* SH specific declarations */
+
+/* Processor specific flags for the ELF header e_flags field. */
+#define EF_SH_MACH_MASK 0x1f
+#define EF_SH_UNKNOWN 0x0
+#define EF_SH1 0x1
+#define EF_SH2 0x2
+#define EF_SH3 0x3
+#define EF_SH_DSP 0x4
+#define EF_SH3_DSP 0x5
+#define EF_SH4AL_DSP 0x6
+#define EF_SH3E 0x8
+#define EF_SH4 0x9
+#define EF_SH2E 0xb
+#define EF_SH4A 0xc
+#define EF_SH2A 0xd
+#define EF_SH4_NOFPU 0x10
+#define EF_SH4A_NOFPU 0x11
+#define EF_SH4_NOMMU_NOFPU 0x12
+#define EF_SH2A_NOFPU 0x13
+#define EF_SH3_NOMMU 0x14
+#define EF_SH2A_SH4_NOFPU 0x15
+#define EF_SH2A_SH3_NOFPU 0x16
+#define EF_SH2A_SH4 0x17
+#define EF_SH2A_SH3E 0x18
+
+/* SH relocs. */
+#define R_SH_NONE 0
+#define R_SH_DIR32 1
+#define R_SH_REL32 2
+#define R_SH_DIR8WPN 3
+#define R_SH_IND12W 4
+#define R_SH_DIR8WPL 5
+#define R_SH_DIR8WPZ 6
+#define R_SH_DIR8BP 7
+#define R_SH_DIR8W 8
+#define R_SH_DIR8L 9
+#define R_SH_SWITCH16 25
+#define R_SH_SWITCH32 26
+#define R_SH_USES 27
+#define R_SH_COUNT 28
+#define R_SH_ALIGN 29
+#define R_SH_CODE 30
+#define R_SH_DATA 31
+#define R_SH_LABEL 32
+#define R_SH_SWITCH8 33
+#define R_SH_GNU_VTINHERIT 34
+#define R_SH_GNU_VTENTRY 35
+#define R_SH_TLS_GD_32 144
+#define R_SH_TLS_LD_32 145
+#define R_SH_TLS_LDO_32 146
+#define R_SH_TLS_IE_32 147
+#define R_SH_TLS_LE_32 148
+#define R_SH_TLS_DTPMOD32 149
+#define R_SH_TLS_DTPOFF32 150
+#define R_SH_TLS_TPOFF32 151
+#define R_SH_GOT32 160
+#define R_SH_PLT32 161
+#define R_SH_COPY 162
+#define R_SH_GLOB_DAT 163
+#define R_SH_JMP_SLOT 164
+#define R_SH_RELATIVE 165
+#define R_SH_GOTOFF 166
+#define R_SH_GOTPC 167
+/* Keep this the last entry. */
+#define R_SH_NUM 256
+
+/* S/390 specific definitions. */
+
+/* Valid values for the e_flags field. */
+
+#define EF_S390_HIGH_GPRS 0x00000001 /* High GPRs kernel facility needed. */
+
+/* Additional s390 relocs */
+
+#define R_390_NONE 0 /* No reloc. */
+#define R_390_8 1 /* Direct 8 bit. */
+#define R_390_12 2 /* Direct 12 bit. */
+#define R_390_16 3 /* Direct 16 bit. */
+#define R_390_32 4 /* Direct 32 bit. */
+#define R_390_PC32 5 /* PC relative 32 bit. */
+#define R_390_GOT12 6 /* 12 bit GOT offset. */
+#define R_390_GOT32 7 /* 32 bit GOT offset. */
+#define R_390_PLT32 8 /* 32 bit PC relative PLT address. */
+#define R_390_COPY 9 /* Copy symbol at runtime. */
+#define R_390_GLOB_DAT 10 /* Create GOT entry. */
+#define R_390_JMP_SLOT 11 /* Create PLT entry. */
+#define R_390_RELATIVE 12 /* Adjust by program base. */
+#define R_390_GOTOFF32 13 /* 32 bit offset to GOT. */
+#define R_390_GOTPC 14 /* 32 bit PC relative offset to GOT. */
+#define R_390_GOT16 15 /* 16 bit GOT offset. */
+#define R_390_PC16 16 /* PC relative 16 bit. */
+#define R_390_PC16DBL 17 /* PC relative 16 bit shifted by 1. */
+#define R_390_PLT16DBL 18 /* 16 bit PC rel. PLT shifted by 1. */
+#define R_390_PC32DBL 19 /* PC relative 32 bit shifted by 1. */
+#define R_390_PLT32DBL 20 /* 32 bit PC rel. PLT shifted by 1. */
+#define R_390_GOTPCDBL 21 /* 32 bit PC rel. GOT shifted by 1. */
+#define R_390_64 22 /* Direct 64 bit. */
+#define R_390_PC64 23 /* PC relative 64 bit. */
+#define R_390_GOT64 24 /* 64 bit GOT offset. */
+#define R_390_PLT64 25 /* 64 bit PC relative PLT address. */
+#define R_390_GOTENT 26 /* 32 bit PC rel. to GOT entry >> 1. */
+#define R_390_GOTOFF16 27 /* 16 bit offset to GOT. */
+#define R_390_GOTOFF64 28 /* 64 bit offset to GOT. */
+#define R_390_GOTPLT12 29 /* 12 bit offset to jump slot. */
+#define R_390_GOTPLT16 30 /* 16 bit offset to jump slot. */
+#define R_390_GOTPLT32 31 /* 32 bit offset to jump slot. */
+#define R_390_GOTPLT64 32 /* 64 bit offset to jump slot. */
+#define R_390_GOTPLTENT 33 /* 32 bit rel. offset to jump slot. */
+#define R_390_PLTOFF16 34 /* 16 bit offset from GOT to PLT. */
+#define R_390_PLTOFF32 35 /* 32 bit offset from GOT to PLT. */
+#define R_390_PLTOFF64 36 /* 16 bit offset from GOT to PLT. */
+#define R_390_TLS_LOAD 37 /* Tag for load insn in TLS code. */
+#define R_390_TLS_GDCALL 38 /* Tag for function call in general
+ dynamic TLS code. */
+#define R_390_TLS_LDCALL 39 /* Tag for function call in local
+ dynamic TLS code. */
+#define R_390_TLS_GD32 40 /* Direct 32 bit for general dynamic
+ thread local data. */
+#define R_390_TLS_GD64 41 /* Direct 64 bit for general dynamic
+ thread local data. */
+#define R_390_TLS_GOTIE12 42 /* 12 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_GOTIE32 43 /* 32 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_GOTIE64 44 /* 64 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_LDM32 45 /* Direct 32 bit for local dynamic
+ thread local data in LE code. */
+#define R_390_TLS_LDM64 46 /* Direct 64 bit for local dynamic
+ thread local data in LE code. */
+#define R_390_TLS_IE32 47 /* 32 bit address of GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_IE64 48 /* 64 bit address of GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_IEENT 49 /* 32 bit rel. offset to GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_LE32 50 /* 32 bit negated offset relative to
+ static TLS block. */
+#define R_390_TLS_LE64 51 /* 64 bit negated offset relative to
+ static TLS block. */
+#define R_390_TLS_LDO32 52 /* 32 bit offset relative to TLS
+ block. */
+#define R_390_TLS_LDO64 53 /* 64 bit offset relative to TLS
+ block. */
+#define R_390_TLS_DTPMOD 54 /* ID of module containing symbol. */
+#define R_390_TLS_DTPOFF 55 /* Offset in TLS block. */
+#define R_390_TLS_TPOFF 56 /* Negated offset in static TLS
+ block. */
+#define R_390_20 57 /* Direct 20 bit. */
+#define R_390_GOT20 58 /* 20 bit GOT offset. */
+#define R_390_GOTPLT20 59 /* 20 bit offset to jump slot. */
+#define R_390_TLS_GOTIE20 60 /* 20 bit GOT offset for static TLS
+ block offset. */
+#define R_390_IRELATIVE 61 /* STT_GNU_IFUNC relocation. */
+/* Keep this the last entry. */
+#define R_390_NUM 62
+
+
+/* CRIS relocations. */
+#define R_CRIS_NONE 0
+#define R_CRIS_8 1
+#define R_CRIS_16 2
+#define R_CRIS_32 3
+#define R_CRIS_8_PCREL 4
+#define R_CRIS_16_PCREL 5
+#define R_CRIS_32_PCREL 6
+#define R_CRIS_GNU_VTINHERIT 7
+#define R_CRIS_GNU_VTENTRY 8
+#define R_CRIS_COPY 9
+#define R_CRIS_GLOB_DAT 10
+#define R_CRIS_JUMP_SLOT 11
+#define R_CRIS_RELATIVE 12
+#define R_CRIS_16_GOT 13
+#define R_CRIS_32_GOT 14
+#define R_CRIS_16_GOTPLT 15
+#define R_CRIS_32_GOTPLT 16
+#define R_CRIS_32_GOTREL 17
+#define R_CRIS_32_PLT_GOTREL 18
+#define R_CRIS_32_PLT_PCREL 19
+
+#define R_CRIS_NUM 20
+
+
+/* AMD x86-64 relocations. */
+#define R_X86_64_NONE 0 /* No reloc */
+#define R_X86_64_64 1 /* Direct 64 bit */
+#define R_X86_64_PC32 2 /* PC relative 32 bit signed */
+#define R_X86_64_GOT32 3 /* 32 bit GOT entry */
+#define R_X86_64_PLT32 4 /* 32 bit PLT address */
+#define R_X86_64_COPY 5 /* Copy symbol at runtime */
+#define R_X86_64_GLOB_DAT 6 /* Create GOT entry */
+#define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */
+#define R_X86_64_RELATIVE 8 /* Adjust by program base */
+#define R_X86_64_GOTPCREL 9 /* 32 bit signed PC relative
+ offset to GOT */
+#define R_X86_64_32 10 /* Direct 32 bit zero extended */
+#define R_X86_64_32S 11 /* Direct 32 bit sign extended */
+#define R_X86_64_16 12 /* Direct 16 bit zero extended */
+#define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */
+#define R_X86_64_8 14 /* Direct 8 bit sign extended */
+#define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */
+#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */
+#define R_X86_64_DTPOFF64 17 /* Offset in module's TLS block */
+#define R_X86_64_TPOFF64 18 /* Offset in initial TLS block */
+#define R_X86_64_TLSGD 19 /* 32 bit signed PC relative offset
+ to two GOT entries for GD symbol */
+#define R_X86_64_TLSLD 20 /* 32 bit signed PC relative offset
+ to two GOT entries for LD symbol */
+#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */
+#define R_X86_64_GOTTPOFF 22 /* 32 bit signed PC relative offset
+ to GOT entry for IE symbol */
+#define R_X86_64_TPOFF32 23 /* Offset in initial TLS block */
+#define R_X86_64_PC64 24 /* PC relative 64 bit */
+#define R_X86_64_GOTOFF64 25 /* 64 bit offset to GOT */
+#define R_X86_64_GOTPC32 26 /* 32 bit signed pc relative
+ offset to GOT */
+#define R_X86_64_GOT64 27 /* 64-bit GOT entry offset */
+#define R_X86_64_GOTPCREL64 28 /* 64-bit PC relative offset
+ to GOT entry */
+#define R_X86_64_GOTPC64 29 /* 64-bit PC relative offset to GOT */
+#define R_X86_64_GOTPLT64 30 /* like GOT64, says PLT entry needed */
+#define R_X86_64_PLTOFF64 31 /* 64-bit GOT relative offset
+ to PLT entry */
+#define R_X86_64_SIZE32 32 /* Size of symbol plus 32-bit addend */
+#define R_X86_64_SIZE64 33 /* Size of symbol plus 64-bit addend */
+#define R_X86_64_GOTPC32_TLSDESC 34 /* GOT offset for TLS descriptor. */
+#define R_X86_64_TLSDESC_CALL 35 /* Marker for call through TLS
+ descriptor. */
+#define R_X86_64_TLSDESC 36 /* TLS descriptor. */
+#define R_X86_64_IRELATIVE 37 /* Adjust indirectly by program base */
+#define R_X86_64_RELATIVE64 38 /* 64-bit adjust by program base */
+ /* 39 Reserved was R_X86_64_PC32_BND */
+ /* 40 Reserved was R_X86_64_PLT32_BND */
+#define R_X86_64_GOTPCRELX 41 /* Load from 32 bit signed pc relative
+ offset to GOT entry without REX
+ prefix, relaxable. */
+#define R_X86_64_REX_GOTPCRELX 42 /* Load from 32 bit signed pc relative
+ offset to GOT entry with REX prefix,
+ relaxable. */
+#define R_X86_64_NUM 43
+
+/* x86-64 sh_type values. */
+#define SHT_X86_64_UNWIND 0x70000001 /* Unwind information. */
+
+
+/* AM33 relocations. */
+#define R_MN10300_NONE 0 /* No reloc. */
+#define R_MN10300_32 1 /* Direct 32 bit. */
+#define R_MN10300_16 2 /* Direct 16 bit. */
+#define R_MN10300_8 3 /* Direct 8 bit. */
+#define R_MN10300_PCREL32 4 /* PC-relative 32-bit. */
+#define R_MN10300_PCREL16 5 /* PC-relative 16-bit signed. */
+#define R_MN10300_PCREL8 6 /* PC-relative 8-bit signed. */
+#define R_MN10300_GNU_VTINHERIT 7 /* Ancient C++ vtable garbage... */
+#define R_MN10300_GNU_VTENTRY 8 /* ... collection annotation. */
+#define R_MN10300_24 9 /* Direct 24 bit. */
+#define R_MN10300_GOTPC32 10 /* 32-bit PCrel offset to GOT. */
+#define R_MN10300_GOTPC16 11 /* 16-bit PCrel offset to GOT. */
+#define R_MN10300_GOTOFF32 12 /* 32-bit offset from GOT. */
+#define R_MN10300_GOTOFF24 13 /* 24-bit offset from GOT. */
+#define R_MN10300_GOTOFF16 14 /* 16-bit offset from GOT. */
+#define R_MN10300_PLT32 15 /* 32-bit PCrel to PLT entry. */
+#define R_MN10300_PLT16 16 /* 16-bit PCrel to PLT entry. */
+#define R_MN10300_GOT32 17 /* 32-bit offset to GOT entry. */
+#define R_MN10300_GOT24 18 /* 24-bit offset to GOT entry. */
+#define R_MN10300_GOT16 19 /* 16-bit offset to GOT entry. */
+#define R_MN10300_COPY 20 /* Copy symbol at runtime. */
+#define R_MN10300_GLOB_DAT 21 /* Create GOT entry. */
+#define R_MN10300_JMP_SLOT 22 /* Create PLT entry. */
+#define R_MN10300_RELATIVE 23 /* Adjust by program base. */
+#define R_MN10300_TLS_GD 24 /* 32-bit offset for global dynamic. */
+#define R_MN10300_TLS_LD 25 /* 32-bit offset for local dynamic. */
+#define R_MN10300_TLS_LDO 26 /* Module-relative offset. */
+#define R_MN10300_TLS_GOTIE 27 /* GOT offset for static TLS block
+ offset. */
+#define R_MN10300_TLS_IE 28 /* GOT address for static TLS block
+ offset. */
+#define R_MN10300_TLS_LE 29 /* Offset relative to static TLS
+ block. */
+#define R_MN10300_TLS_DTPMOD 30 /* ID of module containing symbol. */
+#define R_MN10300_TLS_DTPOFF 31 /* Offset in module TLS block. */
+#define R_MN10300_TLS_TPOFF 32 /* Offset in static TLS block. */
+#define R_MN10300_SYM_DIFF 33 /* Adjustment for next reloc as needed
+ by linker relaxation. */
+#define R_MN10300_ALIGN 34 /* Alignment requirement for linker
+ relaxation. */
+#define R_MN10300_NUM 35
+
+
+/* M32R relocs. */
+#define R_M32R_NONE 0 /* No reloc. */
+#define R_M32R_16 1 /* Direct 16 bit. */
+#define R_M32R_32 2 /* Direct 32 bit. */
+#define R_M32R_24 3 /* Direct 24 bit. */
+#define R_M32R_10_PCREL 4 /* PC relative 10 bit shifted. */
+#define R_M32R_18_PCREL 5 /* PC relative 18 bit shifted. */
+#define R_M32R_26_PCREL 6 /* PC relative 26 bit shifted. */
+#define R_M32R_HI16_ULO 7 /* High 16 bit with unsigned low. */
+#define R_M32R_HI16_SLO 8 /* High 16 bit with signed low. */
+#define R_M32R_LO16 9 /* Low 16 bit. */
+#define R_M32R_SDA16 10 /* 16 bit offset in SDA. */
+#define R_M32R_GNU_VTINHERIT 11
+#define R_M32R_GNU_VTENTRY 12
+/* M32R relocs use SHT_RELA. */
+#define R_M32R_16_RELA 33 /* Direct 16 bit. */
+#define R_M32R_32_RELA 34 /* Direct 32 bit. */
+#define R_M32R_24_RELA 35 /* Direct 24 bit. */
+#define R_M32R_10_PCREL_RELA 36 /* PC relative 10 bit shifted. */
+#define R_M32R_18_PCREL_RELA 37 /* PC relative 18 bit shifted. */
+#define R_M32R_26_PCREL_RELA 38 /* PC relative 26 bit shifted. */
+#define R_M32R_HI16_ULO_RELA 39 /* High 16 bit with unsigned low */
+#define R_M32R_HI16_SLO_RELA 40 /* High 16 bit with signed low */
+#define R_M32R_LO16_RELA 41 /* Low 16 bit */
+#define R_M32R_SDA16_RELA 42 /* 16 bit offset in SDA */
+#define R_M32R_RELA_GNU_VTINHERIT 43
+#define R_M32R_RELA_GNU_VTENTRY 44
+#define R_M32R_REL32 45 /* PC relative 32 bit. */
+
+#define R_M32R_GOT24 48 /* 24 bit GOT entry */
+#define R_M32R_26_PLTREL 49 /* 26 bit PC relative to PLT shifted */
+#define R_M32R_COPY 50 /* Copy symbol at runtime */
+#define R_M32R_GLOB_DAT 51 /* Create GOT entry */
+#define R_M32R_JMP_SLOT 52 /* Create PLT entry */
+#define R_M32R_RELATIVE 53 /* Adjust by program base */
+#define R_M32R_GOTOFF 54 /* 24 bit offset to GOT */
+#define R_M32R_GOTPC24 55 /* 24 bit PC relative offset to GOT */
+#define R_M32R_GOT16_HI_ULO 56 /* High 16 bit GOT entry with unsigned
+ low */
+#define R_M32R_GOT16_HI_SLO 57 /* High 16 bit GOT entry with signed
+ low */
+#define R_M32R_GOT16_LO 58 /* Low 16 bit GOT entry */
+#define R_M32R_GOTPC_HI_ULO 59 /* High 16 bit PC relative offset to
+ GOT with unsigned low */
+#define R_M32R_GOTPC_HI_SLO 60 /* High 16 bit PC relative offset to
+ GOT with signed low */
+#define R_M32R_GOTPC_LO 61 /* Low 16 bit PC relative offset to
+ GOT */
+#define R_M32R_GOTOFF_HI_ULO 62 /* High 16 bit offset to GOT
+ with unsigned low */
+#define R_M32R_GOTOFF_HI_SLO 63 /* High 16 bit offset to GOT
+ with signed low */
+#define R_M32R_GOTOFF_LO 64 /* Low 16 bit offset to GOT */
+#define R_M32R_NUM 256 /* Keep this the last entry. */
+
+/* MicroBlaze relocations */
+#define R_MICROBLAZE_NONE 0 /* No reloc. */
+#define R_MICROBLAZE_32 1 /* Direct 32 bit. */
+#define R_MICROBLAZE_32_PCREL 2 /* PC relative 32 bit. */
+#define R_MICROBLAZE_64_PCREL 3 /* PC relative 64 bit. */
+#define R_MICROBLAZE_32_PCREL_LO 4 /* Low 16 bits of PCREL32. */
+#define R_MICROBLAZE_64 5 /* Direct 64 bit. */
+#define R_MICROBLAZE_32_LO 6 /* Low 16 bit. */
+#define R_MICROBLAZE_SRO32 7 /* Read-only small data area. */
+#define R_MICROBLAZE_SRW32 8 /* Read-write small data area. */
+#define R_MICROBLAZE_64_NONE 9 /* No reloc. */
+#define R_MICROBLAZE_32_SYM_OP_SYM 10 /* Symbol Op Symbol relocation. */
+#define R_MICROBLAZE_GNU_VTINHERIT 11 /* GNU C++ vtable hierarchy. */
+#define R_MICROBLAZE_GNU_VTENTRY 12 /* GNU C++ vtable member usage. */
+#define R_MICROBLAZE_GOTPC_64 13 /* PC-relative GOT offset. */
+#define R_MICROBLAZE_GOT_64 14 /* GOT entry offset. */
+#define R_MICROBLAZE_PLT_64 15 /* PLT offset (PC-relative). */
+#define R_MICROBLAZE_REL 16 /* Adjust by program base. */
+#define R_MICROBLAZE_JUMP_SLOT 17 /* Create PLT entry. */
+#define R_MICROBLAZE_GLOB_DAT 18 /* Create GOT entry. */
+#define R_MICROBLAZE_GOTOFF_64 19 /* 64 bit offset to GOT. */
+#define R_MICROBLAZE_GOTOFF_32 20 /* 32 bit offset to GOT. */
+#define R_MICROBLAZE_COPY 21 /* Runtime copy. */
+#define R_MICROBLAZE_TLS 22 /* TLS Reloc. */
+#define R_MICROBLAZE_TLSGD 23 /* TLS General Dynamic. */
+#define R_MICROBLAZE_TLSLD 24 /* TLS Local Dynamic. */
+#define R_MICROBLAZE_TLSDTPMOD32 25 /* TLS Module ID. */
+#define R_MICROBLAZE_TLSDTPREL32 26 /* TLS Offset Within TLS Block. */
+#define R_MICROBLAZE_TLSDTPREL64 27 /* TLS Offset Within TLS Block. */
+#define R_MICROBLAZE_TLSGOTTPREL32 28 /* TLS Offset From Thread Pointer. */
+#define R_MICROBLAZE_TLSTPREL32 29 /* TLS Offset From Thread Pointer. */
+
+/* Legal values for d_tag (dynamic entry type). */
+#define DT_NIOS2_GP 0x70000002 /* Address of _gp. */
+
+/* Nios II relocations. */
+#define R_NIOS2_NONE 0 /* No reloc. */
+#define R_NIOS2_S16 1 /* Direct signed 16 bit. */
+#define R_NIOS2_U16 2 /* Direct unsigned 16 bit. */
+#define R_NIOS2_PCREL16 3 /* PC relative 16 bit. */
+#define R_NIOS2_CALL26 4 /* Direct call. */
+#define R_NIOS2_IMM5 5 /* 5 bit constant expression. */
+#define R_NIOS2_CACHE_OPX 6 /* 5 bit expression, shift 22. */
+#define R_NIOS2_IMM6 7 /* 6 bit constant expression. */
+#define R_NIOS2_IMM8 8 /* 8 bit constant expression. */
+#define R_NIOS2_HI16 9 /* High 16 bit. */
+#define R_NIOS2_LO16 10 /* Low 16 bit. */
+#define R_NIOS2_HIADJ16 11 /* High 16 bit, adjusted. */
+#define R_NIOS2_BFD_RELOC_32 12 /* 32 bit symbol value + addend. */
+#define R_NIOS2_BFD_RELOC_16 13 /* 16 bit symbol value + addend. */
+#define R_NIOS2_BFD_RELOC_8 14 /* 8 bit symbol value + addend. */
+#define R_NIOS2_GPREL 15 /* 16 bit GP pointer offset. */
+#define R_NIOS2_GNU_VTINHERIT 16 /* GNU C++ vtable hierarchy. */
+#define R_NIOS2_GNU_VTENTRY 17 /* GNU C++ vtable member usage. */
+#define R_NIOS2_UJMP 18 /* Unconditional branch. */
+#define R_NIOS2_CJMP 19 /* Conditional branch. */
+#define R_NIOS2_CALLR 20 /* Indirect call through register. */
+#define R_NIOS2_ALIGN 21 /* Alignment requirement for
+ linker relaxation. */
+#define R_NIOS2_GOT16 22 /* 16 bit GOT entry. */
+#define R_NIOS2_CALL16 23 /* 16 bit GOT entry for function. */
+#define R_NIOS2_GOTOFF_LO 24 /* %lo of offset to GOT pointer. */
+#define R_NIOS2_GOTOFF_HA 25 /* %hiadj of offset to GOT pointer. */
+#define R_NIOS2_PCREL_LO 26 /* %lo of PC relative offset. */
+#define R_NIOS2_PCREL_HA 27 /* %hiadj of PC relative offset. */
+#define R_NIOS2_TLS_GD16 28 /* 16 bit GOT offset for TLS GD. */
+#define R_NIOS2_TLS_LDM16 29 /* 16 bit GOT offset for TLS LDM. */
+#define R_NIOS2_TLS_LDO16 30 /* 16 bit module relative offset. */
+#define R_NIOS2_TLS_IE16 31 /* 16 bit GOT offset for TLS IE. */
+#define R_NIOS2_TLS_LE16 32 /* 16 bit LE TP-relative offset. */
+#define R_NIOS2_TLS_DTPMOD 33 /* Module number. */
+#define R_NIOS2_TLS_DTPREL 34 /* Module-relative offset. */
+#define R_NIOS2_TLS_TPREL 35 /* TP-relative offset. */
+#define R_NIOS2_COPY 36 /* Copy symbol at runtime. */
+#define R_NIOS2_GLOB_DAT 37 /* Create GOT entry. */
+#define R_NIOS2_JUMP_SLOT 38 /* Create PLT entry. */
+#define R_NIOS2_RELATIVE 39 /* Adjust by program base. */
+#define R_NIOS2_GOTOFF 40 /* 16 bit offset to GOT pointer. */
+#define R_NIOS2_CALL26_NOAT 41 /* Direct call in .noat section. */
+#define R_NIOS2_GOT_LO 42 /* %lo() of GOT entry. */
+#define R_NIOS2_GOT_HA 43 /* %hiadj() of GOT entry. */
+#define R_NIOS2_CALL_LO 44 /* %lo() of function GOT entry. */
+#define R_NIOS2_CALL_HA 45 /* %hiadj() of function GOT entry. */
+
+/* TILEPro relocations. */
+#define R_TILEPRO_NONE 0 /* No reloc */
+#define R_TILEPRO_32 1 /* Direct 32 bit */
+#define R_TILEPRO_16 2 /* Direct 16 bit */
+#define R_TILEPRO_8 3 /* Direct 8 bit */
+#define R_TILEPRO_32_PCREL 4 /* PC relative 32 bit */
+#define R_TILEPRO_16_PCREL 5 /* PC relative 16 bit */
+#define R_TILEPRO_8_PCREL 6 /* PC relative 8 bit */
+#define R_TILEPRO_LO16 7 /* Low 16 bit */
+#define R_TILEPRO_HI16 8 /* High 16 bit */
+#define R_TILEPRO_HA16 9 /* High 16 bit, adjusted */
+#define R_TILEPRO_COPY 10 /* Copy relocation */
+#define R_TILEPRO_GLOB_DAT 11 /* Create GOT entry */
+#define R_TILEPRO_JMP_SLOT 12 /* Create PLT entry */
+#define R_TILEPRO_RELATIVE 13 /* Adjust by program base */
+#define R_TILEPRO_BROFF_X1 14 /* X1 pipe branch offset */
+#define R_TILEPRO_JOFFLONG_X1 15 /* X1 pipe jump offset */
+#define R_TILEPRO_JOFFLONG_X1_PLT 16 /* X1 pipe jump offset to PLT */
+#define R_TILEPRO_IMM8_X0 17 /* X0 pipe 8-bit */
+#define R_TILEPRO_IMM8_Y0 18 /* Y0 pipe 8-bit */
+#define R_TILEPRO_IMM8_X1 19 /* X1 pipe 8-bit */
+#define R_TILEPRO_IMM8_Y1 20 /* Y1 pipe 8-bit */
+#define R_TILEPRO_MT_IMM15_X1 21 /* X1 pipe mtspr */
+#define R_TILEPRO_MF_IMM15_X1 22 /* X1 pipe mfspr */
+#define R_TILEPRO_IMM16_X0 23 /* X0 pipe 16-bit */
+#define R_TILEPRO_IMM16_X1 24 /* X1 pipe 16-bit */
+#define R_TILEPRO_IMM16_X0_LO 25 /* X0 pipe low 16-bit */
+#define R_TILEPRO_IMM16_X1_LO 26 /* X1 pipe low 16-bit */
+#define R_TILEPRO_IMM16_X0_HI 27 /* X0 pipe high 16-bit */
+#define R_TILEPRO_IMM16_X1_HI 28 /* X1 pipe high 16-bit */
+#define R_TILEPRO_IMM16_X0_HA 29 /* X0 pipe high 16-bit, adjusted */
+#define R_TILEPRO_IMM16_X1_HA 30 /* X1 pipe high 16-bit, adjusted */
+#define R_TILEPRO_IMM16_X0_PCREL 31 /* X0 pipe PC relative 16 bit */
+#define R_TILEPRO_IMM16_X1_PCREL 32 /* X1 pipe PC relative 16 bit */
+#define R_TILEPRO_IMM16_X0_LO_PCREL 33 /* X0 pipe PC relative low 16 bit */
+#define R_TILEPRO_IMM16_X1_LO_PCREL 34 /* X1 pipe PC relative low 16 bit */
+#define R_TILEPRO_IMM16_X0_HI_PCREL 35 /* X0 pipe PC relative high 16 bit */
+#define R_TILEPRO_IMM16_X1_HI_PCREL 36 /* X1 pipe PC relative high 16 bit */
+#define R_TILEPRO_IMM16_X0_HA_PCREL 37 /* X0 pipe PC relative ha() 16 bit */
+#define R_TILEPRO_IMM16_X1_HA_PCREL 38 /* X1 pipe PC relative ha() 16 bit */
+#define R_TILEPRO_IMM16_X0_GOT 39 /* X0 pipe 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X1_GOT 40 /* X1 pipe 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X0_GOT_LO 41 /* X0 pipe low 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X1_GOT_LO 42 /* X1 pipe low 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X0_GOT_HI 43 /* X0 pipe high 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X1_GOT_HI 44 /* X1 pipe high 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X0_GOT_HA 45 /* X0 pipe ha() 16-bit GOT offset */
+#define R_TILEPRO_IMM16_X1_GOT_HA 46 /* X1 pipe ha() 16-bit GOT offset */
+#define R_TILEPRO_MMSTART_X0 47 /* X0 pipe mm "start" */
+#define R_TILEPRO_MMEND_X0 48 /* X0 pipe mm "end" */
+#define R_TILEPRO_MMSTART_X1 49 /* X1 pipe mm "start" */
+#define R_TILEPRO_MMEND_X1 50 /* X1 pipe mm "end" */
+#define R_TILEPRO_SHAMT_X0 51 /* X0 pipe shift amount */
+#define R_TILEPRO_SHAMT_X1 52 /* X1 pipe shift amount */
+#define R_TILEPRO_SHAMT_Y0 53 /* Y0 pipe shift amount */
+#define R_TILEPRO_SHAMT_Y1 54 /* Y1 pipe shift amount */
+#define R_TILEPRO_DEST_IMM8_X1 55 /* X1 pipe destination 8-bit */
+/* Relocs 56-59 are currently not defined. */
+#define R_TILEPRO_TLS_GD_CALL 60 /* "jal" for TLS GD */
+#define R_TILEPRO_IMM8_X0_TLS_GD_ADD 61 /* X0 pipe "addi" for TLS GD */
+#define R_TILEPRO_IMM8_X1_TLS_GD_ADD 62 /* X1 pipe "addi" for TLS GD */
+#define R_TILEPRO_IMM8_Y0_TLS_GD_ADD 63 /* Y0 pipe "addi" for TLS GD */
+#define R_TILEPRO_IMM8_Y1_TLS_GD_ADD 64 /* Y1 pipe "addi" for TLS GD */
+#define R_TILEPRO_TLS_IE_LOAD 65 /* "lw_tls" for TLS IE */
+#define R_TILEPRO_IMM16_X0_TLS_GD 66 /* X0 pipe 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X1_TLS_GD 67 /* X1 pipe 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X0_TLS_GD_LO 68 /* X0 pipe low 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X1_TLS_GD_LO 69 /* X1 pipe low 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X0_TLS_GD_HI 70 /* X0 pipe high 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X1_TLS_GD_HI 71 /* X1 pipe high 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X0_TLS_GD_HA 72 /* X0 pipe ha() 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X1_TLS_GD_HA 73 /* X1 pipe ha() 16-bit TLS GD offset */
+#define R_TILEPRO_IMM16_X0_TLS_IE 74 /* X0 pipe 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X1_TLS_IE 75 /* X1 pipe 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X0_TLS_IE_LO 76 /* X0 pipe low 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X1_TLS_IE_LO 77 /* X1 pipe low 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X0_TLS_IE_HI 78 /* X0 pipe high 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X1_TLS_IE_HI 79 /* X1 pipe high 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X0_TLS_IE_HA 80 /* X0 pipe ha() 16-bit TLS IE offset */
+#define R_TILEPRO_IMM16_X1_TLS_IE_HA 81 /* X1 pipe ha() 16-bit TLS IE offset */
+#define R_TILEPRO_TLS_DTPMOD32 82 /* ID of module containing symbol */
+#define R_TILEPRO_TLS_DTPOFF32 83 /* Offset in TLS block */
+#define R_TILEPRO_TLS_TPOFF32 84 /* Offset in static TLS block */
+#define R_TILEPRO_IMM16_X0_TLS_LE 85 /* X0 pipe 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X1_TLS_LE 86 /* X1 pipe 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X0_TLS_LE_LO 87 /* X0 pipe low 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X1_TLS_LE_LO 88 /* X1 pipe low 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X0_TLS_LE_HI 89 /* X0 pipe high 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X1_TLS_LE_HI 90 /* X1 pipe high 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X0_TLS_LE_HA 91 /* X0 pipe ha() 16-bit TLS LE offset */
+#define R_TILEPRO_IMM16_X1_TLS_LE_HA 92 /* X1 pipe ha() 16-bit TLS LE offset */
+
+#define R_TILEPRO_GNU_VTINHERIT 128 /* GNU C++ vtable hierarchy */
+#define R_TILEPRO_GNU_VTENTRY 129 /* GNU C++ vtable member usage */
+
+#define R_TILEPRO_NUM 130
+
+
+/* TILE-Gx relocations. */
+#define R_TILEGX_NONE 0 /* No reloc */
+#define R_TILEGX_64 1 /* Direct 64 bit */
+#define R_TILEGX_32 2 /* Direct 32 bit */
+#define R_TILEGX_16 3 /* Direct 16 bit */
+#define R_TILEGX_8 4 /* Direct 8 bit */
+#define R_TILEGX_64_PCREL 5 /* PC relative 64 bit */
+#define R_TILEGX_32_PCREL 6 /* PC relative 32 bit */
+#define R_TILEGX_16_PCREL 7 /* PC relative 16 bit */
+#define R_TILEGX_8_PCREL 8 /* PC relative 8 bit */
+#define R_TILEGX_HW0 9 /* hword 0 16-bit */
+#define R_TILEGX_HW1 10 /* hword 1 16-bit */
+#define R_TILEGX_HW2 11 /* hword 2 16-bit */
+#define R_TILEGX_HW3 12 /* hword 3 16-bit */
+#define R_TILEGX_HW0_LAST 13 /* last hword 0 16-bit */
+#define R_TILEGX_HW1_LAST 14 /* last hword 1 16-bit */
+#define R_TILEGX_HW2_LAST 15 /* last hword 2 16-bit */
+#define R_TILEGX_COPY 16 /* Copy relocation */
+#define R_TILEGX_GLOB_DAT 17 /* Create GOT entry */
+#define R_TILEGX_JMP_SLOT 18 /* Create PLT entry */
+#define R_TILEGX_RELATIVE 19 /* Adjust by program base */
+#define R_TILEGX_BROFF_X1 20 /* X1 pipe branch offset */
+#define R_TILEGX_JUMPOFF_X1 21 /* X1 pipe jump offset */
+#define R_TILEGX_JUMPOFF_X1_PLT 22 /* X1 pipe jump offset to PLT */
+#define R_TILEGX_IMM8_X0 23 /* X0 pipe 8-bit */
+#define R_TILEGX_IMM8_Y0 24 /* Y0 pipe 8-bit */
+#define R_TILEGX_IMM8_X1 25 /* X1 pipe 8-bit */
+#define R_TILEGX_IMM8_Y1 26 /* Y1 pipe 8-bit */
+#define R_TILEGX_DEST_IMM8_X1 27 /* X1 pipe destination 8-bit */
+#define R_TILEGX_MT_IMM14_X1 28 /* X1 pipe mtspr */
+#define R_TILEGX_MF_IMM14_X1 29 /* X1 pipe mfspr */
+#define R_TILEGX_MMSTART_X0 30 /* X0 pipe mm "start" */
+#define R_TILEGX_MMEND_X0 31 /* X0 pipe mm "end" */
+#define R_TILEGX_SHAMT_X0 32 /* X0 pipe shift amount */
+#define R_TILEGX_SHAMT_X1 33 /* X1 pipe shift amount */
+#define R_TILEGX_SHAMT_Y0 34 /* Y0 pipe shift amount */
+#define R_TILEGX_SHAMT_Y1 35 /* Y1 pipe shift amount */
+#define R_TILEGX_IMM16_X0_HW0 36 /* X0 pipe hword 0 */
+#define R_TILEGX_IMM16_X1_HW0 37 /* X1 pipe hword 0 */
+#define R_TILEGX_IMM16_X0_HW1 38 /* X0 pipe hword 1 */
+#define R_TILEGX_IMM16_X1_HW1 39 /* X1 pipe hword 1 */
+#define R_TILEGX_IMM16_X0_HW2 40 /* X0 pipe hword 2 */
+#define R_TILEGX_IMM16_X1_HW2 41 /* X1 pipe hword 2 */
+#define R_TILEGX_IMM16_X0_HW3 42 /* X0 pipe hword 3 */
+#define R_TILEGX_IMM16_X1_HW3 43 /* X1 pipe hword 3 */
+#define R_TILEGX_IMM16_X0_HW0_LAST 44 /* X0 pipe last hword 0 */
+#define R_TILEGX_IMM16_X1_HW0_LAST 45 /* X1 pipe last hword 0 */
+#define R_TILEGX_IMM16_X0_HW1_LAST 46 /* X0 pipe last hword 1 */
+#define R_TILEGX_IMM16_X1_HW1_LAST 47 /* X1 pipe last hword 1 */
+#define R_TILEGX_IMM16_X0_HW2_LAST 48 /* X0 pipe last hword 2 */
+#define R_TILEGX_IMM16_X1_HW2_LAST 49 /* X1 pipe last hword 2 */
+#define R_TILEGX_IMM16_X0_HW0_PCREL 50 /* X0 pipe PC relative hword 0 */
+#define R_TILEGX_IMM16_X1_HW0_PCREL 51 /* X1 pipe PC relative hword 0 */
+#define R_TILEGX_IMM16_X0_HW1_PCREL 52 /* X0 pipe PC relative hword 1 */
+#define R_TILEGX_IMM16_X1_HW1_PCREL 53 /* X1 pipe PC relative hword 1 */
+#define R_TILEGX_IMM16_X0_HW2_PCREL 54 /* X0 pipe PC relative hword 2 */
+#define R_TILEGX_IMM16_X1_HW2_PCREL 55 /* X1 pipe PC relative hword 2 */
+#define R_TILEGX_IMM16_X0_HW3_PCREL 56 /* X0 pipe PC relative hword 3 */
+#define R_TILEGX_IMM16_X1_HW3_PCREL 57 /* X1 pipe PC relative hword 3 */
+#define R_TILEGX_IMM16_X0_HW0_LAST_PCREL 58 /* X0 pipe PC-rel last hword 0 */
+#define R_TILEGX_IMM16_X1_HW0_LAST_PCREL 59 /* X1 pipe PC-rel last hword 0 */
+#define R_TILEGX_IMM16_X0_HW1_LAST_PCREL 60 /* X0 pipe PC-rel last hword 1 */
+#define R_TILEGX_IMM16_X1_HW1_LAST_PCREL 61 /* X1 pipe PC-rel last hword 1 */
+#define R_TILEGX_IMM16_X0_HW2_LAST_PCREL 62 /* X0 pipe PC-rel last hword 2 */
+#define R_TILEGX_IMM16_X1_HW2_LAST_PCREL 63 /* X1 pipe PC-rel last hword 2 */
+#define R_TILEGX_IMM16_X0_HW0_GOT 64 /* X0 pipe hword 0 GOT offset */
+#define R_TILEGX_IMM16_X1_HW0_GOT 65 /* X1 pipe hword 0 GOT offset */
+#define R_TILEGX_IMM16_X0_HW0_PLT_PCREL 66 /* X0 pipe PC-rel PLT hword 0 */
+#define R_TILEGX_IMM16_X1_HW0_PLT_PCREL 67 /* X1 pipe PC-rel PLT hword 0 */
+#define R_TILEGX_IMM16_X0_HW1_PLT_PCREL 68 /* X0 pipe PC-rel PLT hword 1 */
+#define R_TILEGX_IMM16_X1_HW1_PLT_PCREL 69 /* X1 pipe PC-rel PLT hword 1 */
+#define R_TILEGX_IMM16_X0_HW2_PLT_PCREL 70 /* X0 pipe PC-rel PLT hword 2 */
+#define R_TILEGX_IMM16_X1_HW2_PLT_PCREL 71 /* X1 pipe PC-rel PLT hword 2 */
+#define R_TILEGX_IMM16_X0_HW0_LAST_GOT 72 /* X0 pipe last hword 0 GOT offset */
+#define R_TILEGX_IMM16_X1_HW0_LAST_GOT 73 /* X1 pipe last hword 0 GOT offset */
+#define R_TILEGX_IMM16_X0_HW1_LAST_GOT 74 /* X0 pipe last hword 1 GOT offset */
+#define R_TILEGX_IMM16_X1_HW1_LAST_GOT 75 /* X1 pipe last hword 1 GOT offset */
+#define R_TILEGX_IMM16_X0_HW3_PLT_PCREL 76 /* X0 pipe PC-rel PLT hword 3 */
+#define R_TILEGX_IMM16_X1_HW3_PLT_PCREL 77 /* X1 pipe PC-rel PLT hword 3 */
+#define R_TILEGX_IMM16_X0_HW0_TLS_GD 78 /* X0 pipe hword 0 TLS GD offset */
+#define R_TILEGX_IMM16_X1_HW0_TLS_GD 79 /* X1 pipe hword 0 TLS GD offset */
+#define R_TILEGX_IMM16_X0_HW0_TLS_LE 80 /* X0 pipe hword 0 TLS LE offset */
+#define R_TILEGX_IMM16_X1_HW0_TLS_LE 81 /* X1 pipe hword 0 TLS LE offset */
+#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_LE 82 /* X0 pipe last hword 0 LE off */
+#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_LE 83 /* X1 pipe last hword 0 LE off */
+#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_LE 84 /* X0 pipe last hword 1 LE off */
+#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_LE 85 /* X1 pipe last hword 1 LE off */
+#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_GD 86 /* X0 pipe last hword 0 GD off */
+#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_GD 87 /* X1 pipe last hword 0 GD off */
+#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_GD 88 /* X0 pipe last hword 1 GD off */
+#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_GD 89 /* X1 pipe last hword 1 GD off */
+/* Relocs 90-91 are currently not defined. */
+#define R_TILEGX_IMM16_X0_HW0_TLS_IE 92 /* X0 pipe hword 0 TLS IE offset */
+#define R_TILEGX_IMM16_X1_HW0_TLS_IE 93 /* X1 pipe hword 0 TLS IE offset */
+#define R_TILEGX_IMM16_X0_HW0_LAST_PLT_PCREL 94 /* X0 pipe PC-rel PLT last hword 0 */
+#define R_TILEGX_IMM16_X1_HW0_LAST_PLT_PCREL 95 /* X1 pipe PC-rel PLT last hword 0 */
+#define R_TILEGX_IMM16_X0_HW1_LAST_PLT_PCREL 96 /* X0 pipe PC-rel PLT last hword 1 */
+#define R_TILEGX_IMM16_X1_HW1_LAST_PLT_PCREL 97 /* X1 pipe PC-rel PLT last hword 1 */
+#define R_TILEGX_IMM16_X0_HW2_LAST_PLT_PCREL 98 /* X0 pipe PC-rel PLT last hword 2 */
+#define R_TILEGX_IMM16_X1_HW2_LAST_PLT_PCREL 99 /* X1 pipe PC-rel PLT last hword 2 */
+#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_IE 100 /* X0 pipe last hword 0 IE off */
+#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_IE 101 /* X1 pipe last hword 0 IE off */
+#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_IE 102 /* X0 pipe last hword 1 IE off */
+#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_IE 103 /* X1 pipe last hword 1 IE off */
+/* Relocs 104-105 are currently not defined. */
+#define R_TILEGX_TLS_DTPMOD64 106 /* 64-bit ID of symbol's module */
+#define R_TILEGX_TLS_DTPOFF64 107 /* 64-bit offset in TLS block */
+#define R_TILEGX_TLS_TPOFF64 108 /* 64-bit offset in static TLS block */
+#define R_TILEGX_TLS_DTPMOD32 109 /* 32-bit ID of symbol's module */
+#define R_TILEGX_TLS_DTPOFF32 110 /* 32-bit offset in TLS block */
+#define R_TILEGX_TLS_TPOFF32 111 /* 32-bit offset in static TLS block */
+#define R_TILEGX_TLS_GD_CALL 112 /* "jal" for TLS GD */
+#define R_TILEGX_IMM8_X0_TLS_GD_ADD 113 /* X0 pipe "addi" for TLS GD */
+#define R_TILEGX_IMM8_X1_TLS_GD_ADD 114 /* X1 pipe "addi" for TLS GD */
+#define R_TILEGX_IMM8_Y0_TLS_GD_ADD 115 /* Y0 pipe "addi" for TLS GD */
+#define R_TILEGX_IMM8_Y1_TLS_GD_ADD 116 /* Y1 pipe "addi" for TLS GD */
+#define R_TILEGX_TLS_IE_LOAD 117 /* "ld_tls" for TLS IE */
+#define R_TILEGX_IMM8_X0_TLS_ADD 118 /* X0 pipe "addi" for TLS GD/IE */
+#define R_TILEGX_IMM8_X1_TLS_ADD 119 /* X1 pipe "addi" for TLS GD/IE */
+#define R_TILEGX_IMM8_Y0_TLS_ADD 120 /* Y0 pipe "addi" for TLS GD/IE */
+#define R_TILEGX_IMM8_Y1_TLS_ADD 121 /* Y1 pipe "addi" for TLS GD/IE */
+
+#define R_TILEGX_GNU_VTINHERIT 128 /* GNU C++ vtable hierarchy */
+#define R_TILEGX_GNU_VTENTRY 129 /* GNU C++ vtable member usage */
+
+#define R_TILEGX_NUM 130
+
+/* RISC-V ELF Flags */
+#define EF_RISCV_RVC 0x0001
+#define EF_RISCV_FLOAT_ABI 0x0006
+#define EF_RISCV_FLOAT_ABI_SOFT 0x0000
+#define EF_RISCV_FLOAT_ABI_SINGLE 0x0002
+#define EF_RISCV_FLOAT_ABI_DOUBLE 0x0004
+#define EF_RISCV_FLOAT_ABI_QUAD 0x0006
+#define EF_RISCV_RVE 0x0008
+#define EF_RISCV_TSO 0x0010
+
+/* RISC-V relocations. */
+#define R_RISCV_NONE 0
+#define R_RISCV_32 1
+#define R_RISCV_64 2
+#define R_RISCV_RELATIVE 3
+#define R_RISCV_COPY 4
+#define R_RISCV_JUMP_SLOT 5
+#define R_RISCV_TLS_DTPMOD32 6
+#define R_RISCV_TLS_DTPMOD64 7
+#define R_RISCV_TLS_DTPREL32 8
+#define R_RISCV_TLS_DTPREL64 9
+#define R_RISCV_TLS_TPREL32 10
+#define R_RISCV_TLS_TPREL64 11
+#define R_RISCV_BRANCH 16
+#define R_RISCV_JAL 17
+#define R_RISCV_CALL 18
+#define R_RISCV_CALL_PLT 19
+#define R_RISCV_GOT_HI20 20
+#define R_RISCV_TLS_GOT_HI20 21
+#define R_RISCV_TLS_GD_HI20 22
+#define R_RISCV_PCREL_HI20 23
+#define R_RISCV_PCREL_LO12_I 24
+#define R_RISCV_PCREL_LO12_S 25
+#define R_RISCV_HI20 26
+#define R_RISCV_LO12_I 27
+#define R_RISCV_LO12_S 28
+#define R_RISCV_TPREL_HI20 29
+#define R_RISCV_TPREL_LO12_I 30
+#define R_RISCV_TPREL_LO12_S 31
+#define R_RISCV_TPREL_ADD 32
+#define R_RISCV_ADD8 33
+#define R_RISCV_ADD16 34
+#define R_RISCV_ADD32 35
+#define R_RISCV_ADD64 36
+#define R_RISCV_SUB8 37
+#define R_RISCV_SUB16 38
+#define R_RISCV_SUB32 39
+#define R_RISCV_SUB64 40
+#define R_RISCV_GNU_VTINHERIT 41
+#define R_RISCV_GNU_VTENTRY 42
+#define R_RISCV_ALIGN 43
+#define R_RISCV_RVC_BRANCH 44
+#define R_RISCV_RVC_JUMP 45
+#define R_RISCV_RVC_LUI 46
+#define R_RISCV_GPREL_I 47
+#define R_RISCV_GPREL_S 48
+#define R_RISCV_TPREL_I 49
+#define R_RISCV_TPREL_S 50
+#define R_RISCV_RELAX 51
+#define R_RISCV_SUB6 52
+#define R_RISCV_SET6 53
+#define R_RISCV_SET8 54
+#define R_RISCV_SET16 55
+#define R_RISCV_SET32 56
+#define R_RISCV_32_PCREL 57
+#define R_RISCV_IRELATIVE 58
+
+#define R_RISCV_NUM 59
+
+/* RISC-V specific values for the st_other field. */
+#define STO_RISCV_VARIANT_CC 0x80 /* Function uses variant calling
+ convention */
+
+/* RISC-V specific values for the sh_type field. */
+#define SHT_RISCV_ATTRIBUTES (SHT_LOPROC + 3)
+
+/* RISC-V specific values for the p_type field. */
+#define PT_RISCV_ATTRIBUTES (PT_LOPROC + 3)
+
+/* RISC-V specific values for the d_tag field. */
+#define DT_RISCV_VARIANT_CC (DT_LOPROC + 1)
+
+/* BPF specific declarations. */
+
+#define R_BPF_NONE 0 /* No reloc */
+#define R_BPF_64_64 1
+#define R_BPF_64_32 10
+
+/* Imagination Meta specific relocations. */
+
+#define R_METAG_HIADDR16 0
+#define R_METAG_LOADDR16 1
+#define R_METAG_ADDR32 2 /* 32bit absolute address */
+#define R_METAG_NONE 3 /* No reloc */
+#define R_METAG_RELBRANCH 4
+#define R_METAG_GETSETOFF 5
+
+/* Backward compatibility */
+#define R_METAG_REG32OP1 6
+#define R_METAG_REG32OP2 7
+#define R_METAG_REG32OP3 8
+#define R_METAG_REG16OP1 9
+#define R_METAG_REG16OP2 10
+#define R_METAG_REG16OP3 11
+#define R_METAG_REG32OP4 12
+
+#define R_METAG_HIOG 13
+#define R_METAG_LOOG 14
+
+#define R_METAG_REL8 15
+#define R_METAG_REL16 16
+
+/* GNU */
+#define R_METAG_GNU_VTINHERIT 30
+#define R_METAG_GNU_VTENTRY 31
+
+/* PIC relocations */
+#define R_METAG_HI16_GOTOFF 32
+#define R_METAG_LO16_GOTOFF 33
+#define R_METAG_GETSET_GOTOFF 34
+#define R_METAG_GETSET_GOT 35
+#define R_METAG_HI16_GOTPC 36
+#define R_METAG_LO16_GOTPC 37
+#define R_METAG_HI16_PLT 38
+#define R_METAG_LO16_PLT 39
+#define R_METAG_RELBRANCH_PLT 40
+#define R_METAG_GOTOFF 41
+#define R_METAG_PLT 42
+#define R_METAG_COPY 43
+#define R_METAG_JMP_SLOT 44
+#define R_METAG_RELATIVE 45
+#define R_METAG_GLOB_DAT 46
+
+/* TLS relocations */
+#define R_METAG_TLS_GD 47
+#define R_METAG_TLS_LDM 48
+#define R_METAG_TLS_LDO_HI16 49
+#define R_METAG_TLS_LDO_LO16 50
+#define R_METAG_TLS_LDO 51
+#define R_METAG_TLS_IE 52
+#define R_METAG_TLS_IENONPIC 53
+#define R_METAG_TLS_IENONPIC_HI16 54
+#define R_METAG_TLS_IENONPIC_LO16 55
+#define R_METAG_TLS_TPOFF 56
+#define R_METAG_TLS_DTPMOD 57
+#define R_METAG_TLS_DTPOFF 58
+#define R_METAG_TLS_LE 59
+#define R_METAG_TLS_LE_HI16 60
+#define R_METAG_TLS_LE_LO16 61
+
+/* NDS32 relocations. */
+#define R_NDS32_NONE 0
+#define R_NDS32_32_RELA 20
+#define R_NDS32_COPY 39
+#define R_NDS32_GLOB_DAT 40
+#define R_NDS32_JMP_SLOT 41
+#define R_NDS32_RELATIVE 42
+#define R_NDS32_TLS_TPOFF 102
+#define R_NDS32_TLS_DESC 119
+
+/* LoongArch ELF Flags */
+#define EF_LARCH_ABI_MODIFIER_MASK 0x07
+#define EF_LARCH_ABI_SOFT_FLOAT 0x01
+#define EF_LARCH_ABI_SINGLE_FLOAT 0x02
+#define EF_LARCH_ABI_DOUBLE_FLOAT 0x03
+#define EF_LARCH_OBJABI_V1 0x40
+
+/* LoongArch specific dynamic relocations */
+#define R_LARCH_NONE 0
+#define R_LARCH_32 1
+#define R_LARCH_64 2
+#define R_LARCH_RELATIVE 3
+#define R_LARCH_COPY 4
+#define R_LARCH_JUMP_SLOT 5
+#define R_LARCH_TLS_DTPMOD32 6
+#define R_LARCH_TLS_DTPMOD64 7
+#define R_LARCH_TLS_DTPREL32 8
+#define R_LARCH_TLS_DTPREL64 9
+#define R_LARCH_TLS_TPREL32 10
+#define R_LARCH_TLS_TPREL64 11
+#define R_LARCH_IRELATIVE 12
+
+/* Reserved for future relocs that the dynamic linker must understand. */
+
+/* used by the static linker for relocating .text. */
+#define R_LARCH_MARK_LA 20
+#define R_LARCH_MARK_PCREL 21
+#define R_LARCH_SOP_PUSH_PCREL 22
+#define R_LARCH_SOP_PUSH_ABSOLUTE 23
+#define R_LARCH_SOP_PUSH_DUP 24
+#define R_LARCH_SOP_PUSH_GPREL 25
+#define R_LARCH_SOP_PUSH_TLS_TPREL 26
+#define R_LARCH_SOP_PUSH_TLS_GOT 27
+#define R_LARCH_SOP_PUSH_TLS_GD 28
+#define R_LARCH_SOP_PUSH_PLT_PCREL 29
+#define R_LARCH_SOP_ASSERT 30
+#define R_LARCH_SOP_NOT 31
+#define R_LARCH_SOP_SUB 32
+#define R_LARCH_SOP_SL 33
+#define R_LARCH_SOP_SR 34
+#define R_LARCH_SOP_ADD 35
+#define R_LARCH_SOP_AND 36
+#define R_LARCH_SOP_IF_ELSE 37
+#define R_LARCH_SOP_POP_32_S_10_5 38
+#define R_LARCH_SOP_POP_32_U_10_12 39
+#define R_LARCH_SOP_POP_32_S_10_12 40
+#define R_LARCH_SOP_POP_32_S_10_16 41
+#define R_LARCH_SOP_POP_32_S_10_16_S2 42
+#define R_LARCH_SOP_POP_32_S_5_20 43
+#define R_LARCH_SOP_POP_32_S_0_5_10_16_S2 44
+#define R_LARCH_SOP_POP_32_S_0_10_10_16_S2 45
+#define R_LARCH_SOP_POP_32_U 46
+
+/* used by the static linker for relocating non .text. */
+#define R_LARCH_ADD8 47
+#define R_LARCH_ADD16 48
+#define R_LARCH_ADD24 49
+#define R_LARCH_ADD32 50
+#define R_LARCH_ADD64 51
+#define R_LARCH_SUB8 52
+#define R_LARCH_SUB16 53
+#define R_LARCH_SUB24 54
+#define R_LARCH_SUB32 55
+#define R_LARCH_SUB64 56
+#define R_LARCH_GNU_VTINHERIT 57
+#define R_LARCH_GNU_VTENTRY 58
+
+/* reserved 59-63 */
+
+#define R_LARCH_B16 64
+#define R_LARCH_B21 65
+#define R_LARCH_B26 66
+#define R_LARCH_ABS_HI20 67
+#define R_LARCH_ABS_LO12 68
+#define R_LARCH_ABS64_LO20 69
+#define R_LARCH_ABS64_HI12 70
+#define R_LARCH_PCALA_HI20 71
+#define R_LARCH_PCALA_LO12 72
+#define R_LARCH_PCALA64_LO20 73
+#define R_LARCH_PCALA64_HI12 74
+#define R_LARCH_GOT_PC_HI20 75
+#define R_LARCH_GOT_PC_LO12 76
+#define R_LARCH_GOT64_PC_LO20 77
+#define R_LARCH_GOT64_PC_HI12 78
+#define R_LARCH_GOT_HI20 79
+#define R_LARCH_GOT_LO12 80
+#define R_LARCH_GOT64_LO20 81
+#define R_LARCH_GOT64_HI12 82
+#define R_LARCH_TLS_LE_HI20 83
+#define R_LARCH_TLS_LE_LO12 84
+#define R_LARCH_TLS_LE64_LO20 85
+#define R_LARCH_TLS_LE64_HI12 86
+#define R_LARCH_TLS_IE_PC_HI20 87
+#define R_LARCH_TLS_IE_PC_LO12 88
+#define R_LARCH_TLS_IE64_PC_LO20 89
+#define R_LARCH_TLS_IE64_PC_HI12 90
+#define R_LARCH_TLS_IE_HI20 91
+#define R_LARCH_TLS_IE_LO12 92
+#define R_LARCH_TLS_IE64_LO20 93
+#define R_LARCH_TLS_IE64_HI12 94
+#define R_LARCH_TLS_LD_PC_HI20 95
+#define R_LARCH_TLS_LD_HI20 96
+#define R_LARCH_TLS_GD_PC_HI20 97
+#define R_LARCH_TLS_GD_HI20 98
+#define R_LARCH_32_PCREL 99
+#define R_LARCH_RELAX 100
+
+/* ARC specific declarations. */
+
+/* Processor specific flags for the Ehdr e_flags field. */
+#define EF_ARC_MACH_MSK 0x000000ff
+#define EF_ARC_OSABI_MSK 0x00000f00
+#define EF_ARC_ALL_MSK (EF_ARC_MACH_MSK | EF_ARC_OSABI_MSK)
+
+/* Processor specific values for the Shdr sh_type field. */
+#define SHT_ARC_ATTRIBUTES (SHT_LOPROC + 1) /* ARC attributes section. */
+
+/* ARCompact/ARCv2 specific relocs. */
+#define R_ARC_NONE 0x0
+#define R_ARC_8 0x1
+#define R_ARC_16 0x2
+#define R_ARC_24 0x3
+#define R_ARC_32 0x4
+
+#define R_ARC_B22_PCREL 0x6
+#define R_ARC_H30 0x7
+#define R_ARC_N8 0x8
+#define R_ARC_N16 0x9
+#define R_ARC_N24 0xA
+#define R_ARC_N32 0xB
+#define R_ARC_SDA 0xC
+#define R_ARC_SECTOFF 0xD
+#define R_ARC_S21H_PCREL 0xE
+#define R_ARC_S21W_PCREL 0xF
+#define R_ARC_S25H_PCREL 0x10
+#define R_ARC_S25W_PCREL 0x11
+#define R_ARC_SDA32 0x12
+#define R_ARC_SDA_LDST 0x13
+#define R_ARC_SDA_LDST1 0x14
+#define R_ARC_SDA_LDST2 0x15
+#define R_ARC_SDA16_LD 0x16
+#define R_ARC_SDA16_LD1 0x17
+#define R_ARC_SDA16_LD2 0x18
+#define R_ARC_S13_PCREL 0x19
+#define R_ARC_W 0x1A
+#define R_ARC_32_ME 0x1B
+#define R_ARC_N32_ME 0x1C
+#define R_ARC_SECTOFF_ME 0x1D
+#define R_ARC_SDA32_ME 0x1E
+#define R_ARC_W_ME 0x1F
+#define R_ARC_H30_ME 0x20
+#define R_ARC_SECTOFF_U8 0x21
+#define R_ARC_SECTOFF_S9 0x22
+#define R_AC_SECTOFF_U8 0x23
+#define R_AC_SECTOFF_U8_1 0x24
+#define R_AC_SECTOFF_U8_2 0x25
+#define R_AC_SECTOFF_S9 0x26
+#define R_AC_SECTOFF_S9_1 0x27
+#define R_AC_SECTOFF_S9_2 0x28
+#define R_ARC_SECTOFF_ME_1 0x29
+#define R_ARC_SECTOFF_ME_2 0x2A
+#define R_ARC_SECTOFF_1 0x2B
+#define R_ARC_SECTOFF_2 0x2C
+#define R_ARC_SDA_12 0x2D
+#define R_ARC_SDA16_ST2 0x30
+#define R_ARC_32_PCREL 0x31
+#define R_ARC_PC32 0x32
+#define R_ARC_GOTPC32 0x33
+#define R_ARC_PLT32 0x34
+#define R_ARC_COPY 0x35
+#define R_ARC_GLOB_DAT 0x36
+#define R_ARC_JMP_SLOT 0x37
+#define R_ARC_RELATIVE 0x38
+#define R_ARC_GOTOFF 0x39
+#define R_ARC_GOTPC 0x3A
+#define R_ARC_GOT32 0x3B
+#define R_ARC_S21W_PCREL_PLT 0x3C
+#define R_ARC_S25H_PCREL_PLT 0x3D
+
+#define R_ARC_JLI_SECTOFF 0x3F
+
+#define R_ARC_TLS_DTPMOD 0x42
+#define R_ARC_TLS_DTPOFF 0x43
+#define R_ARC_TLS_TPOFF 0x44
+#define R_ARC_TLS_GD_GOT 0x45
+#define R_ARC_TLS_GD_LD 0x46
+#define R_ARC_TLS_GD_CALL 0x47
+#define R_ARC_TLS_IE_GOT 0x48
+#define R_ARC_TLS_DTPOFF_S9 0x49
+#define R_ARC_TLS_LE_S9 0x4A
+#define R_ARC_TLS_LE_32 0x4B
+#define R_ARC_S25W_PCREL_PLT 0x4C
+#define R_ARC_S21H_PCREL_PLT 0x4D
+#define R_ARC_NPS_CMEM16 0x4E
+
+/* OpenRISC 1000 specific relocs. */
+#define R_OR1K_NONE 0
+#define R_OR1K_32 1
+#define R_OR1K_16 2
+#define R_OR1K_8 3
+#define R_OR1K_LO_16_IN_INSN 4
+#define R_OR1K_HI_16_IN_INSN 5
+#define R_OR1K_INSN_REL_26 6
+#define R_OR1K_GNU_VTENTRY 7
+#define R_OR1K_GNU_VTINHERIT 8
+#define R_OR1K_32_PCREL 9
+#define R_OR1K_16_PCREL 10
+#define R_OR1K_8_PCREL 11
+#define R_OR1K_GOTPC_HI16 12
+#define R_OR1K_GOTPC_LO16 13
+#define R_OR1K_GOT16 14
+#define R_OR1K_PLT26 15
+#define R_OR1K_GOTOFF_HI16 16
+#define R_OR1K_GOTOFF_LO16 17
+#define R_OR1K_COPY 18
+#define R_OR1K_GLOB_DAT 19
+#define R_OR1K_JMP_SLOT 20
+#define R_OR1K_RELATIVE 21
+#define R_OR1K_TLS_GD_HI16 22
+#define R_OR1K_TLS_GD_LO16 23
+#define R_OR1K_TLS_LDM_HI16 24
+#define R_OR1K_TLS_LDM_LO16 25
+#define R_OR1K_TLS_LDO_HI16 26
+#define R_OR1K_TLS_LDO_LO16 27
+#define R_OR1K_TLS_IE_HI16 28
+#define R_OR1K_TLS_IE_LO16 29
+#define R_OR1K_TLS_LE_HI16 30
+#define R_OR1K_TLS_LE_LO16 31
+#define R_OR1K_TLS_TPOFF 32
+#define R_OR1K_TLS_DTPOFF 33
+#define R_OR1K_TLS_DTPMOD 34
+
+#endif /* elf.h */
diff --git a/tools/include/endian.h b/tools/include/endian.h
new file mode 100644
index 0000000..f625689
--- /dev/null
+++ b/tools/include/endian.h
@@ -0,0 +1,88 @@
+#ifndef __endian_compat_h
+#define __endian_compat_h
+
+#if defined(__linux__) || defined(__CYGWIN__)
+#include <byteswap.h>
+#include_next <endian.h>
+#elif defined(__APPLE__)
+#include <netinet/in.h>
+#include <libkern/OSByteOrder.h>
+#define bswap_16(x) OSSwapInt16(x)
+#define bswap_32(x) OSSwapInt32(x)
+#define bswap_64(x) OSSwapInt64(x)
+#elif defined(__FreeBSD__)
+#include <sys/endian.h>
+#define bswap_16(x) bswap16(x)
+#define bswap_32(x) bswap32(x)
+#define bswap_64(x) bswap64(x)
+#elif defined(__OpenBSD__)
+#include <sys/types.h>
+#define bswap_16(x) __swap16(x)
+#define bswap_32(x) __swap32(x)
+#define bswap_64(x) __swap64(x)
+#else
+#include <machine/endian.h>
+#define bswap_16(x) swap16(x)
+#define bswap_32(x) swap32(x)
+#define bswap_64(x) swap64(x)
+#endif
+
+#ifndef __BYTE_ORDER
+#define __BYTE_ORDER BYTE_ORDER
+#endif
+#ifndef __BIG_ENDIAN
+#define __BIG_ENDIAN BIG_ENDIAN
+#endif
+#ifndef __LITTLE_ENDIAN
+#define __LITTLE_ENDIAN LITTLE_ENDIAN
+#endif
+
+#ifndef __linux__
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define htobe16(x) bswap_16(x)
+#define be16toh(x) bswap_16(x)
+#define htobe32(x) bswap_32(x)
+#define be32toh(x) bswap_32(x)
+#define htobe64(x) bswap_64(x)
+#define be64toh(x) bswap_64(x)
+#define htole16(x) (uint16_t)(x)
+#define le16toh(x) (uint16_t)(x)
+#define htole32(x) (uint32_t)(x)
+#define le32toh(x) (uint32_t)(x)
+#define htole64(x) (uint64_t)(x)
+#define le64toh(x) (uint64_t)(x)
+#else
+#define htobe16(x) (uint16_t)(x)
+#define be16toh(x) (uint16_t)(x)
+#define htobe32(x) (uint32_t)(x)
+#define be32toh(x) (uint32_t)(x)
+#define htobe64(x) (uint64_t)(x)
+#define be64toh(x) (uint64_t)(x)
+#define htole16(x) bswap_16(x)
+#define le16toh(x) bswap_16(x)
+#define htole32(x) bswap_32(x)
+#define le32toh(x) bswap_32(x)
+#define htole64(x) bswap_64(x)
+#define le64toh(x) bswap_64(x)
+#endif
+
+#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define betoh16(x) bswap_16(x)
+#define betoh32(x) bswap_32(x)
+#define betoh64(x) bswap_64(x)
+#define letoh16(x) (uint16_t)(x)
+#define letoh32(x) (uint32_t)(x)
+#define letoh64(x) (uint64_t)(x)
+#else
+#define betoh16(x) (uint16_t)(x)
+#define betoh32(x) (uint32_t)(x)
+#define betoh64(x) (uint64_t)(x)
+#define letoh16(x) bswap_16(x)
+#define letoh32(x) bswap_32(x)
+#define letoh64(x) bswap_64(x)
+#endif
+#endif
+#endif
+
+#endif
diff --git a/tools/include/linux/big_endian.h b/tools/include/linux/big_endian.h
new file mode 100644
index 0000000..3bb87c5
--- /dev/null
+++ b/tools/include/linux/big_endian.h
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _LINUX_BYTEORDER_BIG_ENDIAN_H
+#define _LINUX_BYTEORDER_BIG_ENDIAN_H
+
+#ifndef __BIG_ENDIAN
+#define __BIG_ENDIAN 4321
+#endif
+#ifndef __BIG_ENDIAN_BITFIELD
+#define __BIG_ENDIAN_BITFIELD
+#endif
+
+#include <linux/stddef.h>
+#include <linux/types.h>
+#include <linux/swab.h>
+
+#define __constant_htonl(x) ((__be32)(__u32)(x))
+#define __constant_ntohl(x) ((__u32)(__be32)(x))
+#define __constant_htons(x) ((__be16)(__u16)(x))
+#define __constant_ntohs(x) ((__u16)(__be16)(x))
+#define __constant_cpu_to_le64(x) ((__le64)___constant_swab64((x)))
+#define __constant_le64_to_cpu(x) ___constant_swab64((__u64)(__le64)(x))
+#define __constant_cpu_to_le32(x) ((__le32)___constant_swab32((x)))
+#define __constant_le32_to_cpu(x) ___constant_swab32((__u32)(__le32)(x))
+#define __constant_cpu_to_le16(x) ((__le16)___constant_swab16((x)))
+#define __constant_le16_to_cpu(x) ___constant_swab16((__u16)(__le16)(x))
+#define __constant_cpu_to_be64(x) ((__be64)(__u64)(x))
+#define __constant_be64_to_cpu(x) ((__u64)(__be64)(x))
+#define __constant_cpu_to_be32(x) ((__be32)(__u32)(x))
+#define __constant_be32_to_cpu(x) ((__u32)(__be32)(x))
+#define __constant_cpu_to_be16(x) ((__be16)(__u16)(x))
+#define __constant_be16_to_cpu(x) ((__u16)(__be16)(x))
+#define __cpu_to_le64(x) ((__le64)__swab64((x)))
+#define __le64_to_cpu(x) __swab64((__u64)(__le64)(x))
+#define __cpu_to_le32(x) ((__le32)__swab32((x)))
+#define __le32_to_cpu(x) __swab32((__u32)(__le32)(x))
+#define __cpu_to_le16(x) ((__le16)__swab16((x)))
+#define __le16_to_cpu(x) __swab16((__u16)(__le16)(x))
+#define __cpu_to_be64(x) ((__be64)(__u64)(x))
+#define __be64_to_cpu(x) ((__u64)(__be64)(x))
+#define __cpu_to_be32(x) ((__be32)(__u32)(x))
+#define __be32_to_cpu(x) ((__u32)(__be32)(x))
+#define __cpu_to_be16(x) ((__be16)(__u16)(x))
+#define __be16_to_cpu(x) ((__u16)(__be16)(x))
+
+static __always_inline __le64 __cpu_to_le64p(const __u64 *p)
+{
+ return (__le64)__swab64p(p);
+}
+static __always_inline __u64 __le64_to_cpup(const __le64 *p)
+{
+ return __swab64p((__u64 *)p);
+}
+static __always_inline __le32 __cpu_to_le32p(const __u32 *p)
+{
+ return (__le32)__swab32p(p);
+}
+static __always_inline __u32 __le32_to_cpup(const __le32 *p)
+{
+ return __swab32p((__u32 *)p);
+}
+static __always_inline __le16 __cpu_to_le16p(const __u16 *p)
+{
+ return (__le16)__swab16p(p);
+}
+static __always_inline __u16 __le16_to_cpup(const __le16 *p)
+{
+ return __swab16p((__u16 *)p);
+}
+static __always_inline __be64 __cpu_to_be64p(const __u64 *p)
+{
+ return (__be64)*p;
+}
+static __always_inline __u64 __be64_to_cpup(const __be64 *p)
+{
+ return (__u64)*p;
+}
+static __always_inline __be32 __cpu_to_be32p(const __u32 *p)
+{
+ return (__be32)*p;
+}
+static __always_inline __u32 __be32_to_cpup(const __be32 *p)
+{
+ return (__u32)*p;
+}
+static __always_inline __be16 __cpu_to_be16p(const __u16 *p)
+{
+ return (__be16)*p;
+}
+static __always_inline __u16 __be16_to_cpup(const __be16 *p)
+{
+ return (__u16)*p;
+}
+#define __cpu_to_le64s(x) __swab64s((x))
+#define __le64_to_cpus(x) __swab64s((x))
+#define __cpu_to_le32s(x) __swab32s((x))
+#define __le32_to_cpus(x) __swab32s((x))
+#define __cpu_to_le16s(x) __swab16s((x))
+#define __le16_to_cpus(x) __swab16s((x))
+#define __cpu_to_be64s(x) do { (void)(x); } while (0)
+#define __be64_to_cpus(x) do { (void)(x); } while (0)
+#define __cpu_to_be32s(x) do { (void)(x); } while (0)
+#define __be32_to_cpus(x) do { (void)(x); } while (0)
+#define __cpu_to_be16s(x) do { (void)(x); } while (0)
+#define __be16_to_cpus(x) do { (void)(x); } while (0)
+
+
+#endif /* _LINUX_BYTEORDER_BIG_ENDIAN_H */
diff --git a/tools/include/linux/errno.h b/tools/include/linux/errno.h
new file mode 100644
index 0000000..70f2bd3
--- /dev/null
+++ b/tools/include/linux/errno.h
@@ -0,0 +1 @@
+#include <asm/errno.h>
diff --git a/tools/include/linux/little_endian.h b/tools/include/linux/little_endian.h
new file mode 100644
index 0000000..ba6c199
--- /dev/null
+++ b/tools/include/linux/little_endian.h
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _LINUX_BYTEORDER_LITTLE_ENDIAN_H
+#define _LINUX_BYTEORDER_LITTLE_ENDIAN_H
+
+#ifndef __LITTLE_ENDIAN
+#define __LITTLE_ENDIAN 1234
+#endif
+#ifndef __LITTLE_ENDIAN_BITFIELD
+#define __LITTLE_ENDIAN_BITFIELD
+#endif
+
+#include <linux/stddef.h>
+#include <linux/types.h>
+#include <linux/swab.h>
+
+#define __constant_htonl(x) ((__be32)___constant_swab32((x)))
+#define __constant_ntohl(x) ___constant_swab32((__be32)(x))
+#define __constant_htons(x) ((__be16)___constant_swab16((x)))
+#define __constant_ntohs(x) ___constant_swab16((__be16)(x))
+#define __constant_cpu_to_le64(x) ((__le64)(__u64)(x))
+#define __constant_le64_to_cpu(x) ((__u64)(__le64)(x))
+#define __constant_cpu_to_le32(x) ((__le32)(__u32)(x))
+#define __constant_le32_to_cpu(x) ((__u32)(__le32)(x))
+#define __constant_cpu_to_le16(x) ((__le16)(__u16)(x))
+#define __constant_le16_to_cpu(x) ((__u16)(__le16)(x))
+#define __constant_cpu_to_be64(x) ((__be64)___constant_swab64((x)))
+#define __constant_be64_to_cpu(x) ___constant_swab64((__u64)(__be64)(x))
+#define __constant_cpu_to_be32(x) ((__be32)___constant_swab32((x)))
+#define __constant_be32_to_cpu(x) ___constant_swab32((__u32)(__be32)(x))
+#define __constant_cpu_to_be16(x) ((__be16)___constant_swab16((x)))
+#define __constant_be16_to_cpu(x) ___constant_swab16((__u16)(__be16)(x))
+#define __cpu_to_le64(x) ((__le64)(__u64)(x))
+#define __le64_to_cpu(x) ((__u64)(__le64)(x))
+#define __cpu_to_le32(x) ((__le32)(__u32)(x))
+#define __le32_to_cpu(x) ((__u32)(__le32)(x))
+#define __cpu_to_le16(x) ((__le16)(__u16)(x))
+#define __le16_to_cpu(x) ((__u16)(__le16)(x))
+#define __cpu_to_be64(x) ((__be64)__swab64((x)))
+#define __be64_to_cpu(x) __swab64((__u64)(__be64)(x))
+#define __cpu_to_be32(x) ((__be32)__swab32((x)))
+#define __be32_to_cpu(x) __swab32((__u32)(__be32)(x))
+#define __cpu_to_be16(x) ((__be16)__swab16((x)))
+#define __be16_to_cpu(x) __swab16((__u16)(__be16)(x))
+
+static __always_inline __le64 __cpu_to_le64p(const __u64 *p)
+{
+ return (__le64)*p;
+}
+static __always_inline __u64 __le64_to_cpup(const __le64 *p)
+{
+ return (__u64)*p;
+}
+static __always_inline __le32 __cpu_to_le32p(const __u32 *p)
+{
+ return (__le32)*p;
+}
+static __always_inline __u32 __le32_to_cpup(const __le32 *p)
+{
+ return (__u32)*p;
+}
+static __always_inline __le16 __cpu_to_le16p(const __u16 *p)
+{
+ return (__le16)*p;
+}
+static __always_inline __u16 __le16_to_cpup(const __le16 *p)
+{
+ return (__u16)*p;
+}
+static __always_inline __be64 __cpu_to_be64p(const __u64 *p)
+{
+ return (__be64)__swab64p(p);
+}
+static __always_inline __u64 __be64_to_cpup(const __be64 *p)
+{
+ return __swab64p((__u64 *)p);
+}
+static __always_inline __be32 __cpu_to_be32p(const __u32 *p)
+{
+ return (__be32)__swab32p(p);
+}
+static __always_inline __u32 __be32_to_cpup(const __be32 *p)
+{
+ return __swab32p((__u32 *)p);
+}
+static __always_inline __be16 __cpu_to_be16p(const __u16 *p)
+{
+ return (__be16)__swab16p(p);
+}
+static __always_inline __u16 __be16_to_cpup(const __be16 *p)
+{
+ return __swab16p((__u16 *)p);
+}
+#define __cpu_to_le64s(x) do { (void)(x); } while (0)
+#define __le64_to_cpus(x) do { (void)(x); } while (0)
+#define __cpu_to_le32s(x) do { (void)(x); } while (0)
+#define __le32_to_cpus(x) do { (void)(x); } while (0)
+#define __cpu_to_le16s(x) do { (void)(x); } while (0)
+#define __le16_to_cpus(x) do { (void)(x); } while (0)
+#define __cpu_to_be64s(x) __swab64s((x))
+#define __be64_to_cpus(x) __swab64s((x))
+#define __cpu_to_be32s(x) __swab32s((x))
+#define __be32_to_cpus(x) __swab32s((x))
+#define __cpu_to_be16s(x) __swab16s((x))
+#define __be16_to_cpus(x) __swab16s((x))
+
+
+#endif /* _LINUX_BYTEORDER_LITTLE_ENDIAN_H */
diff --git a/tools/include/linux/stddef.h b/tools/include/linux/stddef.h
new file mode 100644
index 0000000..e3d20e7
--- /dev/null
+++ b/tools/include/linux/stddef.h
@@ -0,0 +1,56 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _UAPI_LINUX_STDDEF_H
+#define _UAPI_LINUX_STDDEF_H
+
+#ifndef __always_inline
+#define __always_inline inline
+#endif
+
+/**
+ * __struct_group() - Create a mirrored named and anonyomous struct
+ *
+ * @TAG: The tag name for the named sub-struct (usually empty)
+ * @NAME: The identifier name of the mirrored sub-struct
+ * @ATTRS: Any struct attributes (usually empty)
+ * @MEMBERS: The member declarations for the mirrored structs
+ *
+ * Used to create an anonymous union of two structs with identical layout
+ * and size: one anonymous and one named. The former's members can be used
+ * normally without sub-struct naming, and the latter can be used to
+ * reason about the start, end, and size of the group of struct members.
+ * The named struct can also be explicitly tagged for layer reuse, as well
+ * as both having struct attributes appended.
+ */
+#define __struct_group(TAG, NAME, ATTRS, MEMBERS...) \
+ union { \
+ struct { MEMBERS } ATTRS; \
+ struct TAG { MEMBERS } ATTRS NAME; \
+ } ATTRS
+
+#ifdef __cplusplus
+/* sizeof(struct{}) is 1 in C++, not 0, can't use C version of the macro. */
+#define __DECLARE_FLEX_ARRAY(T, member) \
+ T member[0]
+#else
+/**
+ * __DECLARE_FLEX_ARRAY() - Declare a flexible array usable in a union
+ *
+ * @TYPE: The type of each flexible array element
+ * @NAME: The name of the flexible array member
+ *
+ * In order to have a flexible array member in a union or alone in a
+ * struct, it needs to be wrapped in an anonymous struct with at least 1
+ * named member, but that member can be empty.
+ */
+#define __DECLARE_FLEX_ARRAY(TYPE, NAME) \
+ struct { \
+ struct { } __empty_ ## NAME; \
+ TYPE NAME[]; \
+ }
+#endif
+
+#ifndef __counted_by
+#define __counted_by(m)
+#endif
+
+#endif /* _UAPI_LINUX_STDDEF_H */
diff --git a/tools/include/linux/swab.h b/tools/include/linux/swab.h
new file mode 100644
index 0000000..7e3bad5
--- /dev/null
+++ b/tools/include/linux/swab.h
@@ -0,0 +1,305 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+#ifndef _LINUX_SWAB_H
+#define _LINUX_SWAB_H
+
+#include <linux/types.h>
+#include <linux/stddef.h>
+#include <asm/bitsperlong.h>
+#include <asm/swab.h>
+
+/*
+ * casts are necessary for constants, because we never know how for sure
+ * how U/UL/ULL map to __u16, __u32, __u64. At least not in a portable way.
+ */
+#define ___constant_swab16(x) ((__u16)( \
+ (((__u16)(x) & (__u16)0x00ffU) << 8) | \
+ (((__u16)(x) & (__u16)0xff00U) >> 8)))
+
+#define ___constant_swab32(x) ((__u32)( \
+ (((__u32)(x) & (__u32)0x000000ffUL) << 24) | \
+ (((__u32)(x) & (__u32)0x0000ff00UL) << 8) | \
+ (((__u32)(x) & (__u32)0x00ff0000UL) >> 8) | \
+ (((__u32)(x) & (__u32)0xff000000UL) >> 24)))
+
+#define ___constant_swab64(x) ((__u64)( \
+ (((__u64)(x) & (__u64)0x00000000000000ffULL) << 56) | \
+ (((__u64)(x) & (__u64)0x000000000000ff00ULL) << 40) | \
+ (((__u64)(x) & (__u64)0x0000000000ff0000ULL) << 24) | \
+ (((__u64)(x) & (__u64)0x00000000ff000000ULL) << 8) | \
+ (((__u64)(x) & (__u64)0x000000ff00000000ULL) >> 8) | \
+ (((__u64)(x) & (__u64)0x0000ff0000000000ULL) >> 24) | \
+ (((__u64)(x) & (__u64)0x00ff000000000000ULL) >> 40) | \
+ (((__u64)(x) & (__u64)0xff00000000000000ULL) >> 56)))
+
+#define ___constant_swahw32(x) ((__u32)( \
+ (((__u32)(x) & (__u32)0x0000ffffUL) << 16) | \
+ (((__u32)(x) & (__u32)0xffff0000UL) >> 16)))
+
+#define ___constant_swahb32(x) ((__u32)( \
+ (((__u32)(x) & (__u32)0x00ff00ffUL) << 8) | \
+ (((__u32)(x) & (__u32)0xff00ff00UL) >> 8)))
+
+/*
+ * Implement the following as inlines, but define the interface using
+ * macros to allow constant folding when possible:
+ * ___swab16, ___swab32, ___swab64, ___swahw32, ___swahb32
+ */
+
+static __inline__ __u16 __fswab16(__u16 val)
+{
+#if defined (__arch_swab16)
+ return __arch_swab16(val);
+#else
+ return ___constant_swab16(val);
+#endif
+}
+
+static __inline__ __u32 __fswab32(__u32 val)
+{
+#if defined(__arch_swab32)
+ return __arch_swab32(val);
+#else
+ return ___constant_swab32(val);
+#endif
+}
+
+static __inline__ __u64 __fswab64(__u64 val)
+{
+#if defined (__arch_swab64)
+ return __arch_swab64(val);
+#elif defined(__SWAB_64_THRU_32__)
+ __u32 h = val >> 32;
+ __u32 l = val & ((1ULL << 32) - 1);
+ return (((__u64)__fswab32(l)) << 32) | ((__u64)(__fswab32(h)));
+#else
+ return ___constant_swab64(val);
+#endif
+}
+
+static __inline__ __u32 __fswahw32(__u32 val)
+{
+#ifdef __arch_swahw32
+ return __arch_swahw32(val);
+#else
+ return ___constant_swahw32(val);
+#endif
+}
+
+static __inline__ __u32 __fswahb32(__u32 val)
+{
+#ifdef __arch_swahb32
+ return __arch_swahb32(val);
+#else
+ return ___constant_swahb32(val);
+#endif
+}
+
+/**
+ * __swab16 - return a byteswapped 16-bit value
+ * @x: value to byteswap
+ */
+#ifdef __HAVE_BUILTIN_BSWAP16__
+#define __swab16(x) (__u16)__builtin_bswap16((__u16)(x))
+#else
+#define __swab16(x) \
+ (__u16)(__builtin_constant_p(x) ? \
+ ___constant_swab16(x) : \
+ __fswab16(x))
+#endif
+
+/**
+ * __swab32 - return a byteswapped 32-bit value
+ * @x: value to byteswap
+ */
+#ifdef __HAVE_BUILTIN_BSWAP32__
+#define __swab32(x) (__u32)__builtin_bswap32((__u32)(x))
+#else
+#define __swab32(x) \
+ (__u32)(__builtin_constant_p(x) ? \
+ ___constant_swab32(x) : \
+ __fswab32(x))
+#endif
+
+/**
+ * __swab64 - return a byteswapped 64-bit value
+ * @x: value to byteswap
+ */
+#ifdef __HAVE_BUILTIN_BSWAP64__
+#define __swab64(x) (__u64)__builtin_bswap64((__u64)(x))
+#else
+#define __swab64(x) \
+ (__u64)(__builtin_constant_p(x) ? \
+ ___constant_swab64(x) : \
+ __fswab64(x))
+#endif
+
+static __always_inline unsigned long __swab(const unsigned long y)
+{
+#if __BITS_PER_LONG == 64
+ return __swab64(y);
+#else /* __BITS_PER_LONG == 32 */
+ return __swab32(y);
+#endif
+}
+
+/**
+ * __swahw32 - return a word-swapped 32-bit value
+ * @x: value to wordswap
+ *
+ * __swahw32(0x12340000) is 0x00001234
+ */
+#define __swahw32(x) \
+ (__builtin_constant_p((__u32)(x)) ? \
+ ___constant_swahw32(x) : \
+ __fswahw32(x))
+
+/**
+ * __swahb32 - return a high and low byte-swapped 32-bit value
+ * @x: value to byteswap
+ *
+ * __swahb32(0x12345678) is 0x34127856
+ */
+#define __swahb32(x) \
+ (__builtin_constant_p((__u32)(x)) ? \
+ ___constant_swahb32(x) : \
+ __fswahb32(x))
+
+/**
+ * __swab16p - return a byteswapped 16-bit value from a pointer
+ * @p: pointer to a naturally-aligned 16-bit value
+ */
+static __always_inline __u16 __swab16p(const __u16 *p)
+{
+#ifdef __arch_swab16p
+ return __arch_swab16p(p);
+#else
+ return __swab16(*p);
+#endif
+}
+
+/**
+ * __swab32p - return a byteswapped 32-bit value from a pointer
+ * @p: pointer to a naturally-aligned 32-bit value
+ */
+static __always_inline __u32 __swab32p(const __u32 *p)
+{
+#ifdef __arch_swab32p
+ return __arch_swab32p(p);
+#else
+ return __swab32(*p);
+#endif
+}
+
+/**
+ * __swab64p - return a byteswapped 64-bit value from a pointer
+ * @p: pointer to a naturally-aligned 64-bit value
+ */
+static __always_inline __u64 __swab64p(const __u64 *p)
+{
+#ifdef __arch_swab64p
+ return __arch_swab64p(p);
+#else
+ return __swab64(*p);
+#endif
+}
+
+/**
+ * __swahw32p - return a wordswapped 32-bit value from a pointer
+ * @p: pointer to a naturally-aligned 32-bit value
+ *
+ * See __swahw32() for details of wordswapping.
+ */
+static __inline__ __u32 __swahw32p(const __u32 *p)
+{
+#ifdef __arch_swahw32p
+ return __arch_swahw32p(p);
+#else
+ return __swahw32(*p);
+#endif
+}
+
+/**
+ * __swahb32p - return a high and low byteswapped 32-bit value from a pointer
+ * @p: pointer to a naturally-aligned 32-bit value
+ *
+ * See __swahb32() for details of high/low byteswapping.
+ */
+static __inline__ __u32 __swahb32p(const __u32 *p)
+{
+#ifdef __arch_swahb32p
+ return __arch_swahb32p(p);
+#else
+ return __swahb32(*p);
+#endif
+}
+
+/**
+ * __swab16s - byteswap a 16-bit value in-place
+ * @p: pointer to a naturally-aligned 16-bit value
+ */
+static __inline__ void __swab16s(__u16 *p)
+{
+#ifdef __arch_swab16s
+ __arch_swab16s(p);
+#else
+ *p = __swab16p(p);
+#endif
+}
+/**
+ * __swab32s - byteswap a 32-bit value in-place
+ * @p: pointer to a naturally-aligned 32-bit value
+ */
+static __always_inline void __swab32s(__u32 *p)
+{
+#ifdef __arch_swab32s
+ __arch_swab32s(p);
+#else
+ *p = __swab32p(p);
+#endif
+}
+
+/**
+ * __swab64s - byteswap a 64-bit value in-place
+ * @p: pointer to a naturally-aligned 64-bit value
+ */
+static __always_inline void __swab64s(__u64 *p)
+{
+#ifdef __arch_swab64s
+ __arch_swab64s(p);
+#else
+ *p = __swab64p(p);
+#endif
+}
+
+/**
+ * __swahw32s - wordswap a 32-bit value in-place
+ * @p: pointer to a naturally-aligned 32-bit value
+ *
+ * See __swahw32() for details of wordswapping
+ */
+static __inline__ void __swahw32s(__u32 *p)
+{
+#ifdef __arch_swahw32s
+ __arch_swahw32s(p);
+#else
+ *p = __swahw32p(p);
+#endif
+}
+
+/**
+ * __swahb32s - high and low byteswap a 32-bit value in-place
+ * @p: pointer to a naturally-aligned 32-bit value
+ *
+ * See __swahb32() for details of high and low byte swapping
+ */
+static __inline__ void __swahb32s(__u32 *p)
+{
+#ifdef __arch_swahb32s
+ __arch_swahb32s(p);
+#else
+ *p = __swahb32p(p);
+#endif
+}
+
+
+#endif /* _LINUX_SWAB_H */
diff --git a/tools/include/sys/sysmacros.h b/tools/include/sys/sysmacros.h
new file mode 100644
index 0000000..997d928
--- /dev/null
+++ b/tools/include/sys/sysmacros.h
@@ -0,0 +1,56 @@
+/* Definitions of macros to access `dev_t' values.
+ Copyright (C) 1996, 1997, 1999, 2003, 2004 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+
+ The GNU C Library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ The GNU C Library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with the GNU C Library; if not, write to the Free
+ Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+ 02111-1307 USA. */
+
+#ifndef __SYS_SYSMACROS_H
+#define __SYS_SYSMACROS_H 1
+
+static inline unsigned int
+__gnu_dev_major(unsigned long long int __dev)
+{
+ return ((__dev >> 8) & 0xfff) | ((unsigned int) (__dev >> 32) & ~0xfff);
+}
+
+static inline unsigned int
+__gnu_dev_minor(unsigned long long int __dev)
+{
+ return (__dev & 0xff) | ((unsigned int) (__dev >> 12) & ~0xff);
+}
+
+static inline unsigned long long int
+__gnu_dev_makedev(unsigned int __major, unsigned int __minor)
+{
+ return ((__minor & 0xff) | ((__major & 0xfff) << 8)
+ | (((unsigned long long int) (__minor & ~0xff)) << 12)
+ | (((unsigned long long int) (__major & ~0xfff)) << 32));
+}
+
+/* Access the functions with their traditional names. */
+#ifndef major
+# define major(dev) __gnu_dev_major (dev)
+#endif
+
+#ifndef minor
+# define minor(dev) __gnu_dev_minor (dev)
+#endif
+
+#ifndef makedev
+# define makedev(maj, min) __gnu_dev_makedev (maj, min)
+#endif
+
+#endif /* sys/sysmacros.h */
diff --git a/tools/isl/Makefile b/tools/isl/Makefile
new file mode 100644
index 0000000..1ce20fb
--- /dev/null
+++ b/tools/isl/Makefile
@@ -0,0 +1,31 @@
+#
+# Copyright (C) 2009-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=isl
+PKG_VERSION:=0.26
+
+PKG_SOURCE_URL:=https://libisl.sourceforge.io/
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_HASH:=b10473024cbf17d7db85323121eff0e50f03de14342a03738b4d384b587ce212
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+unexport CFLAGS
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static \
+ --disable-shared \
+ --with-gmp-prefix=$(STAGING_DIR_HOST)
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/libdeflate/Makefile b/tools/libdeflate/Makefile
new file mode 100644
index 0000000..8f7946d
--- /dev/null
+++ b/tools/libdeflate/Makefile
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=libdeflate
+PKG_VERSION:=1.22
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/ebiggers/libdeflate/releases/download/v$(PKG_VERSION)
+PKG_HASH:=7834d9adbc9a809e0fb0d7b486060a9ae5f7819eb7f55bb8c22b10d7b3bed8da
+
+include $(INCLUDE_DIR)/host-build.mk
+
+DECOMPRESS_CMD:=$(STAGING_DIR_HOST)/bin/gzip -dc $(DL_DIR)/$(PKG_SOURCE) |
+
+define Host/Compile
+ $(HOSTCC_NOCACHE) $(HOST_CFLAGS) $(HOST_LDFLAGS) \
+ $(HOST_BUILD_DIR)/lib/*{,/*}.c \
+ $(HOST_BUILD_DIR)/programs/{gzip,prog_util,tgetopt}.c \
+ -o $(HOST_BUILD_DIR)/libdeflate-gzip
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/libdeflate-gzip $(STAGING_DIR_HOST)/bin/
+ $(LN) libdeflate-gzip $(STAGING_DIR_HOST)/bin/libdeflate-gunzip
+endef
+
+define Host/Uninstall
+ $(RM) $(STAGING_DIR_HOST)/bin/libdeflate-gzip
+ $(RM) $(STAGING_DIR_HOST)/bin/libdeflate-gunzip
+ $(call Host/Uninstall/Default)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/liblzo/Makefile b/tools/liblzo/Makefile
new file mode 100644
index 0000000..9f60109
--- /dev/null
+++ b/tools/liblzo/Makefile
@@ -0,0 +1,43 @@
+#
+# Copyright (C) 2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=lzo
+PKG_VERSION:=2.10
+PKG_RELEASE:=4
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=http://www.oberhumer.com/opensource/lzo/download/
+PKG_HASH:=c0f892943208266f9b6543b3ae308fab6284c5c90e627931446fb49b4221a072
+
+PKG_LICENSE:=GPL-2.0-or-later
+PKG_LICENSE_FILES:=COPYING
+PKG_CPE_ID:=cpe:/a:lzo_project:lzo
+
+CMAKE_BINARY_SUBDIR:=openwrt-build
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_HOST_OPTIONS += \
+ -DENABLE_SHARED=ON \
+ -DENABLE_TESTS=OFF \
+ -DENABLE_EXAMPLES=OFF \
+ -DENABLE_DOCS=ON \
+ -DBUILD_TESTING=OFF
+
+define Host/Uninstall
+ rm -rf $(HOST_BUILD_PREFIX)/include/lzo
+ rm -f $(HOST_BUILD_PREFIX)/lib/liblzo2.a
+ rm -f $(HOST_BUILD_PREFIX)/lib/liblzo2.so.2.0.0
+ rm -f $(HOST_BUILD_PREFIX)/lib/liblzo2.so.2
+ rm -f $(HOST_BUILD_PREFIX)/lib/liblzo2.so
+ rm -f $(HOST_BUILD_PREFIX)/lib/pkgconfig/lzo2.pc
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/liblzo/patches/001-add-cmake-ENABLE-configurables.patch b/tools/liblzo/patches/001-add-cmake-ENABLE-configurables.patch
new file mode 100644
index 0000000..e0ba410
--- /dev/null
+++ b/tools/liblzo/patches/001-add-cmake-ENABLE-configurables.patch
@@ -0,0 +1,68 @@
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -51,8 +51,11 @@ endif()
+ project(lzo VERSION 2.10 LANGUAGES C)
+
+ # configuration options
+-option(ENABLE_STATIC "Build static LZO library." ON)
+-option(ENABLE_SHARED "Build shared LZO library." OFF)
++option(ENABLE_STATIC "Build static LZO library." ON)
++option(ENABLE_SHARED "Build shared LZO library." OFF)
++option(ENABLE_TESTS "Build tests." ON)
++option(ENABLE_EXAMPLES "Build examples." ON)
++option(ENABLE_DOCS "Install documentation." ON)
+ if(NOT ENABLE_STATIC AND NOT ENABLE_SHARED)
+ set(ENABLE_STATIC ON)
+ endif()
+@@ -127,14 +130,20 @@ macro(lzo_add_executable t)
+ endif()
+ endmacro()
+ # main test driver
++if(ENABLE_TESTS OR ENABLE_EXAMPLES)
+ lzo_add_executable(lzotest lzotest/lzotest.c)
++endif()
+ # examples
++if(ENABLE_EXAMPLES)
+ lzo_add_executable(dict examples/dict.c)
+ lzo_add_executable(lzopack examples/lzopack.c)
+ lzo_add_executable(overlap examples/overlap.c)
+ lzo_add_executable(precomp examples/precomp.c)
+ lzo_add_executable(precomp2 examples/precomp2.c)
++endif()
++if(ENABLE_TESTS OR ENABLE_EXAMPLES)
+ lzo_add_executable(simple examples/simple.c)
++endif()
+ # some boring internal test programs
+ if(0)
+ lzo_add_executable(align tests/align.c)
+@@ -144,7 +153,7 @@ if(0)
+ endif()
+
+ # miniLZO
+-if(1)
++if(ENABLE_TESTS)
+ add_executable(testmini minilzo/testmini.c minilzo/minilzo.c)
+ target_include_directories(testmini PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include/lzo") # needed for "lzoconf.h"
+ endif()
+@@ -263,8 +272,10 @@ add_test(NAME lzotest-03 COMMAND lzotest
+
+ if(DEFINED CMAKE_INSTALL_FULL_LIBDIR)
+
+-set(f AUTHORS COPYING NEWS THANKS doc/LZO.FAQ doc/LZO.TXT doc/LZOAPI.TXT)
+-install(FILES ${f} DESTINATION "${CMAKE_INSTALL_FULL_DOCDIR}")
++if(ENABLE_DOCS)
++ set(f AUTHORS COPYING NEWS THANKS doc/LZO.FAQ doc/LZO.TXT doc/LZOAPI.TXT)
++ install(FILES ${f} DESTINATION "${CMAKE_INSTALL_FULL_DOCDIR}")
++endif()
+
+ set(f include/lzo/lzo1.h include/lzo/lzo1a.h include/lzo/lzo1b.h
+ include/lzo/lzo1c.h include/lzo/lzo1f.h include/lzo/lzo1x.h
+@@ -285,7 +296,7 @@ if(ENABLE_SHARED)
+ )
+ endif()
+
+-if(1)
++if(ENABLE_EXAMPLES)
+ set(f lzopack lzotest simple testmini) # examples
+ install(TARGETS ${f} DESTINATION "${CMAKE_INSTALL_FULL_LIBEXECDIR}/lzo/examples")
+ endif()
diff --git a/tools/libressl/Makefile b/tools/libressl/Makefile
new file mode 100644
index 0000000..4072194
--- /dev/null
+++ b/tools/libressl/Makefile
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2016-2017 LEDE project
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=libressl
+PKG_VERSION:=3.7.3
+PKG_HASH:=7948c856a90c825bd7268b6f85674a8dcd254bae42e221781b24e3f8dc335db3
+
+PKG_CPE_ID:=cpe:/a:openbsd:libressl
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://mirror.ox.ac.uk/pub/OpenBSD/LibreSSL \
+ http://ftp.jaist.ac.jp/pub/OpenBSD/LibreSSL \
+ https://ftp.openbsd.org/pub/OpenBSD/LibreSSL
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+
+HOST_CFLAGS += $(HOST_FPIC)
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static \
+ --disable-shared \
+ --disable-asm \
+ --with-pic \
+ --disable-tests
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/libtool/Makefile b/tools/libtool/Makefile
new file mode 100644
index 0000000..8b73e44
--- /dev/null
+++ b/tools/libtool/Makefile
@@ -0,0 +1,62 @@
+#
+# Copyright (C) 2008-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=libtool
+PKG_CPE_ID:=cpe:/a:gnu:libtool
+PKG_VERSION:=2.4.7
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=04e96c2404ea70c590c546eba4202a4e12722c640016c12b9b2f1ce3d481e9a8
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+export GNULIB_SRCDIR:=$(HOST_GNULIB_SRCDIR)
+
+HOST_CONFIGURE_VARS += \
+ lt_cv_sys_dlsearch_path=""
+
+define Host/Bootstrap
+ ( \
+ cd $(HOST_BUILD_DIR); \
+ $(AM_TOOL_PATHS) \
+ ./bootstrap \
+ --copy \
+ --force \
+ --skip-git \
+ --skip-po \
+ --gnulib-srcdir=$(GNULIB_SRCDIR) \
+ )
+endef
+
+define Host/Prepare
+ $(call Host/Prepare/Default)
+ $(call Host/Uninstall)
+ $(if $(QUILT),,$(call Host/Bootstrap))
+endef
+
+define Host/Configure
+ $(if $(QUILT),$(call Host/Bootstrap))
+ $(call Host/Configure/Default)
+endef
+
+define Host/Install
+ $(call Host/Compile/Default,install)
+ $(SED) 's,\(hardcode_into_libs\)=yes,\1=no,g' $(STAGING_DIR_HOST)/bin/libtool
+ $(CP) $(STAGING_DIR_HOST)/bin/libtool $(STAGING_DIR_HOST)/bin/libtool-ucxx
+ $(SED) 's,-lstdc++,-luClibc++,g' $(STAGING_DIR_HOST)/bin/libtool-ucxx
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+ (cd $(STAGING_DIR_HOST)/share/aclocal/ && rm -f libtool.m4 ltdl.m4 lt~obsolete.m4 ltoptions.m4 ltsugar.m4 ltversion.m4)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/libtool/files/libtool-v1.5.patch b/tools/libtool/files/libtool-v1.5.patch
new file mode 100644
index 0000000..485dfc7
--- /dev/null
+++ b/tools/libtool/files/libtool-v1.5.patch
@@ -0,0 +1,118 @@
+--- a/ltmain.sh
++++ b/ltmain.sh
+@@ -35,7 +35,7 @@ progpath="$0"
+
+ # The name of this program:
+ progname=`echo "$progpath" | $SED $basename`
+-modename="$progname"
++modename="OpenWrt-$progname-patched-1.5"
+
+ # Global variables:
+ EXIT_SUCCESS=0
+@@ -297,8 +297,8 @@ func_infer_tag ()
+ # line option must be used.
+ if test -z "$tagname"; then
+ $echo "$modename: unable to infer tagged configuration"
+- $echo "$modename: specify a tag with \`--tag'" 1>&2
+- exit $EXIT_FAILURE
++ $echo "$modename: defaulting to \`CC'"
++ $echo "$modename: if this is not correct, specify a tag with \`--tag'"
+ # else
+ # $echo "$modename: using $tagname tagged configuration"
+ fi
+@@ -2462,8 +2462,14 @@ EOF
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+- dir="$libdir"
+- absdir="$libdir"
++ # Adding 'libdir' from the .la file to our library search paths
++ # breaks crosscompilation horribly. We cheat here and don't add
++ # it, instead adding the path where we found the .la. -CL
++ dir="$lt_sysroot$abs_ladir"
++ absdir="$abs_ladir"
++ libdir="$abs_ladir"
++ #dir="$libdir"
++ #absdir="$libdir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+@@ -2602,7 +2608,7 @@ EOF
+ { test "$use_static_libs" = no || test -z "$old_library"; }; then
+ if test "$installed" = no; then
+ notinst_deplibs="$notinst_deplibs $lib"
+- need_relink=yes
++ need_relink=no
+ fi
+ # This is a shared library
+
+@@ -2804,7 +2810,6 @@ EOF
+ if test "$hardcode_direct" = yes; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+- add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+@@ -2820,8 +2825,6 @@ EOF
+ add="$libdir/$linklib"
+ fi
+ else
+- # We cannot seem to hardcode it, guess we'll fake it.
+- add_dir="-L$libdir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+@@ -5687,6 +5690,10 @@ fi\
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
++ # Replacing uninstalled with installed can easily break crosscompilation,
++ # since the installed path is generally the wrong architecture. -CL
++ newdependency_libs="$newdependency_libs $deplib"
++ continue
+ case $deplib in
+ *.la)
+ name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
+@@ -5999,8 +6006,12 @@ relink_command=\"$relink_command\""
+ dir="$dir$objdir"
+
+ if test -n "$relink_command"; then
++ # Strip any trailing slash from the destination.
++ s_libdir=`$echo "X$libdir" | $Xsed -e 's%/$%%'`
++ s_destdir=`$echo "X$destdir" | $Xsed -e 's%/$%%'`
++
+ # Determine the prefix the user has applied to our future dir.
+- inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"`
++ inst_prefix_dir=`$echo "$s_destdir" | $SED "s%$s_libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+@@ -6008,10 +6019,13 @@ relink_command=\"$relink_command\""
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+- if test "$inst_prefix_dir" = "$destdir"; then
+- $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
+- exit $EXIT_FAILURE
+- fi
++ #
++ # This breaks install into our staging area. -PB
++ #
++ # if test "$inst_prefix_dir" = "$destdir"; then
++ # $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
++ # exit $EXIT_FAILURE
++ # fi
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+@@ -6020,6 +6034,9 @@ relink_command=\"$relink_command\""
+ relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP`
+ fi
+
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/lib[^[:space:]]*%%"`
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/usr/lib[^[:space:]]*%%"`
++
+ $echo "$modename: warning: relinking \`$file'" 1>&2
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
diff --git a/tools/libtool/files/libtool-v2.2.patch b/tools/libtool/files/libtool-v2.2.patch
new file mode 100644
index 0000000..03994ba
--- /dev/null
+++ b/tools/libtool/files/libtool-v2.2.patch
@@ -0,0 +1,123 @@
+--- a/ltmain.sh
++++ b/ltmain.sh
+@@ -243,7 +243,7 @@ opt_warning=:
+ # name if it has been set yet.
+ func_echo ()
+ {
+- $ECHO "$progname${mode+: }$mode: $*"
++ $ECHO "OpenWrt-$progname-patched-2.2${mode+: }$mode: $*"
+ }
+
+ # func_verbose arg...
+@@ -262,14 +262,14 @@ func_verbose ()
+ # Echo program name prefixed message to standard error.
+ func_error ()
+ {
+- $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2
++ $ECHO "OpenWrt-$progname-patched-2.2${mode+: }$mode: "${1+"$@"} 1>&2
+ }
+
+ # func_warning arg...
+ # Echo program name prefixed warning message to standard error.
+ func_warning ()
+ {
+- $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2
++ $opt_warning && $ECHO "OpenWrt-$progname-patched-2.2${mode+: }$mode: warning: "${1+"$@"} 1>&2
+
+ # bash bug again:
+ :
+@@ -1048,8 +1048,8 @@ func_infer_tag ()
+ # was found and let the user know that the "--tag" command
+ # line option must be used.
+ if test -z "$tagname"; then
+- func_echo "unable to infer tagged configuration"
+- func_fatal_error "specify a tag with \`--tag'"
++ func_echo "defaulting to \`CC'"
++ func_echo "if this is not correct, specify a tag with \`--tag'"
+ # else
+ # func_verbose "using $tagname tagged configuration"
+ fi
+@@ -2009,8 +2009,15 @@ func_mode_install ()
+ dir="$dir$objdir"
+
+ if test -n "$relink_command"; then
++ # Strip any trailing slash from the destination.
++ func_stripname '' '/' "$libdir"
++ s_libdir=$func_stripname_result
++
++ func_stripname '' '/' "$destdir"
++ s_destdir=$func_stripname_result
++
+ # Determine the prefix the user has applied to our future dir.
+- inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"`
++ inst_prefix_dir=`$ECHO "X$s_destdir" | $Xsed -e "s%$s_libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+@@ -2018,8 +2025,11 @@ func_mode_install ()
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+- test "$inst_prefix_dir" = "$destdir" && \
+- func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
++ #
++ # This breaks install into our staging area. -PB
++ #
++ # test "$inst_prefix_dir" = "$destdir" && \
++ # func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+@@ -2028,6 +2038,9 @@ func_mode_install ()
+ relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"`
+ fi
+
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/lib[^[:space:]]*%%"`
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/usr/lib[^[:space:]]*%%"`
++
+ func_warning "relinking \`$file'"
+ func_show_eval "$relink_command" \
+ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+@@ -5412,8 +5425,12 @@ func_mode_link ()
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+- dir="$libdir"
+- absdir="$libdir"
++ # Adding 'libdir' from the .la file to our library search paths
++ # breaks crosscompilation horribly. We cheat here and don't add
++ # it, instead adding the path where we found the .la. -CL
++ dir="$abs_ladir"
++ absdir="$abs_ladir"
++ libdir="$abs_ladir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+@@ -5564,7 +5581,7 @@ func_mode_link ()
+ *)
+ if test "$installed" = no; then
+ notinst_deplibs="$notinst_deplibs $lib"
+- need_relink=yes
++ need_relink=no
+ fi
+ ;;
+ esac
+@@ -5768,7 +5785,6 @@ func_mode_link ()
+ test "$hardcode_direct_absolute" = no; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+- add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+@@ -8052,6 +8068,10 @@ EOF
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
++ # Replacing uninstalled with installed can easily break crosscompilation,
++ # since the installed path is generally the wrong architecture. -CL
++ newdependency_libs="$newdependency_libs $deplib"
++ continue
+ case $deplib in
+ *.la)
+ func_basename "$deplib"
diff --git a/tools/libtool/files/libtool-v2.4.patch b/tools/libtool/files/libtool-v2.4.patch
new file mode 100644
index 0000000..afc754a
--- /dev/null
+++ b/tools/libtool/files/libtool-v2.4.patch
@@ -0,0 +1,160 @@
+--- a/ltmain.sh
++++ b/ltmain.sh
+@@ -443,7 +443,7 @@ opt_warning=:
+ # name if it has been set yet.
+ func_echo ()
+ {
+- $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
++ $ECHO "OpenWrt-$progname-patched-2.4: ${opt_mode+$opt_mode: }$*"
+ }
+
+ # func_verbose arg...
+@@ -469,14 +469,14 @@ func_echo_all ()
+ # Echo program name prefixed message to standard error.
+ func_error ()
+ {
+- $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
++ $ECHO "OpenWrt-$progname-patched-2.4: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
+ }
+
+ # func_warning arg...
+ # Echo program name prefixed warning message to standard error.
+ func_warning ()
+ {
+- $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
++ $opt_warning && $ECHO "OpenWrt-$progname-patched-2.4: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
+
+ # bash bug again:
+ :
+@@ -1416,8 +1416,8 @@ func_infer_tag ()
+ # was found and let the user know that the "--tag" command
+ # line option must be used.
+ if test -z "$tagname"; then
+- func_echo "unable to infer tagged configuration"
+- func_fatal_error "specify a tag with \`--tag'"
++ func_echo "defaulting to \`CC'"
++ func_echo "if this is not correct, specify a tag with \`--tag'"
+ # else
+ # func_verbose "using $tagname tagged configuration"
+ fi
+@@ -2953,8 +2953,15 @@ func_mode_install ()
+ func_append dir "$objdir"
+
+ if test -n "$relink_command"; then
++ # Strip any trailing slash from the destination.
++ func_stripname '' '/' "$libdir"
++ s_libdir=$func_stripname_result
++
++ func_stripname '' '/' "$destdir"
++ s_destdir=$func_stripname_result
++
+ # Determine the prefix the user has applied to our future dir.
+- inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
++ inst_prefix_dir=`$ECHO "$s_destdir" | $SED -e "s%$s_libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+@@ -2962,8 +2969,11 @@ func_mode_install ()
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+- test "$inst_prefix_dir" = "$destdir" && \
+- func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
++ #
++ # This breaks install into our staging area. -PB
++ #
++ # test "$inst_prefix_dir" = "$destdir" && \
++ # func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+@@ -2972,6 +2982,9 @@ func_mode_install ()
+ relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+ fi
+
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/lib[^[:space:]]*%%"`
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/usr/lib[^[:space:]]*%%"`
++
+ func_warning "relinking \`$file'"
+ func_show_eval "$relink_command" \
+ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+@@ -6504,8 +6517,12 @@ func_mode_link ()
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+- dir="$lt_sysroot$libdir"
+- absdir="$lt_sysroot$libdir"
++ # Adding 'libdir' from the .la file to our library search paths
++ # breaks crosscompilation horribly. We cheat here and don't add
++ # it, instead adding the path where we found the .la. -CL
++ dir="$lt_sysroot$abs_ladir"
++ absdir="$abs_ladir"
++ libdir="$abs_ladir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+@@ -6683,7 +6700,7 @@ func_mode_link ()
+ *)
+ if test "$installed" = no; then
+ func_append notinst_deplibs " $lib"
+- need_relink=yes
++ need_relink=no
+ fi
+ ;;
+ esac
+@@ -6887,7 +6904,6 @@ func_mode_link ()
+ test "$hardcode_direct_absolute" = no; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+- add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+@@ -6903,8 +6919,6 @@ func_mode_link ()
+ add="$libdir/$linklib"
+ fi
+ else
+- # We cannot seem to hardcode it, guess we'll fake it.
+- add_dir="-L$libdir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+@@ -7059,7 +7073,17 @@ func_mode_link ()
+ fi
+ ;;
+ *)
+- path="-L$absdir/$objdir"
++ # OE sets installed=no in staging. We need to look in $objdir and $absdir,
++ # preferring $objdir. RP 31/04/2008
++ if test -f "$absdir/$objdir/$depdepl" ; then
++ depdepl="$absdir/$objdir/$depdepl"
++ path="-L$absdir/$objdir"
++ elif test -f "$absdir/$depdepl" ; then
++ depdepl="$absdir/$depdepl"
++ path="-L$absdir"
++ else
++ path="-L$absdir/$objdir"
++ fi
+ ;;
+ esac
+ else
+@@ -8050,7 +8074,7 @@ EOF
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+- *) func_apped perm_rpath " $libdir" ;;
++ *) func_append perm_rpath " $libdir" ;;
+ esac
+ fi
+ done
+@@ -9257,6 +9281,10 @@ EOF
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
++ # Replacing uninstalled with installed can easily break crosscompilation,
++ # since the installed path is generally the wrong architecture. -CL
++ newdependency_libs="$newdependency_libs $deplib"
++ continue
+ case $deplib in
+ *.la)
+ func_basename "$deplib"
diff --git a/tools/libtool/patches/000-relocatable.patch b/tools/libtool/patches/000-relocatable.patch
new file mode 100644
index 0000000..9c3bcb6
--- /dev/null
+++ b/tools/libtool/patches/000-relocatable.patch
@@ -0,0 +1,104 @@
+From ca10caa502f971f90d8c041aa2476de54ef0ce2b Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 16:41:11 -0300
+Subject: openwrt: make relocatable, search resources relative to STAGING_DIR
+
+This was originally commited to openwrt by Jo-Philipp Wich
+<jow@openwrt.org>.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/libtoolize.in
++++ b/libtoolize.in
+@@ -38,14 +38,23 @@
+ # with bootstrap, so set those here where they can still be over-
+ # ridden by the user, but otherwise take precedence.
+
+-: ${AUTOCONF="autoconf"}
+-: ${AUTOMAKE="automake"}
+-: ${EGREP="@EGREP@"}
+-: ${FGREP="@FGREP@"}
+-: ${GREP="@GREP@"}
+ : ${LN_S="@LN_S@"}
+-: ${SED="@SED@"}
+
++if test -n "$STAGING_DIR_HOST"; then
++ : ${AUTOCONF="$STAGING_DIR_HOST/bin/autoconf"}
++ : ${AUTOMAKE="$STAGING_DIR_HOST/bin/automake"}
++ : ${EGREP="$STAGING_DIR_HOST/bin/grep -E"}
++ : ${FGREP="$STAGING_DIR_HOST/bin/grep -F"}
++ : ${GREP="$STAGING_DIR_HOST/bin/grep"}
++ : ${SED="$STAGING_DIR_HOST/bin/sed"}
++else
++ : ${AUTOCONF="autoconf"}
++ : ${AUTOMAKE="automake"}
++ : ${EGREP="@EGREP@"}
++ : ${FGREP="@FGREP@"}
++ : ${GREP="@GREP@"}
++ : ${SED="@SED@"}
++fi
+
+ ## -------------------------- ##
+ ## Source external libraries. ##
+@@ -1903,11 +1912,21 @@ func_require_seen_libtool ()
+ pkgmacro_files="@pkgmacro_files@"
+
+ # Locations for important files:
+- prefix="@prefix@"
+- datadir="@datadir@"
+- pkgauxdir="@pkgauxdir@"
+- pkgltdldir="@pkgdatadir@"
+- aclocaldir="@aclocaldir@"
++ if test -n "$STAGING_DIR_HOST"; then
++ prefix="$STAGING_DIR_HOST"
++ datadir="$STAGING_DIR_HOST/share"
++ pkgauxdir="$STAGING_DIR_HOST/share/libtool/build-aux"
++ pkgdatadir="$STAGING_DIR_HOST/share/libtool"
++ pkgltdldir="$STAGING_DIR_HOST/share/libtool"
++ aclocaldir="$STAGING_DIR_HOST/share/aclocal"
++ else
++ prefix="@prefix@"
++ datadir="@datadir@"
++ pkgauxdir="@pkgauxdir@"
++ pkgdatadir="@pkgdatadir@"
++ pkgltdldir="@pkgdatadir@"
++ aclocaldir="@aclocaldir@"
++ fi
+
+ # Allow the user to override the master libtoolize repository:
+ if test -n "$_lt_pkgdatadir"; then
+--- a/m4/libtool.m4
++++ b/m4/libtool.m4
+@@ -933,7 +933,7 @@ m4_defun([_LT_TAG_COMPILER],
+ [AC_REQUIRE([AC_PROG_CC])dnl
+
+ _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+-_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
++_LT_DECL([LTCFLAGS], [CFLAGS], ["-O2 -I\${STAGING_DIR_HOST:-$STAGING_DIR_HOST}/include"], [LTCC compiler flags])dnl
+ _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+ _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+@@ -8183,9 +8183,9 @@ m4_defun([_LT_DECL_EGREP],
+ [AC_REQUIRE([AC_PROG_EGREP])dnl
+ AC_REQUIRE([AC_PROG_FGREP])dnl
+ test -z "$GREP" && GREP=grep
+-_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+-_LT_DECL([], [EGREP], [1], [An ERE matcher])
+-_LT_DECL([], [FGREP], [1], [A literal string matcher])
++_LT_DECL([], [GREP], ["\${STAGING_DIR_HOST:-$STAGING_DIR_HOST}/bin/grep"], [A grep program that handles long lines])
++_LT_DECL([], [EGREP], ["\${STAGING_DIR_HOST:-$STAGING_DIR_HOST}/bin/grep -E"], [An ERE matcher])
++_LT_DECL([], [FGREP], ["\${STAGING_DIR_HOST:-$STAGING_DIR_HOST}/bin/grep -F"], [A literal string matcher])
+ dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+ AC_SUBST([GREP])
+ ])
+@@ -8226,9 +8226,8 @@ _LT_DECL([], [FILECMD], [1], [A file(cmd
+ # as few characters as possible. Prefer GNU sed if found.
+ m4_defun([_LT_DECL_SED],
+ [AC_PROG_SED
+-test -z "$SED" && SED=sed
+ Xsed="$SED -e 1s/^X//"
+-_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
++_LT_DECL([], [SED], ["\${STAGING_DIR_HOST:-$STAGING_DIR_HOST}/bin/sed"], [A sed program that does not truncate output])
+ _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+ [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+ ])# _LT_DECL_SED
diff --git a/tools/libtool/patches/100-libdir-fixes.patch b/tools/libtool/patches/100-libdir-fixes.patch
new file mode 100644
index 0000000..2a56390
--- /dev/null
+++ b/tools/libtool/patches/100-libdir-fixes.patch
@@ -0,0 +1,66 @@
+From 67ffe8e8582a7ba1f1d1307a419098e6dd88bdaf Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 16:41:11 -0300
+Subject: openwrt: cross-compilation path adjustments
+
+Comments from the patch:
+
+Adding 'libdir' from the .la file to our library search paths
+breaks crosscompilation horribly. We cheat here and don't add
+it, instead adding the path where we found the .la. -CL
+
+OE sets installed=no in staging. We need to look in $objdir and $absdir,
+preferring $objdir. RP 31/04/2008
+
+This was originally commited to openwrt by Jo-Philipp Wich
+<jow@openwrt.org>.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -6097,8 +6097,14 @@ func_mode_link ()
+ absdir=$abs_ladir
+ libdir=$abs_ladir
+ else
+- dir=$lt_sysroot$libdir
+- absdir=$lt_sysroot$libdir
++ # Adding 'libdir' from the .la file to our library search paths
++ # breaks crosscompilation horribly. We cheat here and don't add
++ # it, instead adding the path where we found the .la. -CL
++ dir="$lt_sysroot$abs_ladir"
++ absdir="$abs_ladir"
++ libdir="$abs_ladir"
++ #dir=$lt_sysroot$libdir
++ #absdir=$lt_sysroot$libdir
+ fi
+ test yes = "$hardcode_automatic" && avoidtemprpath=yes
+ else
+@@ -6496,8 +6502,6 @@ func_mode_link ()
+ add=$libdir/$linklib
+ fi
+ else
+- # We cannot seem to hardcode it, guess we'll fake it.
+- add_dir=-L$libdir
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+@@ -6652,7 +6656,17 @@ func_mode_link ()
+ fi
+ ;;
+ *)
+- path=-L$absdir/$objdir
++ # OE sets installed=no in staging. We need to look in $objdir and $absdir,
++ # preferring $objdir. RP 31/04/2008
++ if test -f "$absdir/$objdir/$depdepl" ; then
++ depdepl="$absdir/$objdir/$depdepl"
++ path="-L$absdir/$objdir"
++ elif test -f "$absdir/$depdepl" ; then
++ depdepl="$absdir/$depdepl"
++ path="-L$absdir"
++ else
++ path="-L$absdir/$objdir"
++ fi
+ ;;
+ esac
+ else
diff --git a/tools/libtool/patches/110-dont-use-target-dir-for-relinking.patch b/tools/libtool/patches/110-dont-use-target-dir-for-relinking.patch
new file mode 100644
index 0000000..2d2189e
--- /dev/null
+++ b/tools/libtool/patches/110-dont-use-target-dir-for-relinking.patch
@@ -0,0 +1,32 @@
+From 375833af93999f8b0a747c8a1dfa3ec8d347743d Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 16:52:37 -0300
+Subject: openwrt: don't use target dir for relinking
+
+This was originally commited to openwrt by Jo-Philipp Wich
+<jow@openwrt.org>.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -6482,13 +6482,13 @@ func_mode_link ()
+ add_dir=
+ add=
+ # Finalize command for both is simple: just hardcode it.
+- if test yes = "$hardcode_direct" &&
+- test no = "$hardcode_direct_absolute"; then
+- add=$libdir/$linklib
+- elif test yes = "$hardcode_minus_L"; then
++ if test "$hardcode_direct" = yes &&
++ test "$hardcode_direct_absolute" = no; then
++ add="$libdir/$linklib"
++ elif test "$hardcode_minus_L" = yes; then
+ add_dir=-L$libdir
+- add=-l$name
+- elif test yes = "$hardcode_shlibpath_var"; then
++ add="-l$name"
++ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) func_append finalize_shlibpath "$libdir:" ;;
diff --git a/tools/libtool/patches/120-strip-unsafe-dirs-for-relinking.patch b/tools/libtool/patches/120-strip-unsafe-dirs-for-relinking.patch
new file mode 100644
index 0000000..132f1c9
--- /dev/null
+++ b/tools/libtool/patches/120-strip-unsafe-dirs-for-relinking.patch
@@ -0,0 +1,25 @@
+From 7f2b8a1ab4fa1475eeeddfb84eb5b92594bfce43 Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 16:54:12 -0300
+Subject: openwrt: strip unsave directories from relink command
+
+strip unsave directories from relink command, nuke every -L that looks
+like /usr/lib or /lib
+
+This was originally commited to openwrt by Jo-Philipp Wich
+<jow@openwrt.org>.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -2400,6 +2400,9 @@ func_mode_install ()
+ relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+ fi
+
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/lib[^[:space:]]*%%"`
++ relink_command=`$ECHO "$relink_command" | $SED "s%-L[[:space:]]*/usr/lib[^[:space:]]*%%"`
++
+ func_warning "relinking '$file'"
+ func_show_eval "$relink_command" \
+ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"'
diff --git a/tools/libtool/patches/130-trailingslash.patch b/tools/libtool/patches/130-trailingslash.patch
new file mode 100644
index 0000000..78fdf0a
--- /dev/null
+++ b/tools/libtool/patches/130-trailingslash.patch
@@ -0,0 +1,37 @@
+From 1b45c3c0d6682be7f4876b620780ee246a5acbaa Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 16:56:16 -0300
+Subject: openwrt: remove trailing slash in install destdir
+
+A command like /bin/sh ../../i586-poky-linux-libtool --mode=install /usr/bin/install -c gck-roots-store-standalone.la '/media/data1/builds/poky1/tmp/work/core2-poky-linux/gnome-keyring-2.26.1-r1/image/usr/lib/gnome-keyring/standalone/' fails (e.g. gnome-keyring or pulseaudio)
+
+This is because libdir has a trailing slash which breaks the comparision.
+
+RP 2/1/10
+
+Merged a patch received from Gary Thomas <gary@mlbassoc.com>
+
+Date: 2010/07/12
+Nitin A Kamble <nitin.a.kamble@intel.com>
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -2381,8 +2381,15 @@ func_mode_install ()
+ func_append dir "$objdir"
+
+ if test -n "$relink_command"; then
++ # Strip any trailing slash from the destination.
++ func_stripname '' '/' "$libdir"
++ destlibdir=$func_stripname_result
++
++ func_stripname '' '/' "$destdir"
++ s_destdir=$func_stripname_result
++
+ # Determine the prefix the user has applied to our future dir.
+- inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
++ inst_prefix_dir=`$ECHO "X$s_destdir" | $Xsed -e "s%$destlibdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
diff --git a/tools/libtool/patches/140-don-t-quote-SHELL-in-Makefile.am.patch b/tools/libtool/patches/140-don-t-quote-SHELL-in-Makefile.am.patch
new file mode 100644
index 0000000..3422961
--- /dev/null
+++ b/tools/libtool/patches/140-don-t-quote-SHELL-in-Makefile.am.patch
@@ -0,0 +1,72 @@
+From 879578d3f4dc9bc42aa433b1fb6b584564f83617 Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Wed, 21 Jul 2021 13:38:24 -0300
+Subject: openwrt: don't quote $(SHELL) in Makefile.am
+
+This allows to use SHELL="env bash" to get a controlled enviroment.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -46,7 +46,7 @@ EXTRA_LTLIBRARIES =
+ # Using 'cd' in backquotes may print the directory name, use this instead:
+ lt__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+
+-git_version_gen = '$(SHELL)' '$(aux_dir)/git-version-gen' '--fallback' '$(VERSION)' '.tarball-version'
++git_version_gen = $(SHELL) '$(aux_dir)/git-version-gen' '--fallback' '$(VERSION)' '.tarball-version'
+ rebuild = rebuild=:; revision=`$(lt__cd) $(srcdir) && $(git_version_gen) | $(SED) 's|-.*$$||'`
+
+
+@@ -306,7 +306,7 @@ libtool: $(ltmain_sh) $(config_status) $
+ if test 0 = '$(AM_DEFAULT_VERBOSITY)' && test 1 != '$(V)'; \
+ then echo " GEN " $@; \
+ else echo '$(SHELL) $(top_builddir)/config.status "$@"'; fi; \
+- cd '$(top_builddir)' && '$(SHELL)' ./config.status '$@'; \
++ cd '$(top_builddir)' && $(SHELL) ./config.status '$@'; \
+ fi
+
+
+@@ -789,13 +789,13 @@ testsuite_deps_uninstalled = $(testsuite
+ # Hook the test suite into the check rule
+ check-local: $(testsuite_deps_uninstalled)
+ $(AM_V_at)$(CD_TESTDIR); \
+- CONFIG_SHELL='$(SHELL)' '$(SHELL)' "$$abs_srcdir/$(TESTSUITE)" \
++ CONFIG_SHELL=$(SHELL) $(SHELL) "$$abs_srcdir/$(TESTSUITE)" \
+ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) $(TESTSUITEFLAGS)
+
+ # Run the test suite on the *installed* tree.
+ installcheck-local: $(testsuite_deps)
+ $(AM_V_at)$(CD_TESTDIR); \
+- CONFIG_SHELL='$(SHELL)' '$(SHELL)' "$$abs_srcdir/$(TESTSUITE)" \
++ CONFIG_SHELL=$(SHELL) $(SHELL) "$$abs_srcdir/$(TESTSUITE)" \
+ $(TESTS_ENVIRONMENT) $(INSTALLCHECK_ENVIRONMENT) $(TESTSUITEFLAGS) \
+ AUTOTEST_PATH='$(exec_prefix)/bin'
+
+@@ -807,7 +807,7 @@ check-noninteractive-old:
+ .PHONY: check-noninteractive-new
+ check-noninteractive-new: $(testsuite_deps_uninstalled)
+ $(AM_V_at)$(CD_TESTDIR); \
+- CONFIG_SHELL='$(SHELL)' '$(SHELL)' "$$abs_srcdir/$(TESTSUITE)" \
++ CONFIG_SHELL=$(SHELL) $(SHELL) "$$abs_srcdir/$(TESTSUITE)" \
+ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) \
+ -k '!interactive' INNER_TESTSUITEFLAGS=',!interactive' \
+ $(TESTSUITEFLAGS)
+@@ -816,7 +816,7 @@ check-noninteractive-new: $(testsuite_de
+ .PHONY: check-interactive
+ check-interactive: $(testsuite_deps_uninstalled)
+ $(AM_V_at)$(CD_TESTDIR); \
+- CONFIG_SHELL='$(SHELL)' '$(SHELL)' "$$abs_srcdir/$(TESTSUITE)" \
++ CONFIG_SHELL=$(SHELL) $(SHELL) "$$abs_srcdir/$(TESTSUITE)" \
+ $(TESTS_ENVIRONMENT) $(BUILDCHECK_ENVIRONMENT) \
+ -k interactive -k recursive INNER_TESTSUITEFLAGS=',interactive' \
+ $(TESTSUITEFLAGS)
+@@ -828,7 +828,7 @@ check-noninteractive: check-noninteracti
+ clean-local:
+ -$(CD_TESTDIR); \
+ test -f "$$abs_srcdir/$(TESTSUITE)" && \
+- '$(SHELL)' "$$abs_srcdir/$(TESTSUITE)" --clean
++ $(SHELL) "$$abs_srcdir/$(TESTSUITE)" --clean
+
+ ## An empty target to depend on when a rule needs to always run
+ ## whenever it is visited.
diff --git a/tools/libtool/patches/200-openwrt-branding.patch b/tools/libtool/patches/200-openwrt-branding.patch
new file mode 100644
index 0000000..5876f8b
--- /dev/null
+++ b/tools/libtool/patches/200-openwrt-branding.patch
@@ -0,0 +1,34 @@
+From 90707200efadc8e230635c7c204c9c272cbc8631 Mon Sep 17 00:00:00 2001
+From: Eneas U de Queiroz <cotequeiroz@gmail.com>
+Date: Tue, 20 Jul 2021 17:01:03 -0300
+Subject: openwrt: add openwrt branding
+
+This prepends program name with "OpenWrt-".
+
+This was originally commited to openwrt by Jo-Philipp Wich
+<jow@openwrt.org>.
+
+Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
+
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -82,7 +82,7 @@ func_echo ()
+ IFS=$nl
+ for _G_line in $_G_message; do
+ IFS=$func_echo_IFS
+- $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line"
++ $ECHO "OpenWrt-$progname${opt_mode+: $opt_mode}: $_G_line"
+ done
+ IFS=$func_echo_IFS
+ }
+--- a/build-aux/funclib.sh
++++ b/build-aux/funclib.sh
+@@ -699,7 +699,7 @@ func_echo ()
+ IFS=$nl
+ for _G_line in $_G_message; do
+ IFS=$func_echo_IFS
+- $ECHO "$progname: $_G_line"
++ $ECHO "OpenWrt-$progname: $_G_line"
+ done
+ IFS=$func_echo_IFS
+ }
diff --git a/tools/llvm-bpf/Makefile b/tools/llvm-bpf/Makefile
new file mode 100644
index 0000000..a36ca06
--- /dev/null
+++ b/tools/llvm-bpf/Makefile
@@ -0,0 +1,70 @@
+#
+# Copyright (C) 2006-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=llvm-project
+PKG_VERSION:=18.1.7
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).src.tar.xz
+PKG_SOURCE_URL:=https://github.com/llvm/llvm-project/releases/download/llvmorg-$(PKG_VERSION)
+PKG_HASH:=74446ab6943f686391954cbda0d77ae92e8a60c432eff437b8666e121d748ec4
+PKG_CPE_ID:=cpe:/a:llvm:llvm
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/$(PKG_NAME)-$(PKG_VERSION).src
+
+CMAKE_BINARY_SUBDIR := build
+CMAKE_SOURCE_SUBDIR := llvm
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+ifneq ($(HOST_OS),Linux)
+ HOST_CFLAGS := $(filter-out -I$(STAGING_DIR_HOST)/include,$(HOST_CFLAGS))
+ HOST_CXXFLAGS := $(filter-out -I$(STAGING_DIR_HOST)/include,$(HOST_CXXFLAGS))
+endif
+
+LLVM_BPF_PREFIX = llvm-bpf-$(PKG_VERSION).$(HOST_OS)-$(HOST_ARCH)
+
+CMAKE_HOST_INSTALL_PREFIX = $(STAGING_DIR_HOST)/$(LLVM_BPF_PREFIX)
+
+CMAKE_HOST_OPTIONS += \
+ -DLLVM_TARGETS_TO_BUILD=BPF \
+ -DLLVM_DEFAULT_TARGET_TRIPLE=bpf \
+ -DLLVM_ENABLE_PROJECTS="clang;lld" \
+ -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON \
+ -DLLVM_LINK_LLVM_DYLIB=ON \
+ -DLLVM_TOOLCHAIN_TOOLS="llvm-objcopy;llvm-objdump;llvm-readelf;llvm-strip;llvm-ar;llvm-as;llvm-dis;llvm-link;llvm-nm;llvm-ranlib;llc;opt" \
+ -DLLVM_INCLUDE_BENCHMARKS=OFF \
+ -DLLVM_INCLUDE_DOCS=OFF \
+ -DLLVM_INCLUDE_EXAMPLES=OFF \
+ -DLLVM_INCLUDE_TESTS=OFF \
+ -DLLVM_ENABLE_BINDINGS=OFF \
+ -DLLVM_ENABLE_IDE=OFF \
+ -DLLVM_ENABLE_LIBEDIT=OFF \
+ -DLLVM_ENABLE_LIBPFM=OFF \
+ -DLLVM_ENABLE_LIBXML2=OFF \
+ -DLLVM_ENABLE_OCAMLDOC=OFF \
+ -DLLVM_ENABLE_TERMINFO=OFF \
+ -DLLVM_ENABLE_Z3_SOLVER=OFF \
+ -DLLVM_ENABLE_ZLIB=OFF \
+ -DLLVM_ENABLE_ZSTD=OFF \
+ -DLLVM_PARALLEL_LINK_JOBS=1 \
+ -DCMAKE_SKIP_RPATH=OFF
+
+define Host/Install
+ rm -rf $(STAGING_DIR_HOST)/llvm-bpf*
+ $(Host/Install/Default)
+ ln -s $(LLVM_BPF_PREFIX) $(STAGING_DIR_HOST)/llvm-bpf
+ STRIP_KMOD= PATCHELF= STRIP=strip $(SCRIPT_DIR)/rstrip.sh $(STAGING_DIR_HOST)/llvm-bpf
+ echo "$(PKG_VERSION)" > $(CMAKE_HOST_INSTALL_PREFIX)/.llvm-version
+endef
+
+define Host/Uninstall
+ rm -rf $(STAGING_DIR_HOST)/llvm-bpf*
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/lz4/Makefile b/tools/lz4/Makefile
new file mode 100644
index 0000000..cf1738a
--- /dev/null
+++ b/tools/lz4/Makefile
@@ -0,0 +1,38 @@
+#
+# Copyright (C) 2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=lz4
+PKG_VERSION:=1.9.4
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://codeload.github.com/lz4/lz4/tar.gz/v$(PKG_VERSION)?
+PKG_HASH:=0b0e3aa07c8c063ddf40b082bdf7e37a1562bda40a0ff5272957f3e987e0e54b
+
+PKG_LICENSE:=BSD-2-Clause
+PKG_LICENSE_FILES:=LICENSE lib/LICENSE
+PKG_CPE_ID:=cpe:/a:lz4_project:lz4
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/meson.mk
+
+MESON_HOST_BUILD_DIR:=$(HOST_BUILD_DIR)/contrib/meson/openwrt-build
+
+# Always optimize for speed
+HOST_CFLAGS := $(filter-out -O%,$(HOST_CFLAGS)) -O3
+
+MESON_HOST_ARGS += \
+ -Ddefault_library=static \
+ -Ddebug-level=0 \
+ -Dunstable=false \
+ -Dprograms=true \
+ -Dtests=false \
+ -Dcontrib=false \
+ -Dexamples=false
+
+$(eval $(call HostBuild))
diff --git a/tools/lzma-old/Makefile b/tools/lzma-old/Makefile
new file mode 100644
index 0000000..21e7428
--- /dev/null
+++ b/tools/lzma-old/Makefile
@@ -0,0 +1,38 @@
+#
+# Copyright (C) 2006 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=lzma-old
+PKG_VERSION:=4.32
+
+PKG_SOURCE:=lzma-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@OPENWRT
+PKG_HASH:=49053e4bb5e0646a841d250d9cb81f7714f5fff04a133216c4748163567acc3d
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/lzma-$(PKG_VERSION)
+
+include $(INCLUDE_DIR)/host-build.mk
+
+LIB_DIR=$(HOST_BUILD_DIR)/C/7zip/Compress/LZMA_Lib
+ALONE_DIR=$(HOST_BUILD_DIR)/C/7zip/Compress/LZMA_Alone
+
+define Host/Compile
+ +$(HOST_MAKE_VARS) \
+ $(MAKE) -C $(LIB_DIR)
+ +$(HOST_MAKE_VARS) \
+ $(MAKE) -f makefile.gcc -C $(ALONE_DIR)
+endef
+
+define Host/Install
+ $(INSTALL_DATA) $(LIB_DIR)/liblzma.a $(STAGING_DIR_HOST)/lib/liblzma-old.a
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/lib/liblzma-old.a
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/lzma-old/patches/100-lzma_zlib.patch b/tools/lzma-old/patches/100-lzma_zlib.patch
new file mode 100644
index 0000000..32d1263
--- /dev/null
+++ b/tools/lzma-old/patches/100-lzma_zlib.patch
@@ -0,0 +1,404 @@
+--- a/C/7zip/Compress/LZMA/LZMADecoder.cpp
++++ b/C/7zip/Compress/LZMA/LZMADecoder.cpp
+@@ -274,12 +274,17 @@ STDMETHODIMP CDecoder::SetDecoderPropert
+ Byte remainder = (Byte)(properties[0] / 9);
+ int lp = remainder % 5;
+ int pb = remainder / 5;
+- if (pb > NLength::kNumPosStatesBitsMax)
+- return E_INVALIDARG;
+- _posStateMask = (1 << pb) - 1;
+ UInt32 dictionarySize = 0;
+ for (int i = 0; i < 4; i++)
+ dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8);
++ return SetDecoderPropertiesRaw(lc, lp, pb, dictionarySize);
++}
++
++STDMETHODIMP CDecoder::SetDecoderPropertiesRaw(int lc, int lp, int pb, UInt32 dictionarySize)
++{
++ if (pb > NLength::kNumPosStatesBitsMax)
++ return E_INVALIDARG;
++ _posStateMask = (1 << pb) - 1;
+ if (!_outWindowStream.Create(dictionarySize))
+ return E_OUTOFMEMORY;
+ if (!_literalDecoder.Create(lp, lc))
+--- a/C/7zip/Compress/LZMA/LZMADecoder.h
++++ b/C/7zip/Compress/LZMA/LZMADecoder.h
+@@ -228,6 +228,7 @@ public:
+ ICompressProgressInfo *progress);
+
+ STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
++ STDMETHOD(SetDecoderPropertiesRaw)(int lc, int lp, int pb, UInt32 dictionarySize);
+
+ STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
+
+--- /dev/null
++++ b/C/7zip/Compress/LZMA_Lib/makefile
+@@ -0,0 +1,92 @@
++PROG = liblzma.a
++CXX = g++ -O3 -Wall
++AR = ar
++RM = rm -f
++CFLAGS = -c -I ../../../
++
++OBJS = \
++ ZLib.o \
++ LZMADecoder.o \
++ LZMAEncoder.o \
++ LZInWindow.o \
++ LZOutWindow.o \
++ RangeCoderBit.o \
++ InBuffer.o \
++ OutBuffer.o \
++ FileStreams.o \
++ Alloc.o \
++ C_FileIO.o \
++ CommandLineParser.o \
++ CRC.o \
++ StreamUtils.o \
++ String.o \
++ StringConvert.o \
++ StringToInt.o \
++ Vector.o \
++
++
++all: $(PROG)
++
++$(PROG): $(OBJS)
++ $(AR) r $(PROG) $(OBJS)
++
++ZLib.o: ZLib.cpp
++ $(CXX) $(CFLAGS) ZLib.cpp
++
++LZMADecoder.o: ../LZMA/LZMADecoder.cpp
++ $(CXX) $(CFLAGS) ../LZMA/LZMADecoder.cpp
++
++LZMAEncoder.o: ../LZMA/LZMAEncoder.cpp
++ $(CXX) $(CFLAGS) ../LZMA/LZMAEncoder.cpp
++
++LZInWindow.o: ../LZ/LZInWindow.cpp
++ $(CXX) $(CFLAGS) ../LZ/LZInWindow.cpp
++
++LZOutWindow.o: ../LZ/LZOutWindow.cpp
++ $(CXX) $(CFLAGS) ../LZ/LZOutWindow.cpp
++
++RangeCoderBit.o: ../RangeCoder/RangeCoderBit.cpp
++ $(CXX) $(CFLAGS) ../RangeCoder/RangeCoderBit.cpp
++
++InBuffer.o: ../../Common/InBuffer.cpp
++ $(CXX) $(CFLAGS) ../../Common/InBuffer.cpp
++
++OutBuffer.o: ../../Common/OutBuffer.cpp
++ $(CXX) $(CFLAGS) ../../Common/OutBuffer.cpp
++
++StreamUtils.o: ../../Common/StreamUtils.cpp
++ $(CXX) $(CFLAGS) ../../Common/StreamUtils.cpp
++
++FileStreams.o: ../../Common/FileStreams.cpp
++ $(CXX) $(CFLAGS) ../../Common/FileStreams.cpp
++
++Alloc.o: ../../../Common/Alloc.cpp
++ $(CXX) $(CFLAGS) ../../../Common/Alloc.cpp
++
++C_FileIO.o: ../../../Common/C_FileIO.cpp
++ $(CXX) $(CFLAGS) ../../../Common/C_FileIO.cpp
++
++CommandLineParser.o: ../../../Common/CommandLineParser.cpp
++ $(CXX) $(CFLAGS) ../../../Common/CommandLineParser.cpp
++
++CRC.o: ../../../Common/CRC.cpp
++ $(CXX) $(CFLAGS) ../../../Common/CRC.cpp
++
++MyWindows.o: ../../../Common/MyWindows.cpp
++ $(CXX) $(CFLAGS) ../../../Common/MyWindows.cpp
++
++String.o: ../../../Common/String.cpp
++ $(CXX) $(CFLAGS) ../../../Common/String.cpp
++
++StringConvert.o: ../../../Common/StringConvert.cpp
++ $(CXX) $(CFLAGS) ../../../Common/StringConvert.cpp
++
++StringToInt.o: ../../../Common/StringToInt.cpp
++ $(CXX) $(CFLAGS) ../../../Common/StringToInt.cpp
++
++Vector.o: ../../../Common/Vector.cpp
++ $(CXX) $(CFLAGS) ../../../Common/Vector.cpp
++
++clean:
++ -$(RM) $(PROG) $(OBJS)
++
+--- /dev/null
++++ b/C/7zip/Compress/LZMA_Lib/ZLib.cpp
+@@ -0,0 +1,273 @@
++/*
++ * lzma zlib simplified wrapper
++ *
++ * Copyright (c) 2005-2006 Oleg I. Vdovikin <oleg@cs.msu.su>
++ *
++ * This library is free software; you can redistribute
++ * it and/or modify it under the terms of the GNU Lesser
++ * General Public License as published by the Free Software
++ * Foundation; either version 2.1 of the License, or
++ * (at your option) any later version.
++ *
++ * This library 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 Lesser General Public License
++ * for more details.
++ *
++ * You should have received a copy of the GNU Lesser General
++ * Public License along with this library; if not, write to
++ * the Free Software Foundation, Inc., 59 Temple Place,
++ * Suite 330, Boston, MA 02111-1307 USA
++ */
++
++/*
++ * default values for encoder/decoder used by wrapper
++ */
++
++#include <zlib.h>
++
++#define ZLIB_LC 3
++#define ZLIB_LP 0
++#define ZLIB_PB 2
++
++#ifdef WIN32
++#include <initguid.h>
++#else
++#define INITGUID
++#endif
++
++#include "../../../Common/MyWindows.h"
++#include "../LZMA/LZMADecoder.h"
++#include "../LZMA/LZMAEncoder.h"
++
++#define STG_E_SEEKERROR ((HRESULT)0x80030019L)
++#define STG_E_MEDIUMFULL ((HRESULT)0x80030070L)
++
++class CInMemoryStream:
++ public IInStream,
++ public IStreamGetSize,
++ public CMyUnknownImp
++{
++public:
++ CInMemoryStream(const Bytef *data, UInt64 size) :
++ m_data(data), m_size(size), m_offset(0) {}
++
++ virtual ~CInMemoryStream() {}
++
++ MY_UNKNOWN_IMP2(IInStream, IStreamGetSize)
++
++ STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize)
++ {
++ if (size > m_size - m_offset)
++ size = m_size - m_offset;
++
++ if (size) {
++ memcpy(data, m_data + m_offset, size);
++ }
++
++ m_offset += size;
++
++ if (processedSize)
++ *processedSize = size;
++
++ return S_OK;
++ }
++
++ STDMETHOD(ReadPart)(void *data, UInt32 size, UInt32 *processedSize)
++ {
++ return Read(data, size, processedSize);
++ }
++
++ STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
++ {
++ UInt64 _offset;
++
++ if (seekOrigin == STREAM_SEEK_SET) _offset = offset;
++ else if (seekOrigin == STREAM_SEEK_CUR) _offset = m_offset + offset;
++ else if (seekOrigin == STREAM_SEEK_END) _offset = m_size;
++ else return STG_E_INVALIDFUNCTION;
++
++ if (_offset < 0 || _offset > m_size)
++ return STG_E_SEEKERROR;
++
++ m_offset = _offset;
++
++ if (newPosition)
++ *newPosition = m_offset;
++
++ return S_OK;
++ }
++
++ STDMETHOD(GetSize)(UInt64 *size)
++ {
++ *size = m_size;
++ return S_OK;
++ }
++protected:
++ const Bytef *m_data;
++ UInt64 m_size;
++ UInt64 m_offset;
++};
++
++class COutMemoryStream:
++ public IOutStream,
++ public CMyUnknownImp
++{
++public:
++ COutMemoryStream(Bytef *data, UInt64 maxsize) :
++ m_data(data), m_size(0), m_maxsize(maxsize), m_offset(0) {}
++ virtual ~COutMemoryStream() {}
++
++ MY_UNKNOWN_IMP1(IOutStream)
++
++ STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize)
++ {
++ if (size > m_maxsize - m_offset)
++ size = m_maxsize - m_offset;
++
++ if (size) {
++ memcpy(m_data + m_offset, data, size);
++ }
++
++ m_offset += size;
++
++ if (m_offset > m_size)
++ m_size = m_offset;
++
++ if (processedSize)
++ *processedSize = size;
++
++ return S_OK;
++ }
++
++ STDMETHOD(WritePart)(const void *data, UInt32 size, UInt32 *processedSize)
++ {
++ return Write(data, size, processedSize);
++ }
++
++ STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
++ {
++ UInt64 _offset;
++
++ if (seekOrigin == STREAM_SEEK_SET) _offset = offset;
++ else if (seekOrigin == STREAM_SEEK_CUR) _offset = m_offset + offset;
++ else if (seekOrigin == STREAM_SEEK_END) _offset = m_size;
++ else return STG_E_INVALIDFUNCTION;
++
++ if (_offset < 0 || _offset > m_maxsize)
++ return STG_E_SEEKERROR;
++
++ m_offset = _offset;
++
++ if (newPosition)
++ *newPosition = m_offset;
++
++ return S_OK;
++ }
++
++ STDMETHOD(SetSize)(Int64 newSize)
++ {
++ if ((UInt64)newSize > m_maxsize)
++ return STG_E_MEDIUMFULL;
++
++ return S_OK;
++ }
++protected:
++ Bytef *m_data;
++ UInt64 m_size;
++ UInt64 m_maxsize;
++ UInt64 m_offset;
++};
++
++ZEXTERN int ZEXPORT compress2 (Bytef *dest, uLongf *destLen,
++ const Bytef *source, uLong sourceLen,
++ int level)
++{
++ CInMemoryStream *inStreamSpec = new CInMemoryStream(source, sourceLen);
++ CMyComPtr<ISequentialInStream> inStream = inStreamSpec;
++
++ COutMemoryStream *outStreamSpec = new COutMemoryStream(dest, *destLen);
++ CMyComPtr<ISequentialOutStream> outStream = outStreamSpec;
++
++ NCompress::NLZMA::CEncoder *encoderSpec =
++ new NCompress::NLZMA::CEncoder;
++ CMyComPtr<ICompressCoder> encoder = encoderSpec;
++
++ PROPID propIDs[] =
++ {
++ NCoderPropID::kDictionarySize,
++ NCoderPropID::kPosStateBits,
++ NCoderPropID::kLitContextBits,
++ NCoderPropID::kLitPosBits,
++ NCoderPropID::kAlgorithm,
++ NCoderPropID::kNumFastBytes,
++ NCoderPropID::kMatchFinder,
++ NCoderPropID::kEndMarker
++ };
++ const int kNumProps = sizeof(propIDs) / sizeof(propIDs[0]);
++
++ PROPVARIANT properties[kNumProps];
++ for (int p = 0; p < 6; p++)
++ properties[p].vt = VT_UI4;
++ properties[0].ulVal = UInt32(1 << (level + 14));
++ properties[1].ulVal = UInt32(ZLIB_PB);
++ properties[2].ulVal = UInt32(ZLIB_LC); // for normal files
++ properties[3].ulVal = UInt32(ZLIB_LP); // for normal files
++ properties[4].ulVal = UInt32(2);
++ properties[5].ulVal = UInt32(128);
++
++ properties[6].vt = VT_BSTR;
++ properties[6].bstrVal = (BSTR)(const wchar_t *)L"BT4";
++
++ properties[7].vt = VT_BOOL;
++ properties[7].boolVal = VARIANT_TRUE;
++
++ if (encoderSpec->SetCoderProperties(propIDs, properties, kNumProps) != S_OK)
++ return Z_MEM_ERROR; // should not happen
++
++ HRESULT result = encoder->Code(inStream, outStream, 0, 0, 0);
++ if (result == E_OUTOFMEMORY)
++ {
++ return Z_MEM_ERROR;
++ }
++ else if (result != S_OK)
++ {
++ return Z_BUF_ERROR; // should not happen
++ }
++
++ UInt64 fileSize;
++ outStreamSpec->Seek(0, STREAM_SEEK_END, &fileSize);
++ *destLen = fileSize;
++
++ return Z_OK;
++}
++
++ZEXTERN int ZEXPORT uncompress (Bytef *dest, uLongf *destLen,
++ const Bytef *source, uLong sourceLen)
++{
++ CInMemoryStream *inStreamSpec = new CInMemoryStream(source, sourceLen);
++ CMyComPtr<ISequentialInStream> inStream = inStreamSpec;
++
++ COutMemoryStream *outStreamSpec = new COutMemoryStream(dest, *destLen);
++ CMyComPtr<ISequentialOutStream> outStream = outStreamSpec;
++
++ NCompress::NLZMA::CDecoder *decoderSpec =
++ new NCompress::NLZMA::CDecoder;
++ CMyComPtr<ICompressCoder> decoder = decoderSpec;
++
++ if (decoderSpec->SetDecoderPropertiesRaw(ZLIB_LC,
++ ZLIB_LP, ZLIB_PB, (1 << 23)) != S_OK) return Z_DATA_ERROR;
++
++ UInt64 fileSize = *destLen;
++
++ if (decoder->Code(inStream, outStream, 0, &fileSize, 0) != S_OK)
++ {
++ return Z_DATA_ERROR;
++ }
++
++ outStreamSpec->Seek(0, STREAM_SEEK_END, &fileSize);
++ *destLen = fileSize;
++
++ return Z_OK;
++}
diff --git a/tools/lzma-old/patches/110-ranlib.patch b/tools/lzma-old/patches/110-ranlib.patch
new file mode 100644
index 0000000..813b413
--- /dev/null
+++ b/tools/lzma-old/patches/110-ranlib.patch
@@ -0,0 +1,10 @@
+--- a/C/7zip/Compress/LZMA_Lib/makefile
++++ b/C/7zip/Compress/LZMA_Lib/makefile
+@@ -29,6 +29,7 @@ all: $(PROG)
+
+ $(PROG): $(OBJS)
+ $(AR) r $(PROG) $(OBJS)
++ ranlib $(PROG)
+
+ ZLib.o: ZLib.cpp
+ $(CXX) $(CFLAGS) ZLib.cpp
diff --git a/tools/lzma-old/patches/120-add-cflags.patch b/tools/lzma-old/patches/120-add-cflags.patch
new file mode 100644
index 0000000..9022e7c
--- /dev/null
+++ b/tools/lzma-old/patches/120-add-cflags.patch
@@ -0,0 +1,11 @@
+--- a/C/7zip/Compress/LZMA_Lib/makefile
++++ b/C/7zip/Compress/LZMA_Lib/makefile
+@@ -2,7 +2,7 @@ PROG = liblzma.a
+ CXX = g++ -O3 -Wall
+ AR = ar
+ RM = rm -f
+-CFLAGS = -c -I ../../../
++CFLAGS += -c -I ../../../
+
+ OBJS = \
+ ZLib.o \
diff --git a/tools/lzma/Makefile b/tools/lzma/Makefile
new file mode 100644
index 0000000..29f7e0f
--- /dev/null
+++ b/tools/lzma/Makefile
@@ -0,0 +1,37 @@
+#
+# Copyright (C) 2006 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=lzma
+PKG_VERSION:=4.65
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@OPENWRT
+PKG_HASH:=dcbdb5f4843eff638e4a5e8be0e2486a3c5483df73c70823618db8e66f609ec2
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/$(PKG_NAME)-$(PKG_VERSION)
+
+include $(INCLUDE_DIR)/host-build.mk
+
+UTIL_DIR=$(HOST_BUILD_DIR)/C/LzmaUtil
+ALONE_DIR=$(HOST_BUILD_DIR)/CPP/7zip/Compress/LZMA_Alone
+
+define Host/Compile
+ $(MAKE) -C $(UTIL_DIR) -f makefile.gcc
+ $(MAKE) -C $(ALONE_DIR) -f makefile.gcc
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/CPP/7zip/Compress/LZMA_Alone/lzma_alone $(STAGING_DIR_HOST)/bin/lzma
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/lzma
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/lzma/patches/001-large_files.patch b/tools/lzma/patches/001-large_files.patch
new file mode 100644
index 0000000..65603f4
--- /dev/null
+++ b/tools/lzma/patches/001-large_files.patch
@@ -0,0 +1,11 @@
+--- a/CPP/7zip/Compress/LZMA_Alone/makefile.gcc
++++ b/CPP/7zip/Compress/LZMA_Alone/makefile.gcc
+@@ -3,7 +3,7 @@ CXX = g++ -O2 -Wall
+ CXX_C = gcc -O2 -Wall
+ LIB = -lm
+ RM = rm -f
+-CFLAGS = -c
++CFLAGS = -c -D_FILE_OFFSET_BITS=64
+
+ ifdef SystemDrive
+ IS_MINGW = 1
diff --git a/tools/lzma/patches/002-lzmp.patch b/tools/lzma/patches/002-lzmp.patch
new file mode 100644
index 0000000..f1d45f4
--- /dev/null
+++ b/tools/lzma/patches/002-lzmp.patch
@@ -0,0 +1,1049 @@
+--- /dev/null
++++ b/CPP/7zip/Compress/LZMA_Alone/lzmp.cpp
+@@ -0,0 +1,895 @@
++/*
++ * LZMA command line tool similar to gzip to encode and decode LZMA files.
++ *
++ * Copyright (C) 2005 Ville Koskinen
++ *
++ * 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 2
++ * 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, write to the Free Software
++ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
++ * USA.
++ */
++
++#include "../../../Common/MyInitGuid.h"
++
++#include <iostream>
++using std::cout;
++using std::cerr;
++using std::endl;
++
++#include <cstdio>
++#include <cstdlib>
++#include <cstring>
++
++#include <string>
++using std::string;
++#include <vector>
++using std::vector;
++typedef vector<string> stringVector;
++
++#include <unistd.h>
++#include <getopt.h>
++#include <signal.h>
++
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <utime.h>
++#include <sys/time.h> // futimes()
++
++// For Solaris
++#ifndef HAVE_FUTIMES
++//#define futimes(fd, tv) futimesat(fd, NULL, tv)
++#endif
++
++#if defined(_WIN32) || defined(OS2) || defined(MSDOS)
++#include <fcntl.h>
++#include <io.h>
++#define MY_SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY)
++#else
++#define MY_SET_BINARY_MODE(file)
++#endif
++
++#include "../../../7zip/Common/FileStreams.h"
++
++#include "../../../Common/Types.h"
++
++#include "../../../7zip/Compress/LzmaDecoder.h"
++#include "../../../7zip/Compress/LzmaEncoder.h"
++
++#include "Exception.h"
++
++#include "lzma_version.h"
++
++namespace lzma {
++
++const char *PROGRAM_VERSION = PACKAGE_VERSION;
++const char *PROGRAM_COPYRIGHT = "Copyright (C) 2006 Ville Koskinen";
++
++/* LZMA_Alone switches:
++ -a{N}: set compression mode - [0, 2], default: 2 (max)
++ -d{N}: set dictionary - [0,28], default: 23 (8MB)
++ -fb{N}: set number of fast bytes - [5, 255], default: 128
++ -lc{N}: set number of literal context bits - [0, 8], default: 3
++ -lp{N}: set number of literal pos bits - [0, 4], default: 0
++ -pb{N}: set number of pos bits - [0, 4], default: 2
++ -mf{MF_ID}: set Match Finder: [bt2, bt3, bt4, bt4b, pat2r, pat2,
++ pat2h, pat3h, pat4h, hc3, hc4], default: bt4
++*/
++
++struct lzma_option {
++ short compression_mode; // -a
++ short dictionary; // -d
++ short fast_bytes; // -fb
++ wchar_t *match_finder; // -mf
++ short literal_context_bits; // -lc
++ short literal_pos_bits; // -lp
++ short pos_bits; // -pb
++};
++
++/* The following is a mapping from gzip/bzip2 style -1 .. -9 compression modes
++ * to the corresponding LZMA compression modes. Thanks, Larhzu, for coining
++ * these. */
++const lzma_option option_mapping[] = {
++ { 0, 0, 0, NULL, 0, 0, 0}, // -0 (needed for indexing)
++ { 0, 16, 64, L"hc4", 3, 0, 2}, // -1
++ { 0, 20, 64, L"hc4", 3, 0, 2}, // -2
++ { 1, 19, 64, L"bt4", 3, 0, 2}, // -3
++ { 2, 20, 64, L"bt4", 3, 0, 2}, // -4
++ { 2, 21, 128, L"bt4", 3, 0, 2}, // -5
++ { 2, 22, 128, L"bt4", 3, 0, 2}, // -6
++ { 2, 23, 128, L"bt4", 3, 0, 2}, // -7
++ { 2, 24, 255, L"bt4", 3, 0, 2}, // -8
++ { 2, 25, 255, L"bt4", 3, 0, 2}, // -9
++};
++
++struct extension_pair {
++ char *from;
++ char *to;
++};
++
++const extension_pair known_extensions[] = {
++ { ".lzma", "" },
++ { ".tlz", ".tar" },
++ { NULL, NULL }
++};
++
++/* Sorry, I just happen to like enumerations. */
++enum PROGRAM_MODE {
++ PM_COMPRESS = 0,
++ PM_DECOMPRESS,
++ PM_TEST,
++ PM_HELP,
++ PM_LICENSE,
++ PM_VERSION
++};
++
++enum {
++ STATUS_OK = 0,
++ STATUS_ERROR = 1,
++ STATUS_WARNING = 2
++};
++
++/* getopt options. */
++/* struct option { name, has_arg, flag, val } */
++const struct option long_options[] = {
++ { "stdout", 0, 0, 'c' },
++ { "decompress", 0, 0, 'd' },
++ { "compress", 0, 0, 'z' },
++ { "keep", 0, 0, 'k' },
++ { "force", 0, 0, 'f' },
++ { "test", 0, 0, 't' },
++ { "suffix", 1, 0, 'S' },
++ { "quiet", 0, 0, 'q' },
++ { "verbose", 0, 0, 'v' },
++ { "help", 0, 0, 'h' },
++ { "license", 0, 0, 'L' },
++ { "version", 0, 0, 'V' },
++ { "fast", 0, 0, '1' },
++ { "best", 0, 0, '9' },
++ { 0, 0, 0, 0 }
++};
++
++/* getopt option string (for the above options). */
++const char option_string[] = "cdzkftS:qvhLV123456789A:D:F:";
++
++/* Defaults. */
++PROGRAM_MODE program_mode = PM_COMPRESS;
++int verbosity = 0;
++bool stdinput = false;
++bool stdoutput = false;
++bool keep = false;
++bool force = false;
++int compression_mode = 7;
++//char *suffix = strdup(".lzma");
++char *suffix = strdup(known_extensions[0].from);
++lzma_option advanced_options = { -1, -1, -1, NULL, -1, -1, -1 };
++
++void print_help(const char *const argv0)
++{
++ // Help goes to stdout while other messages go to stderr.
++ cout << "\nlzma " << PROGRAM_VERSION
++ << " " << PROGRAM_COPYRIGHT << "\n"
++ "Based on LZMA SDK " << LZMA_SDK_VERSION_STRING << " "
++ << LZMA_SDK_COPYRIGHT_STRING
++ << "\n\nUsage: " << argv0
++ << " [flags and input files in any order]\n"
++" -c --stdout output to standard output\n"
++" -d --decompress force decompression\n"
++" -z --compress force compression\n"
++" -k --keep keep (don't delete) input files\n"
++" -f --force force overwrite of output file and compress links\n"
++" -t --test test compressed file integrity\n"
++" -S .suf --suffix .suf use suffix .suf on compressed files\n"
++" -q --quiet suppress error messages\n"
++" -v --verbose be verbose\n"
++" -h --help print this message\n"
++" -L --license display the license information\n"
++" -V --version display version numbers of LZMA SDK and lzma\n"
++" -1 .. -2 fast compression\n"
++" -3 .. -9 good to excellent compression. -7 is the default.\n"
++" --fast alias for -1\n"
++" --best alias for -9 (usually *not* what you want)\n\n"
++" Memory usage depends a lot on the chosen compression mode -1 .. -9.\n"
++" See the man page lzma(1) for details.\n\n";
++}
++
++void print_license(void)
++{
++ cout << "\n LZMA command line tool " << PROGRAM_VERSION << " - "
++ << PROGRAM_COPYRIGHT
++ << "\n LZMA SDK " << LZMA_SDK_VERSION_STRING << " - "
++ << LZMA_SDK_COPYRIGHT_STRING
++ << "\n This program is a part of the LZMA utils package.\n"
++ " http://tukaani.org/lzma/\n\n"
++" This program is free software; you can redistribute it and/or\n"
++" modify it under the terms of the GNU General Public License\n"
++" as published by the Free Software Foundation; either version 2\n"
++" of the License, or (at your option) any later version.\n"
++"\n"
++" This program is distributed in the hope that it will be useful,\n"
++" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
++" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
++" GNU General Public License for more details.\n"
++"\n";
++}
++
++void print_version(void)
++{
++ cout << "LZMA command line tool " << PROGRAM_VERSION << "\n"
++ << "LZMA SDK " << LZMA_SDK_VERSION_STRING << "\n";
++}
++
++short str2int (const char *str, const int &min, const int &max)
++{
++ int value = -1;
++ char *endptr = NULL;
++ if (str == NULL || str[0] == '\0')
++ throw ArgumentException("Invalid integer option");
++ value = strtol (str, &endptr, 10);
++ if (*endptr != '\0' || value < min || value > max)
++ throw ArgumentException("Invalid integer option");
++ return value;
++}
++
++void parse_options(int argc, char **argv, stringVector &filenames)
++{
++ /* Snatched from getopt(3). */
++ int c;
++
++ /* Check how we were called */
++ {
++ char *p = strrchr (argv[0], '/'); // Remove path prefix, if any
++ if (p++ == NULL)
++ p = argv[0];
++ if (strstr (p, "un") != NULL) {
++ program_mode = PM_DECOMPRESS;
++ } else if (strstr (p, "cat") != NULL) {
++ program_mode = PM_DECOMPRESS;
++ stdoutput = true;
++ }
++ }
++
++ while (-1 != (c = getopt_long(argc, argv, option_string,
++ long_options, NULL))) {
++ switch (c) {
++ // stdout
++ case 'c':
++ stdoutput = true;
++ break;
++
++ // decompress
++ case 'd':
++ program_mode = PM_DECOMPRESS;
++ break;
++
++ // compress
++ case 'z':
++ program_mode = PM_COMPRESS;
++ break;
++
++ // keep
++ case 'k':
++ keep = true;
++ break;
++
++ // force
++ case 'f':
++ force = true;
++ break;
++
++ // test
++ case 't':
++ program_mode = PM_TEST;
++ break;
++
++ // suffix
++ case 'S':
++ if (optarg) {
++ free(suffix);
++ suffix = strdup(optarg);
++ }
++ break;
++
++ // quiet
++ case 'q':
++ verbosity = 0;
++ break;
++
++ // verbose
++ case 'v':
++ verbosity++;
++ break;
++
++ // help
++ case 'h':
++ program_mode = PM_HELP;
++ break;
++
++ // license
++ case 'L':
++ program_mode = PM_LICENSE;
++ break;
++
++ // version
++ case 'V':
++ program_mode = PM_VERSION;
++ break;
++
++ case '1': case '2': case '3': case '4': case '5':
++ case '6': case '7': case '8': case '9':
++ compression_mode = c - '0';
++ break;
++
++ // Advanced options //
++ // Compression mode
++ case 'A':
++ advanced_options.compression_mode =
++ str2int (optarg, 0, 2);
++ break;
++
++ // Dictionary size
++ case 'D':
++ advanced_options.dictionary =
++ str2int (optarg, 0, 28);
++ break;
++
++ // Fast bytes
++ case 'F':
++ advanced_options.fast_bytes =
++ str2int (optarg, 0, 273);
++ break;
++
++ default:
++ throw ArgumentException("");
++ break;
++ } // switch(c)
++ } // while(1)
++
++ for (int i = optind; i < argc; i++) {
++ if (strcmp("-", argv[i]) == 0)
++ continue;
++ filenames.push_back(argv[i]);
++ }
++} // parse_options
++
++void set_encoder_properties(NCompress::NLzma::CEncoder *encoder,
++ lzma_option &opt)
++{
++ /* Almost verbatim from LzmaAlone.cpp. */
++ PROPID propIDs[] =
++ {
++ NCoderPropID::kDictionarySize,
++ NCoderPropID::kPosStateBits,
++ NCoderPropID::kLitContextBits,
++ NCoderPropID::kLitPosBits,
++ NCoderPropID::kAlgorithm,
++ NCoderPropID::kNumFastBytes,
++ NCoderPropID::kMatchFinder,
++ NCoderPropID::kEndMarker
++ };
++ const int kNumProps = sizeof(propIDs) / sizeof(propIDs[0]);
++#define VALUE(x) (advanced_options.x >= 0 ? advanced_options.x : opt.x)
++ PROPVARIANT properties[kNumProps];
++ for (int p = 0; p < 6; p++)
++ properties[p].vt = VT_UI4;
++ properties[0].ulVal = UInt32(1 << VALUE (dictionary));
++ properties[1].ulVal = UInt32(VALUE (pos_bits));
++ properties[2].ulVal = UInt32(VALUE (literal_context_bits));
++ properties[3].ulVal = UInt32(VALUE (literal_pos_bits));
++ properties[4].ulVal = UInt32(VALUE (compression_mode));
++ properties[5].ulVal = UInt32(VALUE (fast_bytes));
++#undef VALUE
++
++ properties[6].vt = VT_BSTR;
++ properties[6].bstrVal = (BSTR)opt.match_finder;
++
++ properties[7].vt = VT_BOOL;
++ properties[7].boolVal = stdinput ? VARIANT_TRUE : VARIANT_FALSE;
++
++ if (encoder->SetCoderProperties(propIDs, properties, kNumProps) != S_OK)
++ throw Exception("SetCoderProperties() error");
++}
++
++void encode(NCompress::NLzma::CEncoder *encoderSpec,
++ CMyComPtr<ISequentialInStream> inStream,
++ CMyComPtr<ISequentialOutStream> outStream,
++ lzma_option encoder_options,
++ UInt64 fileSize)
++{
++ set_encoder_properties(encoderSpec, encoder_options);
++
++ encoderSpec->WriteCoderProperties(outStream);
++
++ for (int i = 0; i < 8; i++)
++ {
++ Byte b = Byte(fileSize >> (8 * i));
++ if (outStream->Write(&b, sizeof(b), 0) != S_OK)
++ throw Exception("Write error while encoding");
++ }
++
++ HRESULT result = encoderSpec->Code(inStream, outStream, 0, 0, 0);
++
++ if (result == E_OUTOFMEMORY)
++ throw Exception("Cannot allocate memory");
++ else if (result != S_OK) {
++ char buffer[33];
++ snprintf(buffer, 33, "%d", (unsigned int)result);
++ throw Exception(string("Encoder error: ") + buffer);
++ }
++}
++
++void decode(NCompress::NLzma::CDecoder *decoderSpec,
++ CMyComPtr<ISequentialInStream> inStream,
++ CMyComPtr<ISequentialOutStream> outStream)
++{
++ const UInt32 kPropertiesSize = 5;
++ Byte properties[kPropertiesSize];
++ UInt32 processedSize;
++ UInt64 fileSize = 0;
++
++ if (inStream->Read(properties, kPropertiesSize, &processedSize) != S_OK)
++ throw Exception("Read error");
++ if (processedSize != kPropertiesSize)
++ throw Exception("Read error");
++ if (decoderSpec->SetDecoderProperties2(properties, kPropertiesSize) != S_OK)
++ throw Exception("SetDecoderProperties() error");
++
++ for (int i = 0; i < 8; i++)
++ {
++ Byte b;
++
++ if (inStream->Read(&b, sizeof(b), &processedSize) != S_OK)
++ throw Exception("Read error");
++ if (processedSize != 1)
++ throw Exception("Read error");
++
++ fileSize |= ((UInt64)b) << (8 * i);
++ }
++
++ if (decoderSpec->Code(inStream, outStream, 0, &fileSize, 0) != S_OK)
++ throw Exception("Decoder error");
++}
++
++int open_instream(const string infile,
++ CMyComPtr<ISequentialInStream> &inStream,
++ UInt64 &fileSize)
++{
++ CInFileStream *inStreamSpec = new CInFileStream;
++ inStream = inStreamSpec;
++ if (!inStreamSpec->Open(infile.c_str()))
++ throw Exception("Cannot open input file " + infile);
++
++ inStreamSpec->File.GetLength(fileSize);
++
++ return inStreamSpec->File.GetHandle();
++}
++
++int open_outstream(const string outfile,
++ CMyComPtr<ISequentialOutStream> &outStream)
++{
++ COutFileStream *outStreamSpec = new COutFileStream;
++ outStream = outStreamSpec;
++
++ bool open_by_force = (program_mode == PM_TEST) | force;
++
++ if (!outStreamSpec->Create(outfile.c_str(), open_by_force))
++ throw Exception("Cannot open output file " + outfile);
++
++ return outStreamSpec->File.GetHandle();
++}
++
++double get_ratio(int inhandle, int outhandle)
++{
++ struct stat in_stats, out_stats;
++ fstat(inhandle, &in_stats);
++ fstat(outhandle, &out_stats);
++
++ return (double)out_stats.st_size / (double)in_stats.st_size;
++}
++
++mode_t get_file_mode(string filename)
++{
++ struct stat in_stat;
++ lstat(filename.c_str(), &in_stat);
++
++ return in_stat.st_mode;
++}
++
++bool string_ends_with(string str, string ending)
++{
++ return equal(ending.rbegin(), ending.rend(), str.rbegin());
++}
++
++bool extension_is_known(string filename)
++{
++ bool known_format = false;
++ extension_pair extension; int i = 1;
++
++ extension = known_extensions[0];
++ while (extension.from != NULL) {
++ if (string_ends_with(filename, extension.from)) {
++ known_format = true;
++ break;
++ }
++ extension = known_extensions[i];
++ i++;
++ }
++
++ if (!known_format) {
++ if (!string_ends_with(filename, suffix)) {
++ return false;
++ }
++ }
++
++ return true;
++}
++
++string replace_extension(string filename)
++{
++ int suffix_starts_at = filename.length() - strlen (suffix);
++ string from_suffix = filename.substr(suffix_starts_at, strlen (suffix));
++ string ret = filename.substr(0, suffix_starts_at);
++ extension_pair extension; int i = 1;
++
++ bool found_replacement = false;
++ extension = known_extensions[0];
++ while (extension.from != NULL) {
++ if (from_suffix.compare(extension.from) == 0) {
++ ret += extension.to;
++ found_replacement = true;
++ break;
++ }
++
++ extension = known_extensions[i];
++ i++;
++ }
++
++ return ret;
++}
++
++string pretty_print_status(string filename, string output_filename,
++ string ratio)
++{
++ string ret = "";
++
++ ret += filename;
++ ret += ":\t ";
++
++ if (program_mode == PM_TEST) {
++ ret += "decoded succesfully";
++
++ return ret;
++ }
++
++ if (!stdinput && !stdoutput) {
++ ret += ratio;
++ ret += " -- ";
++ }
++
++ if (program_mode == PM_COMPRESS) {
++ if (keep) {
++ ret += "encoded succesfully";
++
++ return ret;
++ }
++
++ ret += "replaced with ";
++ ret += output_filename;
++
++ return ret;
++ }
++
++ if (program_mode == PM_DECOMPRESS) {
++ if (keep) {
++ ret += "decoded succesfully";
++
++ return ret;
++ }
++
++ ret += "replaced with ";
++ ret += output_filename;
++
++ return ret;
++ }
++
++ return ret;
++}
++
++static string archive_name; // I know, it is crude, but I haven't found any other
++ // way then making a global variable to transfer filename to handler
++
++void signal_handler (int signum)
++{
++ unlink (archive_name.c_str()); // deleting
++ signal (signum, SIG_DFL); // we return the default function to used signal
++ kill (getpid(), signum); // and then send this signal to the process again
++}
++
++} // namespace lzma
++
++
++int main(int argc, char **argv)
++{
++ using namespace lzma;
++ using std::cerr;
++
++ stringVector filenames;
++
++ signal (SIGTERM,signal_handler);
++ signal (SIGHUP,signal_handler);
++ signal (SIGINT,signal_handler);
++
++ try {
++ parse_options(argc, argv, filenames);
++ }
++ catch (...) {
++ return STATUS_ERROR;
++ }
++
++ if (program_mode == PM_HELP) {
++ print_help(argv[0]);
++ return STATUS_OK;
++ }
++ else if (program_mode == PM_LICENSE) {
++ print_license();
++ return STATUS_OK;
++ }
++ else if (program_mode == PM_VERSION) {
++ print_version();
++ return STATUS_OK;
++ }
++
++ if (filenames.empty()) {
++ stdinput = true;
++ stdoutput = true;
++
++ /* FIXME: get rid of this */
++ filenames.push_back("-");
++ }
++
++ /* Protection: always create new files with 0600 in order to prevent
++ * outsiders from reading incomplete data. */
++ umask(0077);
++
++ bool warning = false;
++
++ for (int i = 0; i < filenames.size(); i++) {
++ CMyComPtr<ISequentialInStream> inStream;
++ CMyComPtr<ISequentialOutStream> outStream;
++ UInt64 fileSize = 0;
++ int inhandle = 0, outhandle = 0;
++ string output_filename;
++
++ if (stdinput) {
++ inStream = new CStdInFileStream;
++ MY_SET_BINARY_MODE(stdin);
++ fileSize = (UInt64)(Int64)-1;
++
++ inhandle = STDIN_FILENO;
++
++ outStream = new CStdOutFileStream;
++ MY_SET_BINARY_MODE(stdout);
++
++ outhandle = STDOUT_FILENO;
++ }
++ else {
++ mode_t infile_mode = get_file_mode(filenames[i]);
++ if (!S_ISREG(infile_mode)) {
++ if (S_ISDIR(infile_mode)) {
++ warning = true;
++ cerr << argv[0] << ": " << filenames[i] << ": "
++ << "cowardly refusing to work on directory"
++ << endl;
++
++ continue;
++ }
++ else if (S_ISLNK(infile_mode)) {
++ if (!stdoutput && !force) {
++ warning = true;
++
++ cerr << argv[0] << ": " << filenames[i] << ": "
++ << "cowardly refusing to work on symbolic link "
++ << "(use --force to force encoding or decoding)"
++ << endl;
++
++ continue;
++ }
++ }
++ else {
++ warning = true;
++
++ cerr << argv[0] << ": " << filenames[i] << ": "
++ << "doesn't exist or is not a regular file"
++ << endl;
++
++ continue;
++ }
++ }
++
++ // Test if the file already ends with *suffix.
++ if (program_mode == PM_COMPRESS && !force
++ && string_ends_with(filenames[i],
++ suffix)) {
++ warning = true;
++
++ cerr << filenames[i] << " already has "
++ << suffix << " suffix -- unchanged\n";
++
++ continue;
++ }
++
++ // Test if the file extension is known.
++ if (program_mode == PM_DECOMPRESS
++ && !extension_is_known(filenames[i])) {
++ warning = true;
++
++ cerr << filenames[i] << ": "
++ << " unknown suffix -- unchanged"
++ << endl;
++
++ continue;
++ }
++
++ try {
++ inhandle = open_instream(filenames[i], inStream, fileSize);
++ }
++ catch (Exception e) {
++ cerr << argv[0] << ": " << e.what() << endl;
++ return STATUS_ERROR;
++ }
++
++ if (stdoutput) {
++ outStream = new CStdOutFileStream;
++ MY_SET_BINARY_MODE(stdout);
++
++ outhandle = STDOUT_FILENO;
++ }
++ else {
++ /* Testing mode is nothing else but decoding
++ * and throwing away the result. */
++ if (program_mode == PM_TEST)
++ output_filename = "/dev/null";
++ else if (program_mode == PM_DECOMPRESS)
++ output_filename = replace_extension(filenames[i]);
++ else
++ output_filename = filenames[i]
++ + suffix;
++ archive_name = output_filename;
++
++ try {
++ outhandle = open_outstream(output_filename, outStream);
++ }
++ catch (Exception e) {
++ cerr << argv[0] << ": " << e.what() << endl;
++ return STATUS_ERROR;
++ }
++ }
++
++ }
++
++ // Unless --force is specified, do not read/write compressed
++ // data from/to a terminal.
++ if (!force) {
++ if (program_mode == PM_COMPRESS && isatty(outhandle)) {
++ cerr << argv[0] << ": compressed data not "
++ "written to a terminal. Use "
++ "-f to force compression.\n"
++ << argv[0] << ": For help, type: "
++ << argv[0] << " -h\n";
++ return STATUS_ERROR;
++ } else if (program_mode == PM_DECOMPRESS
++ && isatty(inhandle)) {
++ cerr << argv[0] << ": compressed data not "
++ "read from a terminal. Use "
++ "-f to force decompression.\n"
++ << argv[0] << ": For help, type: "
++ << argv[0] << " -h\n";
++ return STATUS_ERROR;
++ }
++ }
++
++ if (program_mode == PM_COMPRESS) {
++ NCompress::NLzma::CEncoder *encoderSpec =
++ new NCompress::NLzma::CEncoder;
++
++ lzma_option options = option_mapping[compression_mode];
++
++ try {
++ encode(encoderSpec, inStream, outStream, options, fileSize);
++ }
++ catch (Exception e) {
++ cerr << argv[0] << ": " << e.what() << endl;
++ unlink(output_filename.c_str());
++ delete(encoderSpec);
++
++ return STATUS_ERROR;
++ }
++
++ delete(encoderSpec);
++ }
++ else { // PM_DECOMPRESS | PM_TEST
++ NCompress::NLzma::CDecoder *decoderSpec =
++ new NCompress::NLzma::CDecoder;
++
++ try {
++ decode(decoderSpec, inStream, outStream);
++ }
++ catch (Exception e) {
++ cerr << argv[0] << ": " << e.what() << endl;
++ unlink(output_filename.c_str());
++ delete(decoderSpec);
++
++ return STATUS_ERROR;
++ }
++
++ delete(decoderSpec);
++ }
++
++ /* Set permissions and owners. */
++ if ( (program_mode == PM_COMPRESS || program_mode == PM_DECOMPRESS )
++ && (!stdinput && !stdoutput) ) {
++
++ int ret = 0;
++ struct stat file_stats;
++ ret = fstat(inhandle, &file_stats);
++
++ ret = fchmod(outhandle, file_stats.st_mode);
++ ret = fchown(outhandle, file_stats.st_uid, file_stats.st_gid);
++ // We need to call fchmod() again, since otherwise the SUID bits
++ // are lost.
++ ret = fchmod(outhandle, file_stats.st_mode);
++
++ struct timeval file_times[2];
++ // Access time
++ file_times[0].tv_sec = file_stats.st_atime;
++ file_times[0].tv_usec = 0;
++ // Modification time
++ file_times[1].tv_sec = file_stats.st_mtime;
++ file_times[1].tv_usec = 0;
++
++ ret = futimes(outhandle, file_times);
++
++ if (!keep)
++ unlink(filenames[i].c_str());
++ }
++
++ if (verbosity > 0) {
++ if (stdoutput) {
++ cerr << filenames[i] << ":\t ";
++ cerr << "decoded succesfully"
++ << endl;
++ }
++
++ else {
++ char buf[10] = { 0 };
++
++ if (program_mode == PM_DECOMPRESS)
++ snprintf(buf, 10, "%.2f%%",
++ (1 - get_ratio(outhandle, inhandle)) * 100);
++ if (program_mode == PM_COMPRESS)
++ snprintf(buf, 10, "%.2f%%",
++ (1 - get_ratio(inhandle, outhandle)) * 100);
++
++ string ratio = buf;
++ cerr << pretty_print_status(filenames[i], output_filename,
++ ratio)
++ << endl;
++ }
++ }
++ }
++
++ if (warning)
++ return STATUS_WARNING;
++
++ return STATUS_OK;
++}
++
+--- /dev/null
++++ b/CPP/7zip/Compress/LZMA_Alone/Exception.h
+@@ -0,0 +1,45 @@
++/* A couple of exceptions for lzmp.
++ *
++ * Copyright (C) 2005 Ville Koskinen
++ *
++ * 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 2
++ * 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.
++ */
++
++#ifndef _EXCEPTION_H_
++#define _EXCEPTION_H_
++
++#include <string>
++using std::string;
++
++class Exception
++{
++private:
++ string message;
++public:
++ Exception(char *what): message(what) { }
++ Exception(string what): message(what) { }
++
++ ~Exception() { }
++
++ string what(void) { return message; }
++};
++
++class ArgumentException: public Exception
++{
++public:
++ ArgumentException(char *what): Exception(what) { }
++ ArgumentException(string what): Exception(what) { }
++
++ ~ArgumentException() { }
++};
++
++#endif
++
+--- a/CPP/7zip/Compress/LZMA_Alone/makefile.gcc
++++ b/CPP/7zip/Compress/LZMA_Alone/makefile.gcc
+@@ -1,9 +1,10 @@
+-PROG = lzma
++PROG = lzma_alone
++PROG2 = lzma
+ CXX = g++ -O2 -Wall
+ CXX_C = gcc -O2 -Wall
+ LIB = -lm
+ RM = rm -f
+-CFLAGS = -c -D_FILE_OFFSET_BITS=64
++CFLAGS = -c -I ../../../ -D_FILE_OFFSET_BITS=64 -DPACKAGE_VERSION="\"4.32.0beta3\""
+
+ ifdef SystemDrive
+ IS_MINGW = 1
+@@ -45,12 +46,35 @@ OBJS = \
+ Lzma86Dec.o \
+ Lzma86Enc.o \
+
++OBJS2 = \
++ C_FileIO.o \
++ CRC.o \
++ Alloc.o \
++ FileStreams.o \
++ StreamUtils.o \
++ InBuffer.o \
++ OutBuffer.o \
++ LzmaDecoder.o \
++ StringConvert.o \
++ StringToInt.o \
++ LzmaEncoder.o \
++ LzmaDec.o \
++ LzmaEnc.o \
++ LzFind.o \
++ 7zCrc.o \
++ lzmp.o
+
+-all: $(PROG)
++all: $(PROG) $(PROG2)
+
+ $(PROG): $(OBJS)
+ $(CXX) -o $(PROG) $(LDFLAGS) $(OBJS) $(LIB) $(LIB2)
+
++$(PROG2): $(OBJS2)
++ $(CXX) -o $(PROG2) $(LDFLAGS) $(OBJS2) $(LIB)
++
++lzmp.o: lzmp.cpp
++ $(CXX) $(CFLAGS) lzmp.cpp
++
+ LzmaAlone.o: LzmaAlone.cpp
+ $(CXX) $(CFLAGS) LzmaAlone.cpp
+
+@@ -131,5 +155,5 @@ Lzma86Enc.o: ../../../../C/LzmaUtil/Lzma
+ $(CXX_C) $(CFLAGS) ../../../../C/LzmaUtil/Lzma86Enc.c
+
+ clean:
+- -$(RM) $(PROG) $(OBJS)
++ -$(RM) $(PROG) $(PROG2) $(OBJS)
+
+--- /dev/null
++++ b/CPP/7zip/Compress/LZMA_Alone/lzma_version.h
+@@ -0,0 +1,31 @@
++#ifndef LZMA_VERSION_H
++#define LZMA_VERSION_H
++
++/*
++ Version and copyright information used by LZMA utils.
++*/
++
++static const char *LZMA_SDK_VERSION_STRING = "4.43";
++
++static const char *LZMA_SDK_COPYRIGHT_STRING =
++ "Copyright (C) 1999-2006 Igor Pavlov";
++
++static const char *LZMA_SDK_COPYRIGHT_INFO =
++ " See http://7-zip.org/sdk.html or the documentation of LZMA SDK for\n"
++ " the license. For reference, the version 4.43 is free software\n"
++ " licensed under the GNU LGPL.";
++
++
++static const char *LZMA_UTILS_VERSION_STRING = PACKAGE_VERSION;
++
++static const char *LZMA_UTILS_COPYRIGHT_STRING =
++ "Copyright (C) 2006 Lasse Collin";
++
++static const char *LZMA_UTILS_COPYRIGHT_INFO =
++ "This program comes with ABSOLUTELY NO WARRANTY.\n"
++ "You may redistribute copies of this program\n"
++ "under the terms of the GNU General Public License.\n"
++ "For more information about these matters, see the file "
++ "named COPYING.\n";
++
++#endif /* ifndef LZMA_VERSION_H */
+--- a/CPP/Common/C_FileIO.h
++++ b/CPP/Common/C_FileIO.h
+@@ -24,6 +24,7 @@ public:
+ bool Close();
+ bool GetLength(UInt64 &length) const;
+ off_t Seek(off_t distanceToMove, int moveMethod) const;
++ int GetHandle() const { return _handle; }
+ };
+
+ class CInFile: public CFileBase
diff --git a/tools/lzma/patches/003-compile_fixes.patch b/tools/lzma/patches/003-compile_fixes.patch
new file mode 100644
index 0000000..06f7a54
--- /dev/null
+++ b/tools/lzma/patches/003-compile_fixes.patch
@@ -0,0 +1,24 @@
+--- a/CPP/7zip/Common/FileStreams.h
++++ b/CPP/7zip/Common/FileStreams.h
+@@ -72,6 +72,7 @@ class COutFileStream:
+ public IOutStream,
+ public CMyUnknownImp
+ {
++public:
+ #ifdef USE_WIN_FILE
+ NWindows::NFile::NIO::COutFile File;
+ #else
+--- a/CPP/Common/MyWindows.h
++++ b/CPP/Common/MyWindows.h
+@@ -101,8 +101,11 @@ typedef LONG SCODE;
+
+ #ifdef __cplusplus
+
++#ifndef INITGUID
++#define INITGUID
+ DEFINE_GUID(IID_IUnknown,
+ 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
++#endif
+ struct IUnknown
+ {
+ STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE;
diff --git a/tools/lzma/patches/100-static_library.patch b/tools/lzma/patches/100-static_library.patch
new file mode 100644
index 0000000..15ab4e0
--- /dev/null
+++ b/tools/lzma/patches/100-static_library.patch
@@ -0,0 +1,70 @@
+--- a/C/LzmaUtil/makefile.gcc
++++ b/C/LzmaUtil/makefile.gcc
+@@ -1,44 +1,53 @@
+ PROG = lzma
+-CXX = g++
+-LIB =
++CC = gcc
++LIB = liblzma.a
+ RM = rm -f
+ CFLAGS = -c -O2 -Wall
++AR = ar
++RANLIB = ranlib
+
+ OBJS = \
+- LzmaUtil.o \
+ Alloc.o \
+ LzFind.o \
+ LzmaDec.o \
+ LzmaEnc.o \
++ LzmaLib.o \
+ 7zFile.o \
+ 7zStream.o \
+
+-
+ all: $(PROG)
+
+-$(PROG): $(OBJS)
+- $(CXX) -o $(PROG) $(LDFLAGS) $(OBJS) $(LIB) $(LIB2)
++$(PROG): LzmaUtil.o $(LIB)
++ $(CC) -o $(PROG) $(LDFLAGS) $< $(LIB)
+
+ LzmaUtil.o: LzmaUtil.c
+- $(CXX) $(CFLAGS) LzmaUtil.c
++ $(CC) $(CFLAGS) LzmaUtil.c
++
++$(LIB): $(OBJS)
++ rm -f $@
++ $(AR) rcu $@ $(OBJS)
++ $(RANLIB) $@
+
+ Alloc.o: ../Alloc.c
+- $(CXX) $(CFLAGS) ../Alloc.c
++ $(CC) $(CFLAGS) ../Alloc.c
+
+ LzFind.o: ../LzFind.c
+- $(CXX) $(CFLAGS) ../LzFind.c
++ $(CC) $(CFLAGS) ../LzFind.c
+
+ LzmaDec.o: ../LzmaDec.c
+- $(CXX) $(CFLAGS) ../LzmaDec.c
++ $(CC) $(CFLAGS) ../LzmaDec.c
+
+ LzmaEnc.o: ../LzmaEnc.c
+- $(CXX) $(CFLAGS) ../LzmaEnc.c
++ $(CC) $(CFLAGS) ../LzmaEnc.c
++
++LzmaLib.o: ../LzmaLib.c
++ $(CC) $(CFLAGS) ../LzmaLib.c
+
+ 7zFile.o: ../7zFile.c
+- $(CXX) $(CFLAGS) ../7zFile.c
++ $(CC) $(CFLAGS) ../7zFile.c
+
+ 7zStream.o: ../7zStream.c
+- $(CXX) $(CFLAGS) ../7zStream.c
++ $(CC) $(CFLAGS) ../7zStream.c
+
+ clean:
+- -$(RM) $(PROG) $(OBJS)
++ -$(RM) $(PROG) *.o *.a
diff --git a/tools/lzma/patches/101-move-copyright-to-usage-info.patch b/tools/lzma/patches/101-move-copyright-to-usage-info.patch
new file mode 100644
index 0000000..ec69285
--- /dev/null
+++ b/tools/lzma/patches/101-move-copyright-to-usage-info.patch
@@ -0,0 +1,20 @@
+--- a/CPP/7zip/Compress/LZMA_Alone/LzmaAlone.cpp
++++ b/CPP/7zip/Compress/LZMA_Alone/LzmaAlone.cpp
+@@ -101,6 +101,8 @@ static const int kNumSwitches = sizeof(k
+
+ static void PrintHelp()
+ {
++ fprintf(stderr, "\nLZMA " MY_VERSION_COPYRIGHT_DATE "\n");
++
+ fprintf(stderr, "\nUsage: LZMA <e|d> inputFile outputFile [<switches>...]\n"
+ " e: encode file\n"
+ " d: decode file\n"
+@@ -168,8 +170,6 @@ int main2(int n, const char *args[])
+ g_IsNT = IsItWindowsNT();
+ #endif
+
+- fprintf(stderr, "\nLZMA " MY_VERSION_COPYRIGHT_DATE "\n");
+-
+ if (n == 1)
+ {
+ PrintHelp();
diff --git a/tools/lzop/Makefile b/tools/lzop/Makefile
new file mode 100644
index 0000000..65bd7fe
--- /dev/null
+++ b/tools/lzop/Makefile
@@ -0,0 +1,33 @@
+#
+# Copyright (C) 2022 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=lzop
+PKG_VERSION:=1.04
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=http://www.lzop.org/download/
+PKG_HASH:=7e72b62a8a60aff5200a047eea0773a8fb205caf7acbe1774d95147f305a2f41
+
+PKG_LICENSE:=GPL-2.0-or-later
+PKG_LICENSE_FILES:=COPYING
+
+CMAKE_BINARY_SUBDIR:=openwrt-build
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_HOST_OPTIONS += \
+ -DENABLE_DOCS=ON \
+ -DBUILD_TESTING=OFF
+
+define Host/Uninstall
+ rm -f $(STAGING_DIR_HOST)/bin/lzop
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/lzop/patches/001-add-cmake-ENABLE_DOCS-configurable.patch b/tools/lzop/patches/001-add-cmake-ENABLE_DOCS-configurable.patch
new file mode 100644
index 0000000..27af782
--- /dev/null
+++ b/tools/lzop/patches/001-add-cmake-ENABLE_DOCS-configurable.patch
@@ -0,0 +1,24 @@
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -50,6 +50,9 @@ endif()
+
+ project(lzop VERSION 1.04 LANGUAGES C)
+
++# configuration options
++option(ENABLE_DOCS "Install documentation." ON)
++
+ # install directories
+ if(NOT CMAKE_INSTALL_PREFIX)
+ message(FATAL_ERROR "ERROR: CMAKE_INSTALL_PREFIX is not defined.")
+@@ -186,9 +189,11 @@ if(DEFINED CMAKE_INSTALL_FULL_LIBDIR)
+
+ install(TARGETS lzop DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}")
+
++if(ENABLE_DOCS)
+ set(f AUTHORS COPYING NEWS README THANKS doc/lzop.html doc/lzop.man doc/lzop.pod doc/lzop.ps doc/lzop.tex doc/lzop.txt)
+ install(FILES ${f} DESTINATION "${CMAKE_INSTALL_FULL_DOCDIR}")
+ install(FILES doc/lzop.1 DESTINATION "${CMAKE_INSTALL_FULL_MANDIR}/man1")
++endif() # ENABLE_DOCS
+
+ endif() # CMAKE_INSTALL_FULL_LIBDIR
+
diff --git a/tools/m4/Makefile b/tools/m4/Makefile
new file mode 100644
index 0000000..ee369f3
--- /dev/null
+++ b/tools/m4/Makefile
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2008-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=m4
+PKG_CPE_ID:=cpe:/a:gnu:m4
+PKG_VERSION:=1.4.19
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=3be4a26d825ffdfda52a56fc43246456989a3630093cced3fbddf4771ee58a70
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_VARS += gl_cv_func_strstr_linear=no
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/make-ext4fs/Makefile b/tools/make-ext4fs/Makefile
new file mode 100644
index 0000000..b5616b1
--- /dev/null
+++ b/tools/make-ext4fs/Makefile
@@ -0,0 +1,28 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+# Copyright (C) 2016 LEDE project
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=make-ext4fs
+
+PKG_SOURCE_URL=$(PROJECT_GIT)/project/make_ext4fs.git
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_DATE:=2020-01-05
+PKG_SOURCE_VERSION:=5c201be7d72aff735da27e17c29852e0cefe3e52
+PKG_MIRROR_HASH:=ec8304dc06f94338e14e608a807f48e10d0987bdac4d90f235650b46994dfbd7
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/make_ext4fs $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/make_ext4fs
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/meson/Makefile b/tools/meson/Makefile
new file mode 100644
index 0000000..f967f33
--- /dev/null
+++ b/tools/meson/Makefile
@@ -0,0 +1,35 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=meson
+PKG_VERSION:=1.5.1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/mesonbuild/meson/releases/download/$(PKG_VERSION)
+PKG_HASH:=567e533adf255de73a2de35049b99923caf872a455af9ce03e01077e0d384bed
+
+PKG_MAINTAINER:=Andre Heider <a.heider@gmail.com>
+PKG_LICENSE:=Apache-2.0
+PKG_LICENSE_FILES:=COPYING
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+endef
+
+define Host/Compile
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin
+ $(HOST_BUILD_DIR)/packaging/create_zipapp.py $(HOST_BUILD_DIR) --outfile $(STAGING_DIR_HOST)/bin/meson.py
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/lib/meson
+ $(INSTALL_CONF) files/openwrt-cross.txt.in $(STAGING_DIR_HOST)/lib/meson/
+ $(INSTALL_CONF) files/openwrt-native.txt.in $(STAGING_DIR_HOST)/lib/meson/
+endef
+
+define Host/Clean
+ $(call Host/Clean/Default)
+ rm -rf $(STAGING_DIR_HOST)/lib/meson
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/meson/files/openwrt-cross.txt.in b/tools/meson/files/openwrt-cross.txt.in
new file mode 100644
index 0000000..836a0e5
--- /dev/null
+++ b/tools/meson/files/openwrt-cross.txt.in
@@ -0,0 +1,27 @@
+[binaries]
+c = [@CC@]
+c_ld = [@LD@]
+cpp = [@CXX@]
+cpp_ld = [@LD@]
+ar = '@AR@'
+strip = '@STRIP@'
+nm = '@NM@'
+pkg-config = '@PKGCONFIG@'
+cmake = '@CMAKE@'
+python = '@PYTHON@'
+
+[built-in options]
+c_args = [@CFLAGS@]
+c_link_args = [@LDFLAGS@]
+cpp_args = [@CXXFLAGS@]
+cpp_link_args = [@LDFLAGS@]
+prefix = '/usr'
+
+[host_machine]
+system = 'linux'
+cpu_family = '@ARCH@'
+cpu = '@CPU@'
+endian = '@ENDIAN@'
+
+[properties]
+needs_exe_wrapper = true
diff --git a/tools/meson/files/openwrt-native.txt.in b/tools/meson/files/openwrt-native.txt.in
new file mode 100644
index 0000000..179e00b
--- /dev/null
+++ b/tools/meson/files/openwrt-native.txt.in
@@ -0,0 +1,15 @@
+[binaries]
+c = [@CC@]
+cpp = [@CXX@]
+pkg-config = '@PKGCONFIG@'
+cmake = '@CMAKE@'
+python = '@PYTHON@'
+
+[built-in options]
+c_args = [@CFLAGS@]
+c_link_args = [@LDFLAGS@]
+cpp_args = [@CXXFLAGS@]
+cpp_link_args = [@LDFLAGS@]
+prefix = '@PREFIX@'
+sbindir = 'bin'
+libdir = 'lib'
diff --git a/tools/missing-macros/Makefile b/tools/missing-macros/Makefile
new file mode 100644
index 0000000..15a1cc9
--- /dev/null
+++ b/tools/missing-macros/Makefile
@@ -0,0 +1,33 @@
+#
+# Copyright (C) 2010-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=missing-macros
+PKG_RELEASE:=12
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+endef
+
+define Host/Compile
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/share/aclocal
+ $(INSTALL_DATA) $(HOST_BUILD_DIR)/m4/*.m4 $(STAGING_DIR_HOST)/share/aclocal/
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/bin/* $(STAGING_DIR_HOST)/bin/
+ $(LN) makeinfo $(STAGING_DIR_HOST)/bin/texi2any
+ $(LN) makeinfo $(STAGING_DIR_HOST)/bin/texi2pdf
+ $(LN) makeinfo $(STAGING_DIR_HOST)/bin/texi2dvi
+ $(LN) makeinfo $(STAGING_DIR_HOST)/bin/pdftexi2dvi
+ $(LN) makeinfo $(STAGING_DIR_HOST)/bin/texi2html
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/missing-macros/src/README b/tools/missing-macros/src/README
new file mode 100644
index 0000000..dd9a9d3
--- /dev/null
+++ b/tools/missing-macros/src/README
@@ -0,0 +1,87 @@
+The m4/ directory below contains various m4 macros used
+by different packages in the OpenWrt feed.
+
+
+Integer data type test macros.
+
+ intmax.m4
+ inttypes-pri.m4
+ uintmax_t.m4
+ intdiv0.m4
+
+
+GNU libc version test macros.
+
+ glibc2.m4
+ glibc21.m4
+
+
+From UCL and LZO:
+Compiler ACC conformance testing macros.
+
+ mfx_acc.m4
+ mfx_cppflags.m4
+ mfx_limits.m4
+
+
+From OSSP-JS:
+Test macros for va_copy() implementations.
+
+ va_copy.m4
+
+
+From libmikmod:
+Feature test macros for the Enlightment Sound Daemon.
+
+ esd.m4
+
+
+From libdnet:
+Feature test macros for socket api implementations.
+
+ dnet.m4
+
+
+From FLAC:
+XMMS feature detection macros.
+
+ xmms.m4
+
+
+From ao:
+Directory expansion macro for Automake.
+
+ as-ac-expand.m4
+
+
+From tinyproxy:
+Autostars m4 macro for detection of compiler flags.
+
+ as-compiler-flags.m4
+
+
+From morituri:
+Autostars m4 macro for versioning.
+
+ as-version.m4
+
+
+From liboil:
+Check if unaligned memory access works correctly.
+
+ as-unaligned-access.m4
+
+
+From OpenWrt:
+Always disable GTK docs.
+
+ fake-gtk-doc-check.m4
+
+Provide intltool.m4 stubs to allow for autoreconf.
+
+ fake-intltool.m4
+
+From XDM:
+XAW macros.
+
+ xaw.m4
diff --git a/tools/missing-macros/src/bin/help2man b/tools/missing-macros/src/bin/help2man
new file mode 100755
index 0000000..6cbec57
--- /dev/null
+++ b/tools/missing-macros/src/bin/help2man
@@ -0,0 +1,29 @@
+#!/usr/bin/env perl
+
+use strict;
+use Getopt::Long;
+
+my $output;
+my $version;
+
+Getopt::Long::Configure('pass_through');
+Getopt::Long::GetOptions(
+ 'output=s' => \$output,
+ 'version' => \$version
+);
+
+if ($version)
+{
+ printf "OpenWrt help2man 1.40.10\n";
+ exit 0;
+}
+elsif ($output)
+{
+ open O, "> $output" || die "Unable to open $output: $!\n";
+ print O "Dummy man page.\n";
+ close O;
+}
+else
+{
+ print O "Dummy man page.\n";
+}
diff --git a/tools/missing-macros/src/bin/makeinfo b/tools/missing-macros/src/bin/makeinfo
new file mode 100755
index 0000000..d698f7b
--- /dev/null
+++ b/tools/missing-macros/src/bin/makeinfo
@@ -0,0 +1,112 @@
+#!/usr/bin/env perl
+
+use strict;
+use Getopt::Long;
+
+my $output;
+my $version;
+my $docbook;
+my $html;
+my $xml;
+my $plaintext;
+my $no_split;
+my $no_headers;
+
+Getopt::Long::Configure('pass_through');
+Getopt::Long::GetOptions(
+ 'output=s' => \$output,
+ 'version' => \$version,
+ 'no-split' => \$no_split,
+ 'no-headers' => \$no_headers,
+ 'docbook' => \$docbook,
+ 'html' => \$html,
+ 'xml' => \$xml,
+ 'plaintext' => \$plaintext
+);
+
+if ($version)
+{
+ print "makeinfo (OpenWrt stub) 9.99\n";
+ exit 0;
+}
+
+
+sub output_filename
+{
+ my $path = shift || return;
+ my $name = $path;
+ my $setfile;
+
+ if (open F, "< $path")
+ {
+ while (defined(my $line = readline F))
+ {
+ if ($line =~ /\@setfilename\s+(\S+)/)
+ {
+ $setfile = $1;
+ $setfile =~ s!^.+/!!;
+ last;
+ }
+ }
+
+ close F;
+ }
+
+ $name =~ s!^.+/!!;
+ $name =~ s!\.[^.]+$!!;
+
+ if ($html)
+ {
+ $setfile =~ s!\.[^.]+$!! if $setfile;
+
+ if ($no_split)
+ {
+ return $setfile ? "$setfile.html" : "$name.html" unless $output;
+ return $output;
+ }
+
+ return $setfile ? "$setfile/index.html" : "$name/index.html" unless $output;
+ return "$output/index.html";
+ }
+ elsif ($xml || $docbook)
+ {
+ $setfile =~ s!\.[^.]+$!! if $setfile;
+
+ return $setfile ? "$setfile.xml" : "$name.info" unless $output;
+ return $output;
+ }
+ elsif ($plaintext)
+ {
+ return ($output || "-");
+ }
+
+ return ($output || $setfile || "$name.info");
+}
+
+foreach my $arg (@ARGV)
+{
+ next unless -f $arg;
+
+ my $out = output_filename($arg);
+ if ($out =~ m!^(.+/)[^/]+$!)
+ {
+ system("mkdir", "-p", $1);
+ }
+
+ my $fd = \*STDOUT;
+ if ($out ne "-" && !$no_headers)
+ {
+ open $fd, "> $out" || die "Can't open $out: $!\n";
+ }
+
+ if ($html || $xml || $docbook)
+ {
+ print $fd "<!-- Dummy output for $arg -->\n";
+ }
+ else
+ {
+ print $fd "Dummy output for $arg\n";
+ }
+
+ close $fd;
+}
diff --git a/tools/missing-macros/src/m4/as-ac-expand.m4 b/tools/missing-macros/src/m4/as-ac-expand.m4
new file mode 100644
index 0000000..d6c9e33
--- /dev/null
+++ b/tools/missing-macros/src/m4/as-ac-expand.m4
@@ -0,0 +1,43 @@
+dnl as-ac-expand.m4 0.2.0
+dnl autostars m4 macro for expanding directories using configure's prefix
+dnl thomas@apestaart.org
+
+dnl AS_AC_EXPAND(VAR, CONFIGURE_VAR)
+dnl example
+dnl AS_AC_EXPAND(SYSCONFDIR, $sysconfdir)
+dnl will set SYSCONFDIR to /usr/local/etc if prefix=/usr/local
+
+AC_DEFUN([AS_AC_EXPAND],
+[
+ EXP_VAR=[$1]
+ FROM_VAR=[$2]
+
+ dnl first expand prefix and exec_prefix if necessary
+ prefix_save=$prefix
+ exec_prefix_save=$exec_prefix
+
+ dnl if no prefix given, then use /usr/local, the default prefix
+ if test "x$prefix" = "xNONE"; then
+ prefix="$ac_default_prefix"
+ fi
+ dnl if no exec_prefix given, then use prefix
+ if test "x$exec_prefix" = "xNONE"; then
+ exec_prefix=$prefix
+ fi
+
+ full_var="$FROM_VAR"
+ dnl loop until it doesn't change anymore
+ while true; do
+ new_full_var="`eval echo $full_var`"
+ if test "x$new_full_var" = "x$full_var"; then break; fi
+ full_var=$new_full_var
+ done
+
+ dnl clean up
+ full_var=$new_full_var
+ AC_SUBST([$1], "$full_var")
+
+ dnl restore prefix and exec_prefix
+ prefix=$prefix_save
+ exec_prefix=$exec_prefix_save
+])
diff --git a/tools/missing-macros/src/m4/as-compiler-flag.m4 b/tools/missing-macros/src/m4/as-compiler-flag.m4
new file mode 100644
index 0000000..0f660cf
--- /dev/null
+++ b/tools/missing-macros/src/m4/as-compiler-flag.m4
@@ -0,0 +1,62 @@
+dnl as-compiler-flag.m4 0.1.0
+
+dnl autostars m4 macro for detection of compiler flags
+
+dnl David Schleef <ds@schleef.org>
+
+dnl $Id: as-compiler-flag.m4,v 1.1 2005/12/15 23:35:19 ds Exp $
+
+dnl AS_COMPILER_FLAG(CFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_COMPILER_FLAG],
+[
+ AC_MSG_CHECKING([to see if compiler understands $1])
+
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $1"
+
+ AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ m4_ifvaln([$2],[$2])
+ true
+ else
+ m4_ifvaln([$3],[$3])
+ true
+ fi
+ AC_MSG_RESULT([$flag_ok])
+])
+
+dnl AS_COMPILER_FLAGS(VAR, FLAGS)
+dnl Tries to compile with the given CFLAGS.
+
+AC_DEFUN([AS_COMPILER_FLAGS],
+[
+ list=$2
+ flags_supported=""
+ flags_unsupported=""
+ AC_MSG_CHECKING([for supported compiler flags])
+ for each in $list
+ do
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $each"
+ AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ flags_supported="$flags_supported $each"
+ else
+ flags_unsupported="$flags_unsupported $each"
+ fi
+ done
+ AC_MSG_RESULT([$flags_supported])
+ if test "X$flags_unsupported" != X ; then
+ AC_MSG_WARN([unsupported compiler flags: $flags_unsupported])
+ fi
+ $1="$$1 $flags_supported"
+])
+
diff --git a/tools/missing-macros/src/m4/as-unaligned-access.m4 b/tools/missing-macros/src/m4/as-unaligned-access.m4
new file mode 100644
index 0000000..ede8bd2
--- /dev/null
+++ b/tools/missing-macros/src/m4/as-unaligned-access.m4
@@ -0,0 +1,41 @@
+dnl AS_UNALIGNED_ACCESS
+
+dnl check if unaligned memory access works correctly
+AC_DEFUN([AS_UNALIGNED_ACCESS], [
+ AC_MSG_CHECKING([if unaligned memory access works correctly])
+ if test x"$as_cv_unaligned_access" = x ; then
+ case $host in
+ alpha*|arm*|hp*|mips*|sh*|sparc*|ia64*)
+ _AS_ECHO_N([(blacklisted) ])
+ as_cv_unaligned_access=no
+ ;;
+ i?86*|x86_64|amd64|powerpc*|m68k*|cris*)
+ _AS_ECHO_N([(whitelisted) ])
+ as_cv_unaligned_access=yes
+ ;;
+ esac
+ else
+ _AS_ECHO_N([(cached) ])
+ fi
+ if test x"$as_cv_unaligned_access" = x ; then
+ AC_TRY_RUN([
+int main(int argc, char **argv)
+{
+ char array[] = "ABCDEFGH";
+ unsigned int iarray[2];
+ memcpy(iarray,array,8);
+#define GET(x) (*(unsigned int *)((char *)iarray + (x)))
+ if(GET(0) != 0x41424344 && GET(0) != 0x44434241) return 1;
+ if(GET(1) != 0x42434445 && GET(1) != 0x45444342) return 1;
+ if(GET(2) != 0x43444546 && GET(2) != 0x46454443) return 1;
+ if(GET(3) != 0x44454647 && GET(3) != 0x47464544) return 1;
+ return 0;
+}
+ ], as_cv_unaligned_access="yes", as_cv_unaligned_access="no")
+ fi
+ AC_MSG_RESULT($as_cv_unaligned_access)
+ if test "$as_cv_unaligned_access" = "yes"; then
+ AC_DEFINE_UNQUOTED(HAVE_UNALIGNED_ACCESS, 1,
+ [defined if unaligned memory access works correctly])
+ fi
+])
diff --git a/tools/missing-macros/src/m4/as-version.m4 b/tools/missing-macros/src/m4/as-version.m4
new file mode 100644
index 0000000..a5b4399
--- /dev/null
+++ b/tools/missing-macros/src/m4/as-version.m4
@@ -0,0 +1,71 @@
+dnl as-version.m4 0.2.0
+
+dnl autostars m4 macro for versioning
+
+dnl Thomas Vander Stichele <thomas at apestaart dot org>
+
+dnl $Id: as-version.m4,v 1.4 2004/06/01 09:40:05 thomasvs Exp $
+
+dnl AS_VERSION
+
+dnl example
+dnl AS_VERSION
+
+dnl this macro
+dnl - AC_SUBST's PACKAGE_VERSION_MAJOR, _MINOR, _MICRO
+dnl - AC_SUBST's PACKAGE_VERSION_RELEASE,
+dnl which can be used for rpm release fields
+dnl - doesn't call AM_INIT_AUTOMAKE anymore because it prevents
+dnl maintainer mode from running correctly
+dnl
+dnl don't forget to put #undef PACKAGE_VERSION_RELEASE in acconfig.h
+dnl if you use acconfig.h
+
+AC_DEFUN([AS_VERSION],
+[
+ PACKAGE_VERSION_MAJOR=$(echo AC_PACKAGE_VERSION | cut -d'.' -f1)
+ PACKAGE_VERSION_MINOR=$(echo AC_PACKAGE_VERSION | cut -d'.' -f2)
+ PACKAGE_VERSION_MICRO=$(echo AC_PACKAGE_VERSION | cut -d'.' -f3)
+
+ AC_SUBST(PACKAGE_VERSION_MAJOR)
+ AC_SUBST(PACKAGE_VERSION_MINOR)
+ AC_SUBST(PACKAGE_VERSION_MICRO)
+])
+
+dnl AS_NANO(ACTION-IF-NO-NANO, [ACTION-IF-NANO])
+
+dnl requires AC_INIT to be called before
+dnl For projects using a fourth or nano number in your versioning to indicate
+dnl development or prerelease snapshots, this macro allows the build to be
+dnl set up differently accordingly.
+
+dnl this macro:
+dnl - parses AC_PACKAGE_VERSION, set by AC_INIT, and extracts the nano number
+dnl - sets the variable PACKAGE_VERSION_NANO
+dnl - sets the variable PACKAGE_VERSION_RELEASE, which can be used
+dnl for rpm release fields
+dnl - executes ACTION-IF-NO-NANO or ACTION-IF-NANO
+
+dnl example:
+dnl AS_NANO(RELEASE="yes", RELEASE="no")
+
+AC_DEFUN([AS_NANO],
+[
+ AC_MSG_CHECKING(nano version)
+
+ NANO=$(echo AC_PACKAGE_VERSION | cut -d'.' -f4)
+
+ if test x"$NANO" = x || test "x$NANO" = "x0" ; then
+ AC_MSG_RESULT([0 (release)])
+ NANO=0
+ PACKAGE_VERSION_RELEASE=1
+ ifelse([$1], , :, [$1])
+ else
+ AC_MSG_RESULT($NANO)
+ PACKAGE_VERSION_RELEASE=0.`date +%Y%m%d.%H%M%S`
+ ifelse([$2], , :, [$2])
+ fi
+ PACKAGE_VERSION_NANO=$NANO
+ AC_SUBST(PACKAGE_VERSION_NANO)
+ AC_SUBST(PACKAGE_VERSION_RELEASE)
+])
diff --git a/tools/missing-macros/src/m4/dnet.m4 b/tools/missing-macros/src/m4/dnet.m4
new file mode 100644
index 0000000..b57ead2
--- /dev/null
+++ b/tools/missing-macros/src/m4/dnet.m4
@@ -0,0 +1,322 @@
+# dnet.m4 serial 1 (libdnet-1.11)
+
+dnl
+dnl Check for 4.4 BSD sa_len member in sockaddr struct
+dnl
+dnl usage: AC_DNET_SOCKADDR_SA_LEN
+dnl results: HAVE_SOCKADDR_SA_LEN (defined)
+dnl
+AC_DEFUN([AC_DNET_SOCKADDR_SA_LEN],
+ [AC_MSG_CHECKING(for sa_len in sockaddr struct)
+ AC_CACHE_VAL(ac_cv_dnet_sockaddr_has_sa_len,
+ AC_TRY_COMPILE([
+# ifndef _SOCKADDR_LEN
+# define _SOCKADDR_LEN 1
+# endif
+# include <sys/types.h>
+# include <sys/socket.h>],
+ [u_int i = sizeof(((struct sockaddr *)0)->sa_len)],
+ ac_cv_dnet_sockaddr_has_sa_len=yes,
+ ac_cv_dnet_sockaddr_has_sa_len=no))
+ AC_MSG_RESULT($ac_cv_dnet_sockaddr_has_sa_len)
+ if test $ac_cv_dnet_sockaddr_has_sa_len = yes ; then
+ AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1,
+ [Define if sockaddr struct has sa_len.])
+ fi])
+
+dnl
+dnl Check for sockaddr_in6 struct in <netinet/in.h>
+dnl
+dnl usage: AC_DNET_SOCKADDR_IN6
+dnl results: HAVE_SOCKADDR_IN6
+dnl
+AC_DEFUN([AC_DNET_SOCKADDR_IN6],
+ [AC_MSG_CHECKING(for sockaddr_in6 struct in <netinet/in.h>)
+ AC_CACHE_VAL(ac_cv_dnet_netinet_in_h_has_sockaddr_in6,
+ AC_TRY_COMPILE([
+# include <sys/types.h>
+# include <sys/socket.h>
+# include <netinet/in.h>],
+ [struct sockaddr_in6 sin6; sin6.sin6_family = AF_INET6;],
+ ac_cv_dnet_netinet_in_h_has_sockaddr_in6=yes,
+ ac_cv_dnet_netinet_in_h_has_sockaddr_in6=no))
+ AC_MSG_RESULT($ac_cv_dnet_netinet_in_h_has_sockaddr_in6)
+ if test $ac_cv_dnet_netinet_in_h_has_sockaddr_in6 = yes ; then
+ AC_DEFINE(HAVE_SOCKADDR_IN6, 1,
+ [Define if <netinet/in.h> has sockaddr_in6 struct.])
+ fi])
+
+dnl
+dnl Check for arp_dev member in arpreq struct
+dnl
+dnl usage: AC_DNET_ARPREQ_ARP_DEV
+dnl results: HAVE_ARPREQ_ARP_DEV (defined)
+dnl
+AC_DEFUN([AC_DNET_ARPREQ_ARP_DEV],
+ [AC_MSG_CHECKING(for arp_dev in arpreq struct)
+ AC_CACHE_VAL(ac_cv_dnet_arpreq_has_arp_dev,
+ AC_TRY_COMPILE([
+# include <sys/types.h>
+# include <sys/socket.h>
+# include <net/if_arp.h>],
+ [void *p = ((struct arpreq *)0)->arp_dev],
+ ac_cv_dnet_arpreq_has_arp_dev=yes,
+ ac_cv_dnet_arpreq_has_arp_dev=no))
+ AC_MSG_RESULT($ac_cv_dnet_arpreq_has_arp_dev)
+ if test $ac_cv_dnet_arpreq_has_arp_dev = yes ; then
+ AC_DEFINE(HAVE_ARPREQ_ARP_DEV, 1,
+ [Define if arpreq struct has arp_dev.])
+ fi])
+
+dnl
+dnl Check for rt_msghdr struct in <net/route.h>
+dnl
+dnl usage: AC_DNET_ROUTE_RT_MSGHDR
+dnl results: HAVE_ROUTE_RT_MSGHDR
+dnl
+AC_DEFUN([AC_DNET_ROUTE_RT_MSGHDR],
+ [AC_MSG_CHECKING(for rt_msghdr struct in <net/route.h>)
+ AC_CACHE_VAL(ac_cv_dnet_route_h_has_rt_msghdr,
+ AC_TRY_COMPILE([
+# include <sys/types.h>
+# include <sys/socket.h>
+# include <net/if.h>
+# include <net/route.h>],
+ [struct rt_msghdr rtm; rtm.rtm_msglen = 0;],
+ ac_cv_dnet_route_h_has_rt_msghdr=yes,
+ ac_cv_dnet_route_h_has_rt_msghdr=no))
+ AC_MSG_RESULT($ac_cv_dnet_route_h_has_rt_msghdr)
+ if test $ac_cv_dnet_route_h_has_rt_msghdr = yes ; then
+ AC_DEFINE(HAVE_ROUTE_RT_MSGHDR, 1,
+ [Define if <net/route.h> has rt_msghdr struct.])
+ fi])
+
+dnl
+dnl Check for the Berkeley Packet Filter
+dnl
+dnl usage: AC_DNET_BSD_BPF
+dnl results: HAVE_BSD_BPF
+dnl
+AC_DEFUN([AC_DNET_BSD_BPF],
+ [AC_MSG_CHECKING(for Berkeley Packet Filter)
+ AC_CACHE_VAL(ac_cv_dnet_bsd_bpf,
+ if test -c /dev/bpf0 ; then
+ ac_cv_dnet_bsd_bpf=yes
+ else
+ ac_cv_dnet_bsd_bpf=no
+ fi)
+ AC_MSG_RESULT($ac_cv_dnet_bsd_bpf)
+ if test $ac_cv_dnet_bsd_bpf = yes ; then
+ AC_DEFINE(HAVE_BSD_BPF, 1,
+ [Define if you have the Berkeley Packet Filter.])
+ fi])
+
+dnl
+dnl Check for the Linux /proc filesystem
+dnl
+dnl usage: AC_DNET_LINUX_PROCFS
+dnl results: HAVE_LINUX_PROCFS
+dnl
+AC_DEFUN([AC_DNET_LINUX_PROCFS],
+ [AC_MSG_CHECKING(for Linux proc filesystem)
+ AC_CACHE_VAL(ac_cv_dnet_linux_procfs,
+ if test "x`cat /proc/sys/kernel/ostype 2>&-`" = "xLinux" ; then
+ ac_cv_dnet_linux_procfs=yes
+ else
+ ac_cv_dnet_linux_procfs=no
+ fi)
+ AC_MSG_RESULT($ac_cv_dnet_linux_procfs)
+ if test $ac_cv_dnet_linux_procfs = yes ; then
+ AC_DEFINE(HAVE_LINUX_PROCFS, 1,
+ [Define if you have the Linux /proc filesystem.])
+ fi])
+
+dnl
+dnl Check for Linux PF_PACKET sockets
+dnl
+dnl usage: AC_DNET_LINUX_PF_PACKET
+dnl results: HAVE_LINUX_PF_PACKET
+dnl
+AC_DEFUN([AC_DNET_LINUX_PF_PACKET],
+ [AC_MSG_CHECKING(for Linux PF_PACKET sockets)
+ AC_CACHE_VAL(ac_cv_dnet_linux_pf_packet,
+ if test -f /usr/include/netpacket/packet.h ; then
+ ac_cv_dnet_linux_pf_packet=yes
+ else
+ ac_cv_dnet_linux_pf_packet=no
+ fi)
+ AC_MSG_RESULT($ac_cv_dnet_linux_pf_packet)
+ if test $ac_cv_dnet_linux_pf_packet = yes ; then
+ AC_DEFINE(HAVE_LINUX_PF_PACKET, 1,
+ [Define if you have Linux PF_PACKET sockets.])
+ fi])
+
+dnl
+dnl Check for SNMP MIB2 STREAMS (Solaris only?)
+dnl
+dnl usage: AC_DNET_STREAMS_MIB2
+dnl results: HAVE_STREAMS_MIB2
+dnl
+AC_DEFUN([AC_DNET_STREAMS_MIB2],
+ [AC_MSG_CHECKING(for SNMP MIB2 STREAMS)
+ AC_CACHE_VAL(ac_cv_dnet_streams_mib2,
+ if test -f /usr/include/inet/mib2.h -a -c /dev/ip ; then
+ ac_cv_dnet_streams_mib2=yes
+ else
+ ac_cv_dnet_streams_mib2=no
+ fi)
+ AC_MSG_RESULT($ac_cv_dnet_streams_mib2)
+ if test $ac_cv_dnet_streams_mib2 = yes ; then
+ AC_DEFINE(HAVE_STREAMS_MIB2, 1,
+ [Define if you have SNMP MIB2 STREAMS.])
+ fi])
+
+dnl
+dnl Check for route(7) STREAMS (UnixWare only?)
+dnl
+dnl usage: AC_DNET_STREAMS_ROUTE
+dnl results: HAVE_STREAMS_ROUTE
+dnl
+AC_DEFUN([AC_DNET_STREAMS_ROUTE],
+ [AC_MSG_CHECKING(for route(7) STREAMS)
+ AC_CACHE_VAL(ac_cv_dnet_streams_route,
+ if grep RTSTR_SEND /usr/include/net/route.h >/dev/null 2>&1 ; then
+ ac_cv_dnet_streams_route=yes
+ else
+ ac_cv_dnet_streams_route=no
+ fi)
+ AC_MSG_RESULT($ac_cv_dnet_streams_route)
+ if test $ac_cv_dnet_streams_route = yes ; then
+ AC_DEFINE(HAVE_STREAMS_ROUTE, 1,
+ [Define if you have route(7) STREAMS.])
+ fi])
+
+dnl
+dnl Check for arp(7) ioctls
+dnl
+dnl usage: AC_DNET_IOCTL_ARP
+dnl results: HAVE_IOCTL_ARP
+dnl
+AC_DEFUN([AC_DNET_IOCTL_ARP],
+ [AC_MSG_CHECKING(for arp(7) ioctls)
+ AC_CACHE_VAL(ac_cv_dnet_ioctl_arp,
+ AC_EGREP_CPP(werd, [
+# include <sys/types.h>
+# define BSD_COMP
+# include <sys/ioctl.h>
+# ifdef SIOCGARP
+ werd
+# endif],
+ ac_cv_dnet_ioctl_arp=yes,
+ ac_cv_dnet_ioctl_arp=no))
+ case "$host_os" in
+ irix*)
+ ac_cv_dnet_ioctl_arp=no ;;
+ esac
+ AC_MSG_RESULT($ac_cv_dnet_ioctl_arp)
+ if test $ac_cv_dnet_ioctl_arp = yes ; then
+ AC_DEFINE(HAVE_IOCTL_ARP, 1,
+ [Define if you have arp(7) ioctls.])
+ fi])
+
+dnl
+dnl Check for raw IP sockets ip_{len,off} host byte ordering
+dnl
+dnl usage: AC_DNET_RAWIP_HOST_OFFLEN
+dnl results: HAVE_RAWIP_HOST_OFFLEN
+dnl
+AC_DEFUN([AC_DNET_RAWIP_HOST_OFFLEN],
+ [AC_MSG_CHECKING([for raw IP sockets ip_{len,off} host byte ordering])
+ AC_CACHE_VAL(ac_cv_dnet_rawip_host_offlen, [
+ case "$host_os" in
+ *openbsd*)
+ ac_cv_dnet_rawip_host_offlen=no ;;
+ *bsd*|*osf*|*unixware*)
+ ac_cv_dnet_rawip_host_offlen=yes ;;
+ *)
+ ac_cv_dnet_rawip_host_offlen=no ;;
+ esac])
+ AC_MSG_RESULT($ac_cv_dnet_rawip_host_offlen)
+ if test $ac_cv_dnet_rawip_host_offlen = yes ; then
+ AC_DEFINE(HAVE_RAWIP_HOST_OFFLEN, 1,
+ [Define if raw IP sockets require host byte ordering for ip_off, ip_len.])
+ fi])
+
+dnl
+dnl Check for cooked raw IP sockets
+dnl
+dnl usage: AC_DNET_RAWIP_COOKED
+dnl results: HAVE_RAWIP_COOKED
+dnl
+AC_DEFUN([AC_DNET_RAWIP_COOKED],
+ [AC_MSG_CHECKING(for cooked raw IP sockets)
+ AC_CACHE_VAL(ac_cv_dnet_rawip_cooked, [
+ case "$host_os" in
+ solaris*|irix*)
+ ac_cv_dnet_rawip_cooked=yes ;;
+ *)
+ ac_cv_dnet_rawip_cooked=no ;;
+ esac])
+ AC_MSG_RESULT($ac_cv_dnet_rawip_cooked)
+ if test $ac_cv_dnet_rawip_cooked = yes ; then
+ AC_DEFINE(HAVE_RAWIP_COOKED, 1,
+ [Define if you have cooked raw IP sockets.])
+ fi])
+
+dnl
+dnl AC_LBL_LIBRARY_NET
+dnl
+dnl This test is for network applications that need socket() and
+dnl gethostbyname() -ish functions. Under Solaris, those applications
+dnl need to link with "-lsocket -lnsl". Under IRIX, they need to link
+dnl with "-lnsl" but should *not* link with "-lsocket" because
+dnl libsocket.a breaks a number of things (for instance:
+dnl gethostbyname() under IRIX 5.2, and snoop sockets under most
+dnl versions of IRIX).
+dnl
+dnl Unfortunately, many application developers are not aware of this,
+dnl and mistakenly write tests that cause -lsocket to be used under
+dnl IRIX. It is also easy to write tests that cause -lnsl to be used
+dnl under operating systems where neither are necessary (or useful),
+dnl such as SunOS 4.1.4, which uses -lnsl for TLI.
+dnl
+dnl This test exists so that every application developer does not test
+dnl this in a different, and subtly broken fashion.
+
+dnl It has been argued that this test should be broken up into two
+dnl seperate tests, one for the resolver libraries, and one for the
+dnl libraries necessary for using Sockets API. Unfortunately, the two
+dnl are carefully intertwined and allowing the autoconf user to use
+dnl them independantly potentially results in unfortunate ordering
+dnl dependancies -- as such, such component macros would have to
+dnl carefully use indirection and be aware if the other components were
+dnl executed. Since other autoconf macros do not go to this trouble,
+dnl and almost no applications use sockets without the resolver, this
+dnl complexity has not been implemented.
+dnl
+dnl The check for libresolv is in case you are attempting to link
+dnl statically and happen to have a libresolv.a lying around (and no
+dnl libnsl.a).
+dnl
+AC_DEFUN([AC_LBL_LIBRARY_NET], [
+ # Most operating systems have gethostbyname() in the default searched
+ # libraries (i.e. libc):
+ AC_CHECK_FUNC(gethostbyname, ,
+ # Some OSes (eg. Solaris) place it in libnsl:
+ AC_CHECK_LIB(nsl, gethostbyname, ,
+ # Some strange OSes (SINIX) have it in libsocket:
+ AC_CHECK_LIB(socket, gethostbyname, ,
+ # Unfortunately libsocket sometimes depends on libnsl.
+ # AC_CHECK_LIB's API is essentially broken so the
+ # following ugliness is necessary:
+ AC_CHECK_LIB(socket, gethostbyname,
+ LIBS="-lsocket -lnsl $LIBS",
+ AC_CHECK_LIB(resolv, gethostbyname),
+ -lnsl))))
+ AC_CHECK_FUNC(socket, , AC_CHECK_LIB(socket, socket, ,
+ AC_CHECK_LIB(socket, socket, LIBS="-lsocket -lnsl $LIBS", ,
+ -lnsl)))
+ # DLPI needs putmsg under HPUX so test for -lstr while we're at it
+ AC_CHECK_LIB(str, putmsg)
+ ])
+
diff --git a/tools/missing-macros/src/m4/fake-gtk-doc-check.m4 b/tools/missing-macros/src/m4/fake-gtk-doc-check.m4
new file mode 100644
index 0000000..26fa723
--- /dev/null
+++ b/tools/missing-macros/src/m4/fake-gtk-doc-check.m4
@@ -0,0 +1,13 @@
+dnl fake-gtk-doc-check.m4 serial 1 (OpenWrt)
+dnl Provide a fake GTK_DOC_CHECK macros which
+dnl always defines false.
+
+AC_DEFUN([GTK_DOC_CHECK],
+[
+ AM_CONDITIONAL([ENABLE_GTK_DOC], [false])
+ AM_CONDITIONAL([GTK_DOC_BUILD_HTML], [false])
+ AM_CONDITIONAL([GTK_DOC_BUILD_PDF], [false])
+ AM_CONDITIONAL([GTK_DOC_USE_LIBTOOL], [false])
+ AM_CONDITIONAL([GTK_DOC_USE_REBASE], [false])
+ AC_PATH_PROGS([GTKDOC_REBASE],[true],[true])
+])
diff --git a/tools/missing-macros/src/m4/fake-intltool.m4 b/tools/missing-macros/src/m4/fake-intltool.m4
new file mode 100644
index 0000000..352053c
--- /dev/null
+++ b/tools/missing-macros/src/m4/fake-intltool.m4
@@ -0,0 +1,16 @@
+# stripped intltool.m4 to make automake happy
+# serial 1
+AC_DEFUN([IT_PROG_INTLTOOL],
+[
+ AC_SUBST(ALL_LINGUAS)
+
+ DATADIRNAME=share
+ AC_SUBST(DATADIRNAME)
+])
+
+# deprecated macros
+AU_ALIAS([AC_PROG_INTLTOOL], [IT_PROG_INTLTOOL])
+
+# A hint is needed for aclocal from Automake <= 1.9.4:
+# AC_DEFUN([AC_PROG_INTLTOOL], ...)
+
diff --git a/tools/missing-macros/src/m4/glibc2.m4 b/tools/missing-macros/src/m4/glibc2.m4
new file mode 100644
index 0000000..f148c12
--- /dev/null
+++ b/tools/missing-macros/src/m4/glibc2.m4
@@ -0,0 +1,30 @@
+# glibc2.m4 serial 2
+dnl Copyright (C) 2000-2002, 2004, 2008-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+# Test for the GNU C Library, version 2.0 or newer.
+# From Bruno Haible.
+
+AC_DEFUN([gt_GLIBC2],
+ [
+ AC_CACHE_CHECK([whether we are using the GNU C Library 2 or newer],
+ [ac_cv_gnu_library_2],
+ [AC_EGREP_CPP([Lucky GNU user],
+ [
+#include <features.h>
+#ifdef __GNU_LIBRARY__
+ #if (__GLIBC__ >= 2)
+ Lucky GNU user
+ #endif
+#endif
+ ],
+ [ac_cv_gnu_library_2=yes],
+ [ac_cv_gnu_library_2=no])
+ ]
+ )
+ AC_SUBST([GLIBC2])
+ GLIBC2="$ac_cv_gnu_library_2"
+ ]
+)
diff --git a/tools/missing-macros/src/m4/glibc21.m4 b/tools/missing-macros/src/m4/glibc21.m4
new file mode 100644
index 0000000..68ada9d
--- /dev/null
+++ b/tools/missing-macros/src/m4/glibc21.m4
@@ -0,0 +1,30 @@
+# glibc21.m4 serial 4
+dnl Copyright (C) 2000-2002, 2004, 2008-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+# Test for the GNU C Library, version 2.1 or newer.
+# From Bruno Haible.
+
+AC_DEFUN([gl_GLIBC21],
+ [
+ AC_CACHE_CHECK([whether we are using the GNU C Library 2.1 or newer],
+ [ac_cv_gnu_library_2_1],
+ [AC_EGREP_CPP([Lucky GNU user],
+ [
+#include <features.h>
+#ifdef __GNU_LIBRARY__
+ #if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)
+ Lucky GNU user
+ #endif
+#endif
+ ],
+ [ac_cv_gnu_library_2_1=yes],
+ [ac_cv_gnu_library_2_1=no])
+ ]
+ )
+ AC_SUBST([GLIBC21])
+ GLIBC21="$ac_cv_gnu_library_2_1"
+ ]
+)
diff --git a/tools/missing-macros/src/m4/intdiv0.m4 b/tools/missing-macros/src/m4/intdiv0.m4
new file mode 100644
index 0000000..289c4df
--- /dev/null
+++ b/tools/missing-macros/src/m4/intdiv0.m4
@@ -0,0 +1,84 @@
+# intdiv0.m4 serial 3 (gettext-0.18)
+dnl Copyright (C) 2002, 2007-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([gt_INTDIV0],
+[
+ AC_REQUIRE([AC_PROG_CC])dnl
+ AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+ AC_CACHE_CHECK([whether integer division by zero raises SIGFPE],
+ gt_cv_int_divbyzero_sigfpe,
+ [
+ gt_cv_int_divbyzero_sigfpe=
+changequote(,)dnl
+ case "$host_os" in
+ macos* | darwin[6-9]* | darwin[1-9][0-9]*)
+ # On MacOS X 10.2 or newer, just assume the same as when cross-
+ # compiling. If we were to perform the real test, 1 Crash Report
+ # dialog window would pop up.
+ case "$host_cpu" in
+ i[34567]86 | x86_64)
+ gt_cv_int_divbyzero_sigfpe="guessing yes" ;;
+ esac
+ ;;
+ esac
+changequote([,])dnl
+ if test -z "$gt_cv_int_divbyzero_sigfpe"; then
+ AC_TRY_RUN([
+#include <stdlib.h>
+#include <signal.h>
+
+static void
+sigfpe_handler (int sig)
+{
+ /* Exit with code 0 if SIGFPE, with code 1 if any other signal. */
+ exit (sig != SIGFPE);
+}
+
+int x = 1;
+int y = 0;
+int z;
+int nan;
+
+int main ()
+{
+ signal (SIGFPE, sigfpe_handler);
+/* IRIX and AIX (when "xlc -qcheck" is used) yield signal SIGTRAP. */
+#if (defined (__sgi) || defined (_AIX)) && defined (SIGTRAP)
+ signal (SIGTRAP, sigfpe_handler);
+#endif
+/* Linux/SPARC yields signal SIGILL. */
+#if defined (__sparc__) && defined (__linux__)
+ signal (SIGILL, sigfpe_handler);
+#endif
+
+ z = x / y;
+ nan = y / y;
+ exit (1);
+}
+], [gt_cv_int_divbyzero_sigfpe=yes], [gt_cv_int_divbyzero_sigfpe=no],
+ [
+ # Guess based on the CPU.
+changequote(,)dnl
+ case "$host_cpu" in
+ alpha* | i[34567]86 | x86_64 | m68k | s390*)
+ gt_cv_int_divbyzero_sigfpe="guessing yes";;
+ *)
+ gt_cv_int_divbyzero_sigfpe="guessing no";;
+ esac
+changequote([,])dnl
+ ])
+ fi
+ ])
+ case "$gt_cv_int_divbyzero_sigfpe" in
+ *yes) value=1;;
+ *) value=0;;
+ esac
+ AC_DEFINE_UNQUOTED([INTDIV0_RAISES_SIGFPE], [$value],
+ [Define if integer division by zero raises signal SIGFPE.])
+])
diff --git a/tools/missing-macros/src/m4/intmax.m4 b/tools/missing-macros/src/m4/intmax.m4
new file mode 100644
index 0000000..74aaaf5
--- /dev/null
+++ b/tools/missing-macros/src/m4/intmax.m4
@@ -0,0 +1,33 @@
+# intmax.m4 serial 5 (gettext-0.18)
+dnl Copyright (C) 2002-2005, 2008-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+dnl Test whether the system has the 'intmax_t' type, but don't attempt to
+dnl find a replacement if it is lacking.
+
+AC_DEFUN([gt_TYPE_INTMAX_T],
+[
+ AC_REQUIRE([gl_AC_HEADER_INTTYPES_H])
+ AC_REQUIRE([gl_AC_HEADER_STDINT_H])
+ AC_CACHE_CHECK([for intmax_t], [gt_cv_c_intmax_t],
+ [AC_TRY_COMPILE([
+#include <stddef.h>
+#include <stdlib.h>
+#if HAVE_STDINT_H_WITH_UINTMAX
+#include <stdint.h>
+#endif
+#if HAVE_INTTYPES_H_WITH_UINTMAX
+#include <inttypes.h>
+#endif
+], [intmax_t x = -1;
+ return !x;],
+ [gt_cv_c_intmax_t=yes],
+ [gt_cv_c_intmax_t=no])])
+ if test $gt_cv_c_intmax_t = yes; then
+ AC_DEFINE([HAVE_INTMAX_T], [1],
+ [Define if you have the 'intmax_t' type in <stdint.h> or <inttypes.h>.])
+ fi
+])
diff --git a/tools/missing-macros/src/m4/inttypes-pri.m4 b/tools/missing-macros/src/m4/inttypes-pri.m4
new file mode 100644
index 0000000..718a4f4
--- /dev/null
+++ b/tools/missing-macros/src/m4/inttypes-pri.m4
@@ -0,0 +1,36 @@
+# inttypes-pri.m4 serial 6 (gettext-0.18)
+dnl Copyright (C) 1997-2002, 2006, 2008-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.52])
+
+# Define PRI_MACROS_BROKEN if <inttypes.h> exists and defines the PRI*
+# macros to non-string values. This is the case on AIX 4.3.3.
+
+AC_DEFUN([gt_INTTYPES_PRI],
+[
+ AC_CHECK_HEADERS([inttypes.h])
+ if test $ac_cv_header_inttypes_h = yes; then
+ AC_CACHE_CHECK([whether the inttypes.h PRIxNN macros are broken],
+ [gt_cv_inttypes_pri_broken],
+ [
+ AC_TRY_COMPILE([#include <inttypes.h>
+#ifdef PRId32
+char *p = PRId32;
+#endif
+], [], [gt_cv_inttypes_pri_broken=no], [gt_cv_inttypes_pri_broken=yes])
+ ])
+ fi
+ if test "$gt_cv_inttypes_pri_broken" = yes; then
+ AC_DEFINE_UNQUOTED([PRI_MACROS_BROKEN], [1],
+ [Define if <inttypes.h> exists and defines unusable PRI* macros.])
+ PRI_MACROS_BROKEN=1
+ else
+ PRI_MACROS_BROKEN=0
+ fi
+ AC_SUBST([PRI_MACROS_BROKEN])
+])
diff --git a/tools/missing-macros/src/m4/mfx_acc.m4 b/tools/missing-macros/src/m4/mfx_acc.m4
new file mode 100644
index 0000000..9685cc3
--- /dev/null
+++ b/tools/missing-macros/src/m4/mfx_acc.m4
@@ -0,0 +1,163 @@
+# acc.m4 serial 1 (ucl-1.03)
+# /***********************************************************************
+# // standard ACC macros
+# ************************************************************************/
+
+AC_DEFUN([mfx_ACC_CHECK_ENDIAN], [
+AC_C_BIGENDIAN([AC_DEFINE(ACC_ABI_BIG_ENDIAN,1,[Define to 1 if your machine is big endian.])],[AC_DEFINE(ACC_ABI_LITTLE_ENDIAN,1,[Define to 1 if your machine is little endian.])])
+])#
+
+AC_DEFUN([mfx_ACC_CHECK_HEADERS], [
+AC_HEADER_TIME
+AC_CHECK_HEADERS([assert.h ctype.h dirent.h errno.h fcntl.h float.h limits.h malloc.h memory.h setjmp.h signal.h stdarg.h stddef.h stdint.h stdio.h stdlib.h string.h strings.h time.h unistd.h utime.h sys/mman.h sys/resource.h sys/stat.h sys/time.h sys/types.h sys/wait.h])
+])#
+
+AC_DEFUN([mfx_ACC_CHECK_FUNCS], [
+AC_CHECK_FUNCS(access alloca atexit atoi atol chmod chown clock_getcpuclockid clock_getres clock_gettime ctime difftime fstat getenv getpagesize getrusage gettimeofday gmtime isatty localtime longjmp lstat memcmp memcpy memmove memset mkdir mktime mmap mprotect munmap qsort raise rmdir setjmp signal snprintf strcasecmp strchr strdup strerror strftime stricmp strncasecmp strnicmp strrchr strstr time umask utime vsnprintf)
+])#
+
+
+AC_DEFUN([mfx_ACC_CHECK_SIZEOF], [
+AC_CHECK_SIZEOF(short)
+AC_CHECK_SIZEOF(int)
+AC_CHECK_SIZEOF(long)
+
+AC_CHECK_SIZEOF(long long)
+AC_CHECK_SIZEOF(__int16)
+AC_CHECK_SIZEOF(__int32)
+AC_CHECK_SIZEOF(__int64)
+
+AC_CHECK_SIZEOF(void *)
+AC_CHECK_SIZEOF(char *)
+AC_CHECK_SIZEOF(size_t)
+AC_CHECK_SIZEOF(ptrdiff_t)
+])#
+
+
+# /***********************************************************************
+# // Check for ACC_conformance
+# ************************************************************************/
+
+AC_DEFUN([mfx_ACC_ACCCHK], [
+mfx_tmp=$1
+mfx_save_CPPFLAGS=$CPPFLAGS
+dnl in Makefile.in $(INCLUDES) will be before $(CPPFLAGS), so we mimic this here
+test "X$mfx_tmp" = "X" || CPPFLAGS="$mfx_tmp $CPPFLAGS"
+
+AC_MSG_CHECKING([whether your compiler passes the ACC conformance test])
+
+AC_LANG_CONFTEST([AC_LANG_PROGRAM(
+[[#define ACC_CONFIG_NO_HEADER 1
+#include "acc/acc.h"
+#include "acc/acc_incd.h"
+#undef ACCCHK_ASSERT
+#define ACCCHK_ASSERT(expr) ACC_COMPILE_TIME_ASSERT_HEADER(expr)
+#include "acc/acc_chk.ch"
+#undef ACCCHK_ASSERT
+static void test_acc_compile_time_assert(void) {
+#define ACCCHK_ASSERT(expr) ACC_COMPILE_TIME_ASSERT(expr)
+#include "acc/acc_chk.ch"
+#undef ACCCHK_ASSERT
+}
+#undef NDEBUG
+#include <assert.h>
+static int test_acc_run_time_assert(int r) {
+#define ACCCHK_ASSERT(expr) assert(expr);
+#include "acc/acc_chk.ch"
+#undef ACCCHK_ASSERT
+return r;
+}
+]], [[
+test_acc_compile_time_assert();
+if (test_acc_run_time_assert(1) != 1) return 1;
+]]
+)])
+
+mfx_tmp=FAILED
+_AC_COMPILE_IFELSE([], [mfx_tmp=yes])
+rm -f conftest.$ac_ext conftest.$ac_objext
+
+CPPFLAGS=$mfx_save_CPPFLAGS
+
+AC_MSG_RESULT([$mfx_tmp])
+case x$mfx_tmp in
+ xpassed | xyes) ;;
+ *)
+ AC_MSG_NOTICE([])
+ AC_MSG_NOTICE([Your compiler failed the ACC conformance test - for details see ])
+ AC_MSG_NOTICE([`config.log'. Please check that log file and consider sending])
+ AC_MSG_NOTICE([a patch or bug-report to <${PACKAGE_BUGREPORT}>.])
+ AC_MSG_NOTICE([Thanks for your support.])
+ AC_MSG_NOTICE([])
+ AC_MSG_ERROR([ACC conformance test failed. Stop.])
+dnl AS_EXIT
+ ;;
+esac
+])# mfx_ACC_ACCCHK
+
+
+# /***********************************************************************
+# // Check for ACC_conformance
+# ************************************************************************/
+
+AC_DEFUN([mfx_MINIACC_ACCCHK], [
+mfx_tmp=$1
+mfx_save_CPPFLAGS=$CPPFLAGS
+dnl in Makefile.in $(INCLUDES) will be before $(CPPFLAGS), so we mimic this here
+test "X$mfx_tmp" = "X" || CPPFLAGS="$mfx_tmp $CPPFLAGS"
+
+AC_MSG_CHECKING([whether your compiler passes the ACC conformance test])
+
+AC_LANG_CONFTEST([AC_LANG_PROGRAM(
+[[#define ACC_CONFIG_NO_HEADER 1
+#define ACC_WANT_ACC_INCD_H 1
+#include $2
+
+#define ACC_WANT_ACC_CHK_CH 1
+#undef ACCCHK_ASSERT
+#define ACCCHK_ASSERT(expr) ACC_COMPILE_TIME_ASSERT_HEADER(expr)
+#include $2
+
+#define ACC_WANT_ACC_CHK_CH 1
+#undef ACCCHK_ASSERT
+#define ACCCHK_ASSERT(expr) ACC_COMPILE_TIME_ASSERT(expr)
+static void test_acc_compile_time_assert(void) {
+#include $2
+}
+
+#undef NDEBUG
+#include <assert.h>
+#define ACC_WANT_ACC_CHK_CH 1
+#undef ACCCHK_ASSERT
+#define ACCCHK_ASSERT(expr) assert(expr);
+static int test_acc_run_time_assert(int r) {
+#include $2
+return r;
+}
+]], [[
+test_acc_compile_time_assert();
+if (test_acc_run_time_assert(1) != 1) return 1;
+]]
+)])
+
+mfx_tmp=FAILED
+_AC_COMPILE_IFELSE([], [mfx_tmp=yes])
+rm -f conftest.$ac_ext conftest.$ac_objext
+
+CPPFLAGS=$mfx_save_CPPFLAGS
+
+AC_MSG_RESULT([$mfx_tmp])
+case x$mfx_tmp in
+ xpassed | xyes) ;;
+ *)
+ AC_MSG_NOTICE([])
+ AC_MSG_NOTICE([Your compiler failed the ACC conformance test - for details see ])
+ AC_MSG_NOTICE([`config.log'. Please check that log file and consider sending])
+ AC_MSG_NOTICE([a patch or bug-report to <${PACKAGE_BUGREPORT}>.])
+ AC_MSG_NOTICE([Thanks for your support.])
+ AC_MSG_NOTICE([])
+ AC_MSG_ERROR([ACC conformance test failed. Stop.])
+dnl AS_EXIT
+ ;;
+esac
+])# mfx_MINIACC_ACCCHK
diff --git a/tools/missing-macros/src/m4/mfx_cppflags.m4 b/tools/missing-macros/src/m4/mfx_cppflags.m4
new file mode 100644
index 0000000..0ad9141
--- /dev/null
+++ b/tools/missing-macros/src/m4/mfx_cppflags.m4
@@ -0,0 +1,41 @@
+# serial 1
+
+AC_DEFUN([mfx_PROG_CPPFLAGS], [
+AC_MSG_CHECKING([whether the C preprocessor needs special flags])
+
+AC_LANG_CONFTEST([AC_LANG_PROGRAM(
+[[#include <limits.h>
+#if (32767 >= 4294967295ul) || (65535u >= 4294967295ul)
+# include "your C preprocessor is broken 1"
+#elif (0xffffu == 0xfffffffful)
+# include "your C preprocessor is broken 2"
+#elif (32767 >= ULONG_MAX) || (65535u >= ULONG_MAX)
+# include "your C preprocessor is broken 3"
+#endif
+]], [[ ]]
+)])
+
+mfx_save_CPPFLAGS=$CPPFLAGS
+mfx_tmp=ERROR
+for mfx_arg in "" -no-cpp-precomp
+do
+ CPPFLAGS="$mfx_arg $mfx_save_CPPFLAGS"
+ _AC_COMPILE_IFELSE([],
+[mfx_tmp=$mfx_arg
+break])
+done
+CPPFLAGS=$mfx_save_CPPFLAGS
+rm -f conftest.$ac_ext conftest.$ac_objext
+case x$mfx_tmp in
+ x)
+ AC_MSG_RESULT([none needed]) ;;
+ xERROR)
+ AC_MSG_RESULT([ERROR])
+ AC_MSG_ERROR([your C preprocessor is broken - for details see config.log])
+ ;;
+ *)
+ AC_MSG_RESULT([$mfx_tmp])
+ CPPFLAGS="$mfx_tmp $CPPFLAGS"
+ ;;
+esac
+])# mfx_PROG_CPPFLAGS
diff --git a/tools/missing-macros/src/m4/mfx_limits.m4 b/tools/missing-macros/src/m4/mfx_limits.m4
new file mode 100644
index 0000000..b4e3ceb
--- /dev/null
+++ b/tools/missing-macros/src/m4/mfx_limits.m4
@@ -0,0 +1,152 @@
+# serial 3
+
+AC_DEFUN([mfx_CHECK_HEADER_SANE_LIMITS_H], [
+AC_CACHE_CHECK([whether limits.h is sane],
+mfx_cv_header_sane_limits_h,
+[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <limits.h>
+#if (32767 >= 4294967295ul) || (65535u >= 4294967295ul)
+# if defined(__APPLE__) && defined(__GNUC__)
+# error "your preprocessor is broken - use compiler option -no-cpp-precomp"
+# else
+# include "your preprocessor is broken"
+# endif
+#endif
+#define MFX_0xffff 0xffff
+#define MFX_0xffffffffL 4294967295ul
+#if !defined(CHAR_BIT) || (CHAR_BIT != 8)
+# include "error CHAR_BIT"
+#endif
+#if !defined(UCHAR_MAX)
+# include "error UCHAR_MAX 1"
+#endif
+#if !defined(USHRT_MAX)
+# include "error USHRT_MAX 1"
+#endif
+#if !defined(UINT_MAX)
+# include "error UINT_MAX 1"
+#endif
+#if !defined(ULONG_MAX)
+# include "error ULONG_MAX 1"
+#endif
+#if !defined(SHRT_MAX)
+# include "error SHRT_MAX 1"
+#endif
+#if !defined(INT_MAX)
+# include "error INT_MAX 1"
+#endif
+#if !defined(LONG_MAX)
+# include "error LONG_MAX 1"
+#endif
+#if (UCHAR_MAX < 1)
+# include "error UCHAR_MAX 2"
+#endif
+#if (USHRT_MAX < 1)
+# include "error USHRT_MAX 2"
+#endif
+#if (UINT_MAX < 1)
+# include "error UINT_MAX 2"
+#endif
+#if (ULONG_MAX < 1)
+# include "error ULONG_MAX 2"
+#endif
+#if (UCHAR_MAX < 0xff)
+# include "error UCHAR_MAX 3"
+#endif
+#if (USHRT_MAX < MFX_0xffff)
+# include "error USHRT_MAX 3"
+#endif
+#if (UINT_MAX < MFX_0xffff)
+# include "error UINT_MAX 3"
+#endif
+#if (ULONG_MAX < MFX_0xffffffffL)
+# include "error ULONG_MAX 3"
+#endif
+#if (USHRT_MAX > UINT_MAX)
+# include "error USHRT_MAX vs UINT_MAX"
+#endif
+#if (UINT_MAX > ULONG_MAX)
+# include "error UINT_MAX vs ULONG_MAX"
+#endif
+]], [[
+#if (USHRT_MAX == MFX_0xffff)
+{ typedef char a_short2a[1 - 2 * !(sizeof(short) == 2)]; }
+#elif (USHRT_MAX >= MFX_0xffff)
+{ typedef char a_short2b[1 - 2 * !(sizeof(short) > 2)]; }
+#endif
+#if (UINT_MAX == MFX_0xffff)
+{ typedef char a_int2a[1 - 2 * !(sizeof(int) == 2)]; }
+#elif (UINT_MAX >= MFX_0xffff)
+{ typedef char a_int2b[1 - 2 * !(sizeof(int) > 2)]; }
+#endif
+#if (ULONG_MAX == MFX_0xffff)
+{ typedef char a_long2a[1 - 2 * !(sizeof(long) == 2)]; }
+#elif (ULONG_MAX >= MFX_0xffff)
+{ typedef char a_long2b[1 - 2 * !(sizeof(long) > 2)]; }
+#endif
+#if !defined(_CRAY1) /* CRAY PVP systems */
+#if (USHRT_MAX == MFX_0xffffffffL)
+{ typedef char a_short4a[1 - 2 * !(sizeof(short) == 4)]; }
+#elif (USHRT_MAX >= MFX_0xffffffffL)
+{ typedef char a_short4b[1 - 2 * !(sizeof(short) > 4)]; }
+#endif
+#endif /* _CRAY1 */
+#if (UINT_MAX == MFX_0xffffffffL)
+{ typedef char a_int4a[1 - 2 * !(sizeof(int) == 4)]; }
+#elif (UINT_MAX >= MFX_0xffffffffL)
+{ typedef char a_int4b[1 - 2 * !(sizeof(int) > 4)]; }
+#endif
+#if (ULONG_MAX == MFX_0xffffffffL)
+{ typedef char a_long4a[1 - 2 * !(sizeof(long) == 4)]; }
+#elif (ULONG_MAX >= MFX_0xffffffffL)
+{ typedef char a_long4b[1 - 2 * !(sizeof(long) > 4)]; }
+#endif
+]])],
+[mfx_cv_header_sane_limits_h=yes],
+[mfx_cv_header_sane_limits_h=no])])
+])
+
+# /***********************************************************************
+# // standard
+# ************************************************************************/
+
+AC_DEFUN([mfx_LZO_CHECK_ENDIAN], [
+AC_C_BIGENDIAN([AC_DEFINE(LZO_ABI_BIG_ENDIAN,1,[Define to 1 if your machine is big endian.])],[AC_DEFINE(LZO_ABI_LITTLE_ENDIAN,1,[Define to 1 if your machine is little endian.])])
+])#
+
+
+# /***********************************************************************
+# //
+# ************************************************************************/
+
+dnl more types which are not yet covered by ACC
+
+AC_DEFUN([mfx_CHECK_SIZEOF], [
+AC_CHECK_SIZEOF(__int32)
+AC_CHECK_SIZEOF(intmax_t)
+AC_CHECK_SIZEOF(uintmax_t)
+AC_CHECK_SIZEOF(intptr_t)
+AC_CHECK_SIZEOF(uintptr_t)
+
+AC_CHECK_SIZEOF(float)
+AC_CHECK_SIZEOF(double)
+AC_CHECK_SIZEOF(long double)
+
+AC_CHECK_SIZEOF(dev_t)
+AC_CHECK_SIZEOF(fpos_t)
+AC_CHECK_SIZEOF(mode_t)
+AC_CHECK_SIZEOF(off_t)
+AC_CHECK_SIZEOF(ssize_t)
+AC_CHECK_SIZEOF(time_t)
+])#
+
+
+
+AC_DEFUN([mfx_CHECK_LIB_WINMM], [
+if test "X$GCC" = Xyes; then
+case $host_os in
+cygwin* | mingw* | pw32*)
+ test "X$LIBS" != "X" && LIBS="$LIBS "
+ LIBS="${LIBS}-lwinmm" ;;
+esac
+fi
+])#
diff --git a/tools/missing-macros/src/m4/uintmax_t.m4 b/tools/missing-macros/src/m4/uintmax_t.m4
new file mode 100644
index 0000000..03b51bc
--- /dev/null
+++ b/tools/missing-macros/src/m4/uintmax_t.m4
@@ -0,0 +1,30 @@
+# uintmax_t.m4 serial 12
+dnl Copyright (C) 1997-2004, 2007-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Paul Eggert.
+
+AC_PREREQ([2.13])
+
+# Define uintmax_t to 'unsigned long' or 'unsigned long long'
+# if it is not already defined in <stdint.h> or <inttypes.h>.
+
+AC_DEFUN([gl_AC_TYPE_UINTMAX_T],
+[
+ AC_REQUIRE([gl_AC_HEADER_INTTYPES_H])
+ AC_REQUIRE([gl_AC_HEADER_STDINT_H])
+ if test $gl_cv_header_inttypes_h = no && test $gl_cv_header_stdint_h = no; then
+ AC_REQUIRE([AC_TYPE_UNSIGNED_LONG_LONG_INT])
+ test $ac_cv_type_unsigned_long_long_int = yes \
+ && ac_type='unsigned long long' \
+ || ac_type='unsigned long'
+ AC_DEFINE_UNQUOTED([uintmax_t], [$ac_type],
+ [Define to unsigned long or unsigned long long
+ if <stdint.h> and <inttypes.h> don't define.])
+ else
+ AC_DEFINE([HAVE_UINTMAX_T], [1],
+ [Define if you have the 'uintmax_t' type in <stdint.h> or <inttypes.h>.])
+ fi
+])
diff --git a/tools/missing-macros/src/m4/va_copy.m4 b/tools/missing-macros/src/m4/va_copy.m4
new file mode 100644
index 0000000..0e88ee6
--- /dev/null
+++ b/tools/missing-macros/src/m4/va_copy.m4
@@ -0,0 +1,111 @@
+# va_copy.m4 serial 1 (js-1.6.20070208)
+
+dnl ##
+dnl ## Check for C99 va_copy() implementation
+dnl ## (and provide fallback implementation if neccessary)
+dnl ##
+dnl ## configure.in:
+dnl ## AC_CHECK_VA_COPY
+dnl ## foo.c:
+dnl ## #include "config.h"
+dnl ## [...]
+dnl ## va_copy(d,s)
+dnl ##
+dnl ## This check is rather complex: first because we really have to
+dnl ## try various possible implementations in sequence and second, we
+dnl ## cannot define a macro in config.h with parameters directly.
+dnl ##
+
+dnl # test program for va_copy() implementation
+changequote(<<,>>)
+m4_define(__va_copy_test, <<[
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#define DO_VA_COPY(d, s) $1
+void test(char *str, ...)
+{
+ va_list ap, ap2;
+ int i;
+ va_start(ap, str);
+ DO_VA_COPY(ap2, ap);
+ for (i = 1; i <= 9; i++) {
+ int k = (int)va_arg(ap, int);
+ if (k != i)
+ abort();
+ }
+ DO_VA_COPY(ap, ap2);
+ for (i = 1; i <= 9; i++) {
+ int k = (int)va_arg(ap, int);
+ if (k != i)
+ abort();
+ }
+ va_end(ap);
+}
+int main(int argc, char *argv[])
+{
+ test("test", 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ exit(0);
+}
+]>>)
+changequote([,])
+
+dnl # test driver for va_copy() implementation
+m4_define(__va_copy_check, [
+ AH_VERBATIM($1,
+[/* Predefined possible va_copy() implementation (id: $1) */
+#define __VA_COPY_USE_$1(d, s) $2])
+ if test ".$ac_cv_va_copy" = .; then
+ AC_TRY_RUN(__va_copy_test($2), [ac_cv_va_copy="$1"])
+ fi
+])
+
+dnl # Autoconf check for va_copy() implementation checking
+AC_DEFUN([AC_CHECK_VA_COPY],[
+ dnl # provide Autoconf display check message
+ AC_MSG_CHECKING(for va_copy() function)
+ dnl # check for various implementations in priorized sequence
+ AC_CACHE_VAL(ac_cv_va_copy, [
+ ac_cv_va_copy=""
+ dnl # 1. check for standardized C99 macro
+ __va_copy_check(C99, [va_copy((d), (s))])
+ dnl # 2. check for alternative/deprecated GCC macro
+ __va_copy_check(GCM, [VA_COPY((d), (s))])
+ dnl # 3. check for internal GCC macro (high-level define)
+ __va_copy_check(GCH, [__va_copy((d), (s))])
+ dnl # 4. check for internal GCC macro (built-in function)
+ __va_copy_check(GCB, [__builtin_va_copy((d), (s))])
+ dnl # 5. check for assignment approach (assuming va_list is a struct)
+ __va_copy_check(ASS, [do { (d) = (s); } while (0)])
+ dnl # 6. check for assignment approach (assuming va_list is a pointer)
+ __va_copy_check(ASP, [do { *(d) = *(s); } while (0)])
+ dnl # 7. check for memory copying approach (assuming va_list is a struct)
+ __va_copy_check(CPS, [memcpy((void *)&(d), (void *)&(s)), sizeof((s))])
+ dnl # 8. check for memory copying approach (assuming va_list is a pointer)
+ __va_copy_check(CPP, [memcpy((void *)(d), (void *)(s)), sizeof(*(s))])
+ if test ".$ac_cv_va_copy" = .; then
+ AC_ERROR([no working implementation found])
+ fi
+ ])
+ dnl # optionally activate the fallback implementation
+ if test ".$ac_cv_va_copy" = ".C99"; then
+ AC_DEFINE(HAVE_VA_COPY, 1, [Define if va_copy() macro exists (and no fallback implementation is required)])
+ fi
+ dnl # declare which fallback implementation to actually use
+ AC_DEFINE_UNQUOTED([__VA_COPY_USE], [__VA_COPY_USE_$ac_cv_va_copy],
+ [Define to id of used va_copy() implementation])
+ dnl # provide activation hook for fallback implementation
+ AH_VERBATIM([__VA_COPY_ACTIVATION],
+[/* Optional va_copy() implementation activation */
+#ifndef HAVE_VA_COPY
+#define va_copy(d, s) __VA_COPY_USE(d, s)
+#endif
+])
+ dnl # provide Autoconf display result message
+ if test ".$ac_cv_va_copy" = ".C99"; then
+ AC_MSG_RESULT([yes])
+ else
+ AC_MSG_RESULT([no (using fallback implementation)])
+ fi
+])
+
diff --git a/tools/mkimage/Makefile b/tools/mkimage/Makefile
new file mode 100644
index 0000000..0a1712b
--- /dev/null
+++ b/tools/mkimage/Makefile
@@ -0,0 +1,53 @@
+#
+# Copyright (C) 2006-2014 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mkimage
+PKG_VERSION:=2024.07
+
+PKG_SOURCE:=u-boot-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:= \
+ https://mirror.cyberbits.eu/u-boot \
+ https://ftp.denx.de/pub/u-boot \
+ ftp://ftp.denx.de/pub/u-boot
+PKG_HASH:=f591da9ab90ef3d6b3d173766d0ddff90c4ed7330680897486117df390d83c8f
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/u-boot-$(PKG_VERSION)
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+ $(MAKE) -C $(HOST_BUILD_DIR) \
+ HOSTCFLAGS="$(HOST_CFLAGS)" \
+ HOSTLDFLAGS="$(HOST_LDFLAGS)" \
+ PKG_CONFIG_EXTRAARGS="--static" \
+ V=$(if $(findstring c,$(OPENWRT_VERBOSE)),1) \
+ tools-only_config
+
+ sed -i 's/CONFIG_TOOLS_MKEFICAPSULE=y/# CONFIG_TOOLS_MKEFICAPSULE is not set/' $(HOST_BUILD_DIR)/.config
+endef
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR) \
+ HOSTCFLAGS="$(HOST_CFLAGS)" \
+ HOSTLDFLAGS="$(HOST_LDFLAGS)" \
+ PKG_CONFIG_EXTRAARGS="--static" \
+ V=$(if $(findstring c,$(OPENWRT_VERBOSE)),1) \
+ tools-only
+endef
+
+define Host/Install
+ $(CP) $(HOST_BUILD_DIR)/tools/mkimage $(STAGING_DIR_HOST)/bin/
+ $(CP) $(HOST_BUILD_DIR)/tools/mkenvimage $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/mkimage
+ rm -f $(STAGING_DIR_HOST)/bin/mkenvimage
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/mkimage/patches/030-allow-to-use-different-magic.patch b/tools/mkimage/patches/030-allow-to-use-different-magic.patch
new file mode 100644
index 0000000..bcbdc4d
--- /dev/null
+++ b/tools/mkimage/patches/030-allow-to-use-different-magic.patch
@@ -0,0 +1,80 @@
+This patch makes it possible to set a custom image magic.
+
+--- a/tools/mkimage.c
++++ b/tools/mkimage.c
+@@ -26,6 +26,7 @@ static struct image_tool_params params =
+ .arch = IH_ARCH_PPC,
+ .type = IH_TYPE_KERNEL,
+ .comp = IH_COMP_GZIP,
++ .magic = IH_MAGIC,
+ .dtc = MKIMAGE_DEFAULT_DTC_OPTIONS,
+ .imagename = "",
+ .imagename2 = "",
+@@ -89,11 +90,12 @@ static void usage(const char *msg)
+ " -q ==> quiet\n",
+ params.cmdname);
+ fprintf(stderr,
+- " %s [-x] -A arch -O os -T type -C comp -a addr -e ep -n name -d data_file[:data_file...] image\n"
++ " %s [-x] -A arch -O os -T type -C comp -M magic -a addr -e ep -n name -d data_file[:data_file...] image\n"
+ " -A ==> set architecture to 'arch'\n"
+ " -O ==> set operating system to 'os'\n"
+ " -T ==> set image type to 'type'\n"
+ " -C ==> set compression type 'comp'\n"
++ " -M ==> set image magic to 'magic'\n"
+ " -a ==> set load address to 'addr' (hex)\n"
+ " -e ==> set entry point to 'ep' (hex)\n"
+ " -n ==> set image name to 'name'\n"
+@@ -160,7 +162,7 @@ static int add_content(int type, const c
+ }
+
+ static const char optstring[] =
+- "a:A:b:B:c:C:d:D:e:Ef:Fg:G:i:k:K:ln:N:o:O:p:qrR:stT:vVx";
++ "a:A:b:B:c:C:d:D:e:Ef:Fg:G:i:k:K:lM:n:N:o:O:p:qrR:stT:vVx";
+
+ static const struct option longopts[] = {
+ { "load-address", required_argument, NULL, 'a' },
+@@ -303,6 +305,14 @@ static void process_args(int argc, char
+ case 'l':
+ params.lflag = 1;
+ break;
++ case 'M':
++ params.magic = strtoull(optarg, &ptr, 16);
++ if (*ptr) {
++ fprintf(stderr, "%s: invalid magic %s\n",
++ params.cmdname, optarg);
++ exit(EXIT_FAILURE);
++ }
++ break;
+ case 'n':
+ params.imagename = optarg;
+ break;
+--- a/tools/default_image.c
++++ b/tools/default_image.c
+@@ -67,7 +67,7 @@ static int image_verify_header(unsigned
+ */
+ memcpy(hdr, ptr, sizeof(struct legacy_img_hdr));
+
+- if (be32_to_cpu(hdr->ih_magic) != IH_MAGIC) {
++ if (be32_to_cpu(hdr->ih_magic) != params->magic) {
+ debug("%s: Bad Magic Number: \"%s\" is no valid image\n",
+ params->cmdname, params->imagefile);
+ return -FDT_ERR_BADMAGIC;
+@@ -146,7 +146,7 @@ static void image_set_header(void *ptr,
+ }
+
+ /* Build new header */
+- image_set_magic(hdr, IH_MAGIC);
++ image_set_magic(hdr, params->magic);
+ image_set_time(hdr, time);
+ image_set_size(hdr, imagesize);
+ image_set_load(hdr, addr);
+--- a/tools/imagetool.h
++++ b/tools/imagetool.h
+@@ -67,6 +67,7 @@ struct image_tool_params {
+ int arch;
+ int type;
+ int comp;
++ unsigned int magic;
+ char *dtc;
+ unsigned int addr;
+ unsigned int ep;
diff --git a/tools/mkimage/patches/050-Add-compatibility-with-non-Linux-hosts.patch b/tools/mkimage/patches/050-Add-compatibility-with-non-Linux-hosts.patch
new file mode 100644
index 0000000..7b71dce
--- /dev/null
+++ b/tools/mkimage/patches/050-Add-compatibility-with-non-Linux-hosts.patch
@@ -0,0 +1,65 @@
+From 590b23a46b7ae0f5ec5e8f57a85c0e7578c71141 Mon Sep 17 00:00:00 2001
+From: Hauke Mehrtens <hauke@hauke-m.de>
+Date: Sun, 26 Apr 2020 17:15:17 +0200
+Subject: [PATCH 1/2] Add compatibility with non Linux hosts
+
+This adds some changes to the u-boot tools to make it possible to build
+them on non Linux hosts like MacOS or FreeBSD.
+
+asm/byteorder.h, asm/posix_types.h, asm/types.h and linux/kernel.h are
+not available on such systems. Remove the include and add the necessary
+parts for these header files manually or remove the usage too.
+
+__u64 is not available on FreeBSD, remove its usage.
+
+Signed-off-by: Hauke Mehrtens <hauke@hauke-m.de>
+---
+ include/image.h | 2 ++
+ include/linux/posix_types.h | 2 ++
+ include/linux/types.h | 4 +++-
+ 3 files changed, 7 insertions(+), 1 deletion(-)
+
+--- a/include/image.h
++++ b/include/image.h
+@@ -16,7 +16,9 @@
+ #define __IMAGE_H__
+
+ #include "compiler.h"
++#ifdef linux
+ #include <asm/byteorder.h>
++#endif
+ #include <stdbool.h>
+
+ /* Define this to avoid #ifdefs later on */
+--- a/include/linux/posix_types.h
++++ b/include/linux/posix_types.h
+@@ -43,6 +43,8 @@ typedef void (*__kernel_sighandler_t)(in
+ /* Type of a SYSV IPC key. */
+ typedef int __kernel_key_t;
+
++#ifdef linux
+ #include <asm/posix_types.h>
++#endif
+
+ #endif /* _LINUX_POSIX_TYPES_H */
+--- a/include/linux/types.h
++++ b/include/linux/types.h
+@@ -2,7 +2,9 @@
+ #define _LINUX_TYPES_H
+
+ #include <linux/posix_types.h>
++#ifdef linux
+ #include <asm/types.h>
++#endif
+ #include <stdbool.h>
+
+ #ifndef __KERNEL_STRICT_NAMES
+@@ -142,7 +144,7 @@ typedef __u16 __bitwise __le16;
+ typedef __u16 __bitwise __be16;
+ typedef __u32 __bitwise __le32;
+ typedef __u32 __bitwise __be32;
+-#if defined(__GNUC__)
++#if defined(__GNUC__) && defined(linux)
+ typedef __u64 __bitwise __le64;
+ typedef __u64 __bitwise __be64;
+ #endif
diff --git a/tools/mkimage/patches/095-tools-disable-TOOLS_FIT_FULL_CHECK.patch b/tools/mkimage/patches/095-tools-disable-TOOLS_FIT_FULL_CHECK.patch
new file mode 100644
index 0000000..ed6824b
--- /dev/null
+++ b/tools/mkimage/patches/095-tools-disable-TOOLS_FIT_FULL_CHECK.patch
@@ -0,0 +1,25 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Huangbin Zhan <zhanhb88@gmail.com>
+Date: Fri, 18 Feb 2022 14:19:23 +0800
+Subject: [PATCH] tools: disable TOOLS_FIT_FULL_CHECK
+
+ U-Boot disallows unit addresses by default. Disable TOOLS_FIT_FULL_CHECK
+ to allow at symbol in node names.
+
+https://github.com/openwrt/openwrt/commits/master/scripts/mkits.sh
+https://github.com/u-boot/u-boot/commit/3f04db891a353f4b127ed57279279f851c6b4917
+---
+ tools/Kconfig | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+--- a/tools/Kconfig
++++ b/tools/Kconfig
+@@ -36,7 +36,7 @@ config TOOLS_FIT
+ Enable FIT support in the tools builds.
+
+ config TOOLS_FIT_FULL_CHECK
+- def_bool y
++ bool "Do a full check of the FIT"
+ help
+ Do a full check of the FIT before using it in the tools builds
+
diff --git a/tools/mklibs/Makefile b/tools/mklibs/Makefile
new file mode 100644
index 0000000..efa912b
--- /dev/null
+++ b/tools/mklibs/Makefile
@@ -0,0 +1,35 @@
+#
+# Copyright (C) 2009-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mklibs
+PKG_VERSION:=0.1.45
+
+PKG_SOURCE:=$(PKG_NAME)_$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@DEBIAN/pool/main/m/mklibs/
+PKG_HASH:=dd92a904b3942566f713fe536cd77dd1a5cfc62243c0e0bc6bb5d866e37422f3
+
+HOST_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CFLAGS += -I$(CURDIR)/include
+HOST_CPPFLAGS += -std=gnu++98
+
+define Host/Install
+ $(INSTALL_BIN) \
+ $(HOST_BUILD_DIR)/src/mklibs \
+ $(HOST_BUILD_DIR)/src/mklibs-copy \
+ $(HOST_BUILD_DIR)/src/mklibs-readelf/mklibs-readelf \
+ $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/mklibs*
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/mklibs/include/elf.h b/tools/mklibs/include/elf.h
new file mode 100644
index 0000000..d796350
--- /dev/null
+++ b/tools/mklibs/include/elf.h
@@ -0,0 +1,2559 @@
+/* This file defines standard ELF types, structures, and macros.
+ Copyright (C) 1995-2003, 2004 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+
+ The GNU C Library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ The GNU C Library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with the GNU C Library; if not, write to the Free
+ Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+ 02111-1307 USA. */
+
+#ifndef _ELF_H
+#define _ELF_H 1
+
+__BEGIN_DECLS
+
+/* Standard ELF types. */
+
+#include <stdint.h>
+
+/* Type for a 16-bit quantity. */
+typedef uint16_t Elf32_Half;
+typedef uint16_t Elf64_Half;
+
+/* Types for signed and unsigned 32-bit quantities. */
+typedef uint32_t Elf32_Word;
+typedef int32_t Elf32_Sword;
+typedef uint32_t Elf64_Word;
+typedef int32_t Elf64_Sword;
+
+/* Types for signed and unsigned 64-bit quantities. */
+typedef uint64_t Elf32_Xword;
+typedef int64_t Elf32_Sxword;
+typedef uint64_t Elf64_Xword;
+typedef int64_t Elf64_Sxword;
+
+/* Type of addresses. */
+typedef uint32_t Elf32_Addr;
+typedef uint64_t Elf64_Addr;
+
+/* Type of file offsets. */
+typedef uint32_t Elf32_Off;
+typedef uint64_t Elf64_Off;
+
+/* Type for section indices, which are 16-bit quantities. */
+typedef uint16_t Elf32_Section;
+typedef uint16_t Elf64_Section;
+
+/* Type for version symbol information. */
+typedef Elf32_Half Elf32_Versym;
+typedef Elf64_Half Elf64_Versym;
+
+
+/* The ELF file header. This appears at the start of every ELF file. */
+
+#define EI_NIDENT (16)
+
+typedef struct
+{
+ unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
+ Elf32_Half e_type; /* Object file type */
+ Elf32_Half e_machine; /* Architecture */
+ Elf32_Word e_version; /* Object file version */
+ Elf32_Addr e_entry; /* Entry point virtual address */
+ Elf32_Off e_phoff; /* Program header table file offset */
+ Elf32_Off e_shoff; /* Section header table file offset */
+ Elf32_Word e_flags; /* Processor-specific flags */
+ Elf32_Half e_ehsize; /* ELF header size in bytes */
+ Elf32_Half e_phentsize; /* Program header table entry size */
+ Elf32_Half e_phnum; /* Program header table entry count */
+ Elf32_Half e_shentsize; /* Section header table entry size */
+ Elf32_Half e_shnum; /* Section header table entry count */
+ Elf32_Half e_shstrndx; /* Section header string table index */
+} Elf32_Ehdr;
+
+typedef struct
+{
+ unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
+ Elf64_Half e_type; /* Object file type */
+ Elf64_Half e_machine; /* Architecture */
+ Elf64_Word e_version; /* Object file version */
+ Elf64_Addr e_entry; /* Entry point virtual address */
+ Elf64_Off e_phoff; /* Program header table file offset */
+ Elf64_Off e_shoff; /* Section header table file offset */
+ Elf64_Word e_flags; /* Processor-specific flags */
+ Elf64_Half e_ehsize; /* ELF header size in bytes */
+ Elf64_Half e_phentsize; /* Program header table entry size */
+ Elf64_Half e_phnum; /* Program header table entry count */
+ Elf64_Half e_shentsize; /* Section header table entry size */
+ Elf64_Half e_shnum; /* Section header table entry count */
+ Elf64_Half e_shstrndx; /* Section header string table index */
+} Elf64_Ehdr;
+
+/* Fields in the e_ident array. The EI_* macros are indices into the
+ array. The macros under each EI_* macro are the values the byte
+ may have. */
+
+#define EI_MAG0 0 /* File identification byte 0 index */
+#define ELFMAG0 0x7f /* Magic number byte 0 */
+
+#define EI_MAG1 1 /* File identification byte 1 index */
+#define ELFMAG1 'E' /* Magic number byte 1 */
+
+#define EI_MAG2 2 /* File identification byte 2 index */
+#define ELFMAG2 'L' /* Magic number byte 2 */
+
+#define EI_MAG3 3 /* File identification byte 3 index */
+#define ELFMAG3 'F' /* Magic number byte 3 */
+
+/* Conglomeration of the identification bytes, for easy testing as a word. */
+#define ELFMAG "\177ELF"
+#define SELFMAG 4
+
+#define EI_CLASS 4 /* File class byte index */
+#define ELFCLASSNONE 0 /* Invalid class */
+#define ELFCLASS32 1 /* 32-bit objects */
+#define ELFCLASS64 2 /* 64-bit objects */
+#define ELFCLASSNUM 3
+
+#define EI_DATA 5 /* Data encoding byte index */
+#define ELFDATANONE 0 /* Invalid data encoding */
+#define ELFDATA2LSB 1 /* 2's complement, little endian */
+#define ELFDATA2MSB 2 /* 2's complement, big endian */
+#define ELFDATANUM 3
+
+#define EI_VERSION 6 /* File version byte index */
+ /* Value must be EV_CURRENT */
+
+#define EI_OSABI 7 /* OS ABI identification */
+#define ELFOSABI_NONE 0 /* UNIX System V ABI */
+#define ELFOSABI_SYSV 0 /* Alias. */
+#define ELFOSABI_HPUX 1 /* HP-UX */
+#define ELFOSABI_NETBSD 2 /* NetBSD. */
+#define ELFOSABI_LINUX 3 /* Linux. */
+#define ELFOSABI_SOLARIS 6 /* Sun Solaris. */
+#define ELFOSABI_AIX 7 /* IBM AIX. */
+#define ELFOSABI_IRIX 8 /* SGI Irix. */
+#define ELFOSABI_FREEBSD 9 /* FreeBSD. */
+#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX. */
+#define ELFOSABI_MODESTO 11 /* Novell Modesto. */
+#define ELFOSABI_OPENBSD 12 /* OpenBSD. */
+#define ELFOSABI_ARM 97 /* ARM */
+#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */
+
+#define EI_ABIVERSION 8 /* ABI version */
+
+#define EI_PAD 9 /* Byte index of padding bytes */
+
+/* Legal values for e_type (object file type). */
+
+#define ET_NONE 0 /* No file type */
+#define ET_REL 1 /* Relocatable file */
+#define ET_EXEC 2 /* Executable file */
+#define ET_DYN 3 /* Shared object file */
+#define ET_CORE 4 /* Core file */
+#define ET_NUM 5 /* Number of defined types */
+#define ET_LOOS 0xfe00 /* OS-specific range start */
+#define ET_HIOS 0xfeff /* OS-specific range end */
+#define ET_LOPROC 0xff00 /* Processor-specific range start */
+#define ET_HIPROC 0xffff /* Processor-specific range end */
+
+/* Legal values for e_machine (architecture). */
+
+#define EM_NONE 0 /* No machine */
+#define EM_M32 1 /* AT&T WE 32100 */
+#define EM_SPARC 2 /* SUN SPARC */
+#define EM_386 3 /* Intel 80386 */
+#define EM_68K 4 /* Motorola m68k family */
+#define EM_88K 5 /* Motorola m88k family */
+#define EM_860 7 /* Intel 80860 */
+#define EM_MIPS 8 /* MIPS R3000 big-endian */
+#define EM_S370 9 /* IBM System/370 */
+#define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */
+
+#define EM_PARISC 15 /* HPPA */
+#define EM_VPP500 17 /* Fujitsu VPP500 */
+#define EM_SPARC32PLUS 18 /* Sun's "v8plus" */
+#define EM_960 19 /* Intel 80960 */
+#define EM_PPC 20 /* PowerPC */
+#define EM_PPC64 21 /* PowerPC 64-bit */
+#define EM_S390 22 /* IBM S390 */
+
+#define EM_V800 36 /* NEC V800 series */
+#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_FAKE_ALPHA 41 /* Digital Alpha */
+#define EM_SH 42 /* Hitachi SH */
+#define EM_SPARCV9 43 /* SPARC v9 64-bit */
+#define EM_TRICORE 44 /* Siemens Tricore */
+#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 Merced */
+#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 Multimedia Accelerator*/
+#define EM_PCP 55 /* Siemens PCP */
+#define EM_NCPU 56 /* Sony nCPU embeeded RISC */
+#define EM_NDR1 57 /* Denso NDR1 microprocessor */
+#define EM_STARCORE 58 /* Motorola Start*Core processor */
+#define EM_ME16 59 /* Toyota ME16 processor */
+#define EM_ST100 60 /* STMicroelectronic ST100 processor */
+#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/
+#define EM_X86_64 62 /* AMD x86-64 architecture */
+#define EM_PDSP 63 /* Sony DSP Processor */
+
+#define EM_FX66 66 /* Siemens FX66 microcontroller */
+#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */
+#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */
+#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 processor */
+#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_NUM 95
+
+/* If it is necessary to assign new unofficial EM_* values, please
+ pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
+ chances of collision with official or non-GNU unofficial values. */
+
+#define EM_ALPHA 0x9026
+
+/* Legal values for e_version (version). */
+
+#define EV_NONE 0 /* Invalid ELF version */
+#define EV_CURRENT 1 /* Current version */
+#define EV_NUM 2
+
+/* Section header. */
+
+typedef struct
+{
+ Elf32_Word sh_name; /* Section name (string tbl index) */
+ Elf32_Word sh_type; /* Section type */
+ Elf32_Word sh_flags; /* Section flags */
+ Elf32_Addr sh_addr; /* Section virtual addr at execution */
+ Elf32_Off sh_offset; /* Section file offset */
+ Elf32_Word sh_size; /* Section size in bytes */
+ Elf32_Word sh_link; /* Link to another section */
+ Elf32_Word sh_info; /* Additional section information */
+ Elf32_Word sh_addralign; /* Section alignment */
+ Elf32_Word sh_entsize; /* Entry size if section holds table */
+} Elf32_Shdr;
+
+typedef struct
+{
+ Elf64_Word sh_name; /* Section name (string tbl index) */
+ Elf64_Word sh_type; /* Section type */
+ Elf64_Xword sh_flags; /* Section flags */
+ Elf64_Addr sh_addr; /* Section virtual addr at execution */
+ Elf64_Off sh_offset; /* Section file offset */
+ Elf64_Xword sh_size; /* Section size in bytes */
+ Elf64_Word sh_link; /* Link to another section */
+ Elf64_Word sh_info; /* Additional section information */
+ Elf64_Xword sh_addralign; /* Section alignment */
+ Elf64_Xword sh_entsize; /* Entry size if section holds table */
+} Elf64_Shdr;
+
+/* Special section indices. */
+
+#define SHN_UNDEF 0 /* Undefined section */
+#define SHN_LORESERVE 0xff00 /* Start of reserved indices */
+#define SHN_LOPROC 0xff00 /* Start of processor-specific */
+#define SHN_BEFORE 0xff00 /* Order section before all others
+ (Solaris). */
+#define SHN_AFTER 0xff01 /* Order section after all others
+ (Solaris). */
+#define SHN_HIPROC 0xff1f /* End of processor-specific */
+#define SHN_LOOS 0xff20 /* Start of OS-specific */
+#define SHN_HIOS 0xff3f /* End of OS-specific */
+#define SHN_ABS 0xfff1 /* Associated symbol is absolute */
+#define SHN_COMMON 0xfff2 /* Associated symbol is common */
+#define SHN_XINDEX 0xffff /* Index is in extra table. */
+#define SHN_HIRESERVE 0xffff /* End of reserved indices */
+
+/* Legal values for sh_type (section type). */
+
+#define SHT_NULL 0 /* Section header table entry unused */
+#define SHT_PROGBITS 1 /* Program data */
+#define SHT_SYMTAB 2 /* Symbol table */
+#define SHT_STRTAB 3 /* String table */
+#define SHT_RELA 4 /* Relocation entries with addends */
+#define SHT_HASH 5 /* Symbol hash table */
+#define SHT_DYNAMIC 6 /* Dynamic linking information */
+#define SHT_NOTE 7 /* Notes */
+#define SHT_NOBITS 8 /* Program space with no data (bss) */
+#define SHT_REL 9 /* Relocation entries, no addends */
+#define SHT_SHLIB 10 /* Reserved */
+#define SHT_DYNSYM 11 /* Dynamic linker symbol table */
+#define SHT_INIT_ARRAY 14 /* Array of constructors */
+#define SHT_FINI_ARRAY 15 /* Array of destructors */
+#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */
+#define SHT_GROUP 17 /* Section group */
+#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */
+#define SHT_NUM 19 /* Number of defined types. */
+#define SHT_LOOS 0x60000000 /* Start OS-specific */
+#define SHT_GNU_LIBLIST 0x6ffffff7 /* Prelink library list */
+#define SHT_CHECKSUM 0x6ffffff8 /* Checksum for DSO content. */
+#define SHT_LOSUNW 0x6ffffffa /* Sun-specific low bound. */
+#define SHT_SUNW_move 0x6ffffffa
+#define SHT_SUNW_COMDAT 0x6ffffffb
+#define SHT_SUNW_syminfo 0x6ffffffc
+#define SHT_GNU_verdef 0x6ffffffd /* Version definition section. */
+#define SHT_GNU_verneed 0x6ffffffe /* Version needs section. */
+#define SHT_GNU_versym 0x6fffffff /* Version symbol table. */
+#define SHT_HISUNW 0x6fffffff /* Sun-specific high bound. */
+#define SHT_HIOS 0x6fffffff /* End OS-specific type */
+#define SHT_LOPROC 0x70000000 /* Start of processor-specific */
+#define SHT_HIPROC 0x7fffffff /* End of processor-specific */
+#define SHT_LOUSER 0x80000000 /* Start of application-specific */
+#define SHT_HIUSER 0x8fffffff /* End of application-specific */
+
+/* Legal values for sh_flags (section flags). */
+
+#define SHF_WRITE (1 << 0) /* Writable */
+#define SHF_ALLOC (1 << 1) /* Occupies memory during execution */
+#define SHF_EXECINSTR (1 << 2) /* Executable */
+#define SHF_MERGE (1 << 4) /* Might be merged */
+#define SHF_STRINGS (1 << 5) /* Contains nul-terminated strings */
+#define SHF_INFO_LINK (1 << 6) /* `sh_info' contains SHT index */
+#define SHF_LINK_ORDER (1 << 7) /* Preserve order after combining */
+#define SHF_OS_NONCONFORMING (1 << 8) /* Non-standard OS specific handling
+ required */
+#define SHF_GROUP (1 << 9) /* Section is member of a group. */
+#define SHF_TLS (1 << 10) /* Section hold thread-local data. */
+#define SHF_MASKOS 0x0ff00000 /* OS-specific. */
+#define SHF_MASKPROC 0xf0000000 /* Processor-specific */
+#define SHF_ORDERED (1 << 30) /* Special ordering requirement
+ (Solaris). */
+#define SHF_EXCLUDE (1 << 31) /* Section is excluded unless
+ referenced or allocated (Solaris).*/
+
+/* Section group handling. */
+#define GRP_COMDAT 0x1 /* Mark group as COMDAT. */
+
+/* Symbol table entry. */
+
+typedef struct
+{
+ Elf32_Word st_name; /* Symbol name (string tbl index) */
+ Elf32_Addr st_value; /* Symbol value */
+ Elf32_Word st_size; /* Symbol size */
+ unsigned char st_info; /* Symbol type and binding */
+ unsigned char st_other; /* Symbol visibility */
+ Elf32_Section st_shndx; /* Section index */
+} Elf32_Sym;
+
+typedef struct
+{
+ Elf64_Word st_name; /* Symbol name (string tbl index) */
+ unsigned char st_info; /* Symbol type and binding */
+ unsigned char st_other; /* Symbol visibility */
+ Elf64_Section st_shndx; /* Section index */
+ Elf64_Addr st_value; /* Symbol value */
+ Elf64_Xword st_size; /* Symbol size */
+} Elf64_Sym;
+
+/* The syminfo section if available contains additional information about
+ every dynamic symbol. */
+
+typedef struct
+{
+ Elf32_Half si_boundto; /* Direct bindings, symbol bound to */
+ Elf32_Half si_flags; /* Per symbol flags */
+} Elf32_Syminfo;
+
+typedef struct
+{
+ Elf64_Half si_boundto; /* Direct bindings, symbol bound to */
+ Elf64_Half si_flags; /* Per symbol flags */
+} Elf64_Syminfo;
+
+/* Possible values for si_boundto. */
+#define SYMINFO_BT_SELF 0xffff /* Symbol bound to self */
+#define SYMINFO_BT_PARENT 0xfffe /* Symbol bound to parent */
+#define SYMINFO_BT_LOWRESERVE 0xff00 /* Beginning of reserved entries */
+
+/* Possible bitmasks for si_flags. */
+#define SYMINFO_FLG_DIRECT 0x0001 /* Direct bound symbol */
+#define SYMINFO_FLG_PASSTHRU 0x0002 /* Pass-thru symbol for translator */
+#define SYMINFO_FLG_COPY 0x0004 /* Symbol is a copy-reloc */
+#define SYMINFO_FLG_LAZYLOAD 0x0008 /* Symbol bound to object to be lazy
+ loaded */
+/* Syminfo version values. */
+#define SYMINFO_NONE 0
+#define SYMINFO_CURRENT 1
+#define SYMINFO_NUM 2
+
+
+/* How to extract and insert information held in the st_info field. */
+
+#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4)
+#define ELF32_ST_TYPE(val) ((val) & 0xf)
+#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
+
+/* Both Elf32_Sym and Elf64_Sym use the same one-byte st_info field. */
+#define ELF64_ST_BIND(val) ELF32_ST_BIND (val)
+#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val)
+#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type))
+
+/* Legal values for ST_BIND subfield of st_info (symbol binding). */
+
+#define STB_LOCAL 0 /* Local symbol */
+#define STB_GLOBAL 1 /* Global symbol */
+#define STB_WEAK 2 /* Weak symbol */
+#define STB_NUM 3 /* Number of defined types. */
+#define STB_LOOS 10 /* Start of OS-specific */
+#define STB_HIOS 12 /* End of OS-specific */
+#define STB_LOPROC 13 /* Start of processor-specific */
+#define STB_HIPROC 15 /* End of processor-specific */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_NOTYPE 0 /* Symbol type is unspecified */
+#define STT_OBJECT 1 /* Symbol is a data object */
+#define STT_FUNC 2 /* Symbol is a code object */
+#define STT_SECTION 3 /* Symbol associated with a section */
+#define STT_FILE 4 /* Symbol's name is file name */
+#define STT_COMMON 5 /* Symbol is a common data object */
+#define STT_TLS 6 /* Symbol is thread-local data object*/
+#define STT_NUM 7 /* Number of defined types. */
+#define STT_LOOS 10 /* Start of OS-specific */
+#define STT_HIOS 12 /* End of OS-specific */
+#define STT_LOPROC 13 /* Start of processor-specific */
+#define STT_HIPROC 15 /* End of processor-specific */
+
+
+/* Symbol table indices are found in the hash buckets and chain table
+ of a symbol hash table section. This special index value indicates
+ the end of a chain, meaning no further symbols are found in that bucket. */
+
+#define STN_UNDEF 0 /* End of a chain. */
+
+
+/* How to extract and insert information held in the st_other field. */
+
+#define ELF32_ST_VISIBILITY(o) ((o) & 0x03)
+
+/* For ELF64 the definitions are the same. */
+#define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o)
+
+/* Symbol visibility specification encoded in the st_other field. */
+#define STV_DEFAULT 0 /* Default symbol visibility rules */
+#define STV_INTERNAL 1 /* Processor specific hidden class */
+#define STV_HIDDEN 2 /* Sym unavailable in other modules */
+#define STV_PROTECTED 3 /* Not preemptible, not exported */
+
+
+/* Relocation table entry without addend (in section of type SHT_REL). */
+
+typedef struct
+{
+ Elf32_Addr r_offset; /* Address */
+ Elf32_Word r_info; /* Relocation type and symbol index */
+} Elf32_Rel;
+
+/* I have seen two different definitions of the Elf64_Rel and
+ Elf64_Rela structures, so we'll leave them out until Novell (or
+ whoever) gets their act together. */
+/* The following, at least, is used on Sparc v9, MIPS, and Alpha. */
+
+typedef struct
+{
+ Elf64_Addr r_offset; /* Address */
+ Elf64_Xword r_info; /* Relocation type and symbol index */
+} Elf64_Rel;
+
+/* Relocation table entry with addend (in section of type SHT_RELA). */
+
+typedef struct
+{
+ Elf32_Addr r_offset; /* Address */
+ Elf32_Word r_info; /* Relocation type and symbol index */
+ Elf32_Sword r_addend; /* Addend */
+} Elf32_Rela;
+
+typedef struct
+{
+ Elf64_Addr r_offset; /* Address */
+ Elf64_Xword r_info; /* Relocation type and symbol index */
+ Elf64_Sxword r_addend; /* Addend */
+} Elf64_Rela;
+
+/* How to extract and insert information held in the r_info field. */
+
+#define ELF32_R_SYM(val) ((val) >> 8)
+#define ELF32_R_TYPE(val) ((val) & 0xff)
+#define ELF32_R_INFO(sym, type) (((sym) << 8) + ((type) & 0xff))
+
+#define ELF64_R_SYM(i) ((i) >> 32)
+#define ELF64_R_TYPE(i) ((i) & 0xffffffff)
+#define ELF64_R_INFO(sym,type) ((((Elf64_Xword) (sym)) << 32) + (type))
+
+/* Program segment header. */
+
+typedef struct
+{
+ Elf32_Word p_type; /* Segment type */
+ Elf32_Off p_offset; /* Segment file offset */
+ Elf32_Addr p_vaddr; /* Segment virtual address */
+ Elf32_Addr p_paddr; /* Segment physical address */
+ Elf32_Word p_filesz; /* Segment size in file */
+ Elf32_Word p_memsz; /* Segment size in memory */
+ Elf32_Word p_flags; /* Segment flags */
+ Elf32_Word p_align; /* Segment alignment */
+} Elf32_Phdr;
+
+typedef struct
+{
+ Elf64_Word p_type; /* Segment type */
+ Elf64_Word p_flags; /* Segment flags */
+ Elf64_Off p_offset; /* Segment file offset */
+ Elf64_Addr p_vaddr; /* Segment virtual address */
+ Elf64_Addr p_paddr; /* Segment physical address */
+ Elf64_Xword p_filesz; /* Segment size in file */
+ Elf64_Xword p_memsz; /* Segment size in memory */
+ Elf64_Xword p_align; /* Segment alignment */
+} Elf64_Phdr;
+
+/* Legal values for p_type (segment type). */
+
+#define PT_NULL 0 /* Program header table entry unused */
+#define PT_LOAD 1 /* Loadable program segment */
+#define PT_DYNAMIC 2 /* Dynamic linking information */
+#define PT_INTERP 3 /* Program interpreter */
+#define PT_NOTE 4 /* Auxiliary information */
+#define PT_SHLIB 5 /* Reserved */
+#define PT_PHDR 6 /* Entry for header table itself */
+#define PT_TLS 7 /* Thread-local storage segment */
+#define PT_NUM 8 /* Number of defined types */
+#define PT_LOOS 0x60000000 /* Start of OS-specific */
+#define PT_GNU_EH_FRAME 0x6474e550 /* GCC .eh_frame_hdr segment */
+#define PT_GNU_STACK 0x6474e551 /* Indicates stack executability */
+#define PT_GNU_RELRO 0x6474e552 /* Read-only after relocation */
+#define PT_LOSUNW 0x6ffffffa
+#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */
+#define PT_SUNWSTACK 0x6ffffffb /* Stack segment */
+#define PT_HISUNW 0x6fffffff
+#define PT_HIOS 0x6fffffff /* End of OS-specific */
+#define PT_LOPROC 0x70000000 /* Start of processor-specific */
+#define PT_HIPROC 0x7fffffff /* End of processor-specific */
+
+/* Legal values for p_flags (segment flags). */
+
+#define PF_X (1 << 0) /* Segment is executable */
+#define PF_W (1 << 1) /* Segment is writable */
+#define PF_R (1 << 2) /* Segment is readable */
+#define PF_MASKOS 0x0ff00000 /* OS-specific */
+#define PF_MASKPROC 0xf0000000 /* Processor-specific */
+
+/* Legal values for note segment descriptor types for core files. */
+
+#define NT_PRSTATUS 1 /* Contains copy of prstatus struct */
+#define NT_FPREGSET 2 /* Contains copy of fpregset struct */
+#define NT_PRPSINFO 3 /* Contains copy of prpsinfo struct */
+#define NT_PRXREG 4 /* Contains copy of prxregset struct */
+#define NT_TASKSTRUCT 4 /* Contains copy of task structure */
+#define NT_PLATFORM 5 /* String from sysinfo(SI_PLATFORM) */
+#define NT_AUXV 6 /* Contains copy of auxv array */
+#define NT_GWINDOWS 7 /* Contains copy of gwindows struct */
+#define NT_ASRS 8 /* Contains copy of asrset struct */
+#define NT_PSTATUS 10 /* Contains copy of pstatus struct */
+#define NT_PSINFO 13 /* Contains copy of psinfo struct */
+#define NT_PRCRED 14 /* Contains copy of prcred struct */
+#define NT_UTSNAME 15 /* Contains copy of utsname struct */
+#define NT_LWPSTATUS 16 /* Contains copy of lwpstatus struct */
+#define NT_LWPSINFO 17 /* Contains copy of lwpinfo struct */
+#define NT_PRFPXREG 20 /* Contains copy of fprxregset struct*/
+
+/* Legal values for the note segment descriptor types for object files. */
+
+#define NT_VERSION 1 /* Contains a version string. */
+
+
+/* Dynamic section entry. */
+
+typedef struct
+{
+ Elf32_Sword d_tag; /* Dynamic entry type */
+ union
+ {
+ Elf32_Word d_val; /* Integer value */
+ Elf32_Addr d_ptr; /* Address value */
+ } d_un;
+} Elf32_Dyn;
+
+typedef struct
+{
+ Elf64_Sxword d_tag; /* Dynamic entry type */
+ union
+ {
+ Elf64_Xword d_val; /* Integer value */
+ Elf64_Addr d_ptr; /* Address value */
+ } d_un;
+} Elf64_Dyn;
+
+/* Legal values for d_tag (dynamic entry type). */
+
+#define DT_NULL 0 /* Marks end of dynamic section */
+#define DT_NEEDED 1 /* Name of needed library */
+#define DT_PLTRELSZ 2 /* Size in bytes of PLT relocs */
+#define DT_PLTGOT 3 /* Processor defined value */
+#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 Rela relocs */
+#define DT_RELASZ 8 /* Total size of Rela relocs */
+#define DT_RELAENT 9 /* Size of one Rela reloc */
+#define DT_STRSZ 10 /* Size of string table */
+#define DT_SYMENT 11 /* Size of one symbol table entry */
+#define DT_INIT 12 /* Address of init function */
+#define DT_FINI 13 /* Address of termination function */
+#define DT_SONAME 14 /* Name of shared object */
+#define DT_RPATH 15 /* Library search path (deprecated) */
+#define DT_SYMBOLIC 16 /* Start symbol search here */
+#define DT_REL 17 /* Address of Rel relocs */
+#define DT_RELSZ 18 /* Total size of Rel relocs */
+#define DT_RELENT 19 /* Size of one Rel reloc */
+#define DT_PLTREL 20 /* Type of reloc in PLT */
+#define DT_DEBUG 21 /* For debugging; unspecified */
+#define DT_TEXTREL 22 /* Reloc might modify .text */
+#define DT_JMPREL 23 /* Address of PLT relocs */
+#define DT_BIND_NOW 24 /* Process relocations of object */
+#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */
+#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */
+#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */
+#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */
+#define DT_RUNPATH 29 /* Library search path */
+#define DT_FLAGS 30 /* Flags for the object being loaded */
+#define DT_ENCODING 32 /* Start of encoded range */
+#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/
+#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */
+#define DT_NUM 34 /* Number used */
+#define DT_LOOS 0x6000000d /* Start of OS-specific */
+#define DT_HIOS 0x6ffff000 /* End of OS-specific */
+#define DT_LOPROC 0x70000000 /* Start of processor-specific */
+#define DT_HIPROC 0x7fffffff /* End of processor-specific */
+#define DT_PROCNUM DT_MIPS_NUM /* Most used by any processor */
+
+/* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
+ Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's
+ approach. */
+#define DT_VALRNGLO 0x6ffffd00
+#define DT_GNU_PRELINKED 0x6ffffdf5 /* Prelinking timestamp */
+#define DT_GNU_CONFLICTSZ 0x6ffffdf6 /* Size of conflict section */
+#define DT_GNU_LIBLISTSZ 0x6ffffdf7 /* Size of library list */
+#define DT_CHECKSUM 0x6ffffdf8
+#define DT_PLTPADSZ 0x6ffffdf9
+#define DT_MOVEENT 0x6ffffdfa
+#define DT_MOVESZ 0x6ffffdfb
+#define DT_FEATURE_1 0x6ffffdfc /* Feature selection (DTF_*). */
+#define DT_POSFLAG_1 0x6ffffdfd /* Flags for DT_* entries, effecting
+ the following DT_* entry. */
+#define DT_SYMINSZ 0x6ffffdfe /* Size of syminfo table (in bytes) */
+#define DT_SYMINENT 0x6ffffdff /* Entry size of syminfo */
+#define DT_VALRNGHI 0x6ffffdff
+#define DT_VALTAGIDX(tag) (DT_VALRNGHI - (tag)) /* Reverse order! */
+#define DT_VALNUM 12
+
+/* 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_CONFLICT 0x6ffffef8 /* Start of conflict section */
+#define DT_GNU_LIBLIST 0x6ffffef9 /* Library list */
+#define DT_CONFIG 0x6ffffefa /* Configuration information. */
+#define DT_DEPAUDIT 0x6ffffefb /* Dependency auditing. */
+#define DT_AUDIT 0x6ffffefc /* Object auditing. */
+#define DT_PLTPAD 0x6ffffefd /* PLT padding. */
+#define DT_MOVETAB 0x6ffffefe /* Move table. */
+#define DT_SYMINFO 0x6ffffeff /* Syminfo table. */
+#define DT_ADDRRNGHI 0x6ffffeff
+#define DT_ADDRTAGIDX(tag) (DT_ADDRRNGHI - (tag)) /* Reverse order! */
+#define DT_ADDRNUM 10
+
+/* The versioning entry types. The next are defined as part of the
+ GNU extension. */
+#define DT_VERSYM 0x6ffffff0
+
+#define DT_RELACOUNT 0x6ffffff9
+#define DT_RELCOUNT 0x6ffffffa
+
+/* These were chosen by Sun. */
+#define DT_FLAGS_1 0x6ffffffb /* State flags, see DF_1_* below. */
+#define DT_VERDEF 0x6ffffffc /* Address of version definition
+ table */
+#define DT_VERDEFNUM 0x6ffffffd /* Number of version definitions */
+#define DT_VERNEED 0x6ffffffe /* Address of table with needed
+ versions */
+#define DT_VERNEEDNUM 0x6fffffff /* Number of needed versions */
+#define DT_VERSIONTAGIDX(tag) (DT_VERNEEDNUM - (tag)) /* Reverse order! */
+#define DT_VERSIONTAGNUM 16
+
+/* Sun added these machine-independent extensions in the "processor-specific"
+ range. Be compatible. */
+#define DT_AUXILIARY 0x7ffffffd /* Shared object to load before self */
+#define DT_FILTER 0x7fffffff /* Shared object to get values from */
+#define DT_EXTRATAGIDX(tag) ((Elf32_Word)-((Elf32_Sword) (tag) <<1>>1)-1)
+#define DT_EXTRANUM 3
+
+/* Values of `d_un.d_val' in the DT_FLAGS entry. */
+#define DF_ORIGIN 0x00000001 /* Object may use DF_ORIGIN */
+#define DF_SYMBOLIC 0x00000002 /* Symbol resolutions starts here */
+#define DF_TEXTREL 0x00000004 /* Object contains text relocations */
+#define DF_BIND_NOW 0x00000008 /* No lazy binding for this object */
+#define DF_STATIC_TLS 0x00000010 /* Module uses the static TLS model */
+
+/* State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1
+ entry in the dynamic section. */
+#define DF_1_NOW 0x00000001 /* Set RTLD_NOW for this object. */
+#define DF_1_GLOBAL 0x00000002 /* Set RTLD_GLOBAL for this object. */
+#define DF_1_GROUP 0x00000004 /* Set RTLD_GROUP for this object. */
+#define DF_1_NODELETE 0x00000008 /* Set RTLD_NODELETE for this object.*/
+#define DF_1_LOADFLTR 0x00000010 /* Trigger filtee loading at runtime.*/
+#define DF_1_INITFIRST 0x00000020 /* Set RTLD_INITFIRST for this object*/
+#define DF_1_NOOPEN 0x00000040 /* Set RTLD_NOOPEN for this object. */
+#define DF_1_ORIGIN 0x00000080 /* $ORIGIN must be handled. */
+#define DF_1_DIRECT 0x00000100 /* Direct binding enabled. */
+#define DF_1_TRANS 0x00000200
+#define DF_1_INTERPOSE 0x00000400 /* Object is used to interpose. */
+#define DF_1_NODEFLIB 0x00000800 /* Ignore default lib search path. */
+#define DF_1_NODUMP 0x00001000 /* Object can't be dldump'ed. */
+#define DF_1_CONFALT 0x00002000 /* Configuration alternative created.*/
+#define DF_1_ENDFILTEE 0x00004000 /* Filtee terminates filters search. */
+#define DF_1_DISPRELDNE 0x00008000 /* Disp reloc applied at build time. */
+#define DF_1_DISPRELPND 0x00010000 /* Disp reloc applied at run-time. */
+
+/* Flags for the feature selection in DT_FEATURE_1. */
+#define DTF_1_PARINIT 0x00000001
+#define DTF_1_CONFEXP 0x00000002
+
+/* Flags in the DT_POSFLAG_1 entry effecting only the next DT_* entry. */
+#define DF_P1_LAZYLOAD 0x00000001 /* Lazyload following object. */
+#define DF_P1_GROUPPERM 0x00000002 /* Symbols from next object are not
+ generally available. */
+
+/* Version definition sections. */
+
+typedef struct
+{
+ Elf32_Half vd_version; /* Version revision */
+ Elf32_Half vd_flags; /* Version information */
+ Elf32_Half vd_ndx; /* Version Index */
+ Elf32_Half vd_cnt; /* Number of associated aux entries */
+ Elf32_Word vd_hash; /* Version name hash value */
+ Elf32_Word vd_aux; /* Offset in bytes to verdaux array */
+ Elf32_Word vd_next; /* Offset in bytes to next verdef
+ entry */
+} Elf32_Verdef;
+
+typedef struct
+{
+ Elf64_Half vd_version; /* Version revision */
+ Elf64_Half vd_flags; /* Version information */
+ Elf64_Half vd_ndx; /* Version Index */
+ Elf64_Half vd_cnt; /* Number of associated aux entries */
+ Elf64_Word vd_hash; /* Version name hash value */
+ Elf64_Word vd_aux; /* Offset in bytes to verdaux array */
+ Elf64_Word vd_next; /* Offset in bytes to next verdef
+ entry */
+} Elf64_Verdef;
+
+
+/* Legal values for vd_version (version revision). */
+#define VER_DEF_NONE 0 /* No version */
+#define VER_DEF_CURRENT 1 /* Current version */
+#define VER_DEF_NUM 2 /* Given version number */
+
+/* Legal values for vd_flags (version information flags). */
+#define VER_FLG_BASE 0x1 /* Version definition of file itself */
+#define VER_FLG_WEAK 0x2 /* Weak version identifier */
+
+/* Versym symbol index values. */
+#define VER_NDX_LOCAL 0 /* Symbol is local. */
+#define VER_NDX_GLOBAL 1 /* Symbol is global. */
+#define VER_NDX_LORESERVE 0xff00 /* Beginning of reserved entries. */
+#define VER_NDX_ELIMINATE 0xff01 /* Symbol is to be eliminated. */
+
+/* Auxialiary version information. */
+
+typedef struct
+{
+ Elf32_Word vda_name; /* Version or dependency names */
+ Elf32_Word vda_next; /* Offset in bytes to next verdaux
+ entry */
+} Elf32_Verdaux;
+
+typedef struct
+{
+ Elf64_Word vda_name; /* Version or dependency names */
+ Elf64_Word vda_next; /* Offset in bytes to next verdaux
+ entry */
+} Elf64_Verdaux;
+
+
+/* Version dependency section. */
+
+typedef struct
+{
+ Elf32_Half vn_version; /* Version of structure */
+ Elf32_Half vn_cnt; /* Number of associated aux entries */
+ Elf32_Word vn_file; /* Offset of filename for this
+ dependency */
+ Elf32_Word vn_aux; /* Offset in bytes to vernaux array */
+ Elf32_Word vn_next; /* Offset in bytes to next verneed
+ entry */
+} Elf32_Verneed;
+
+typedef struct
+{
+ Elf64_Half vn_version; /* Version of structure */
+ Elf64_Half vn_cnt; /* Number of associated aux entries */
+ Elf64_Word vn_file; /* Offset of filename for this
+ dependency */
+ Elf64_Word vn_aux; /* Offset in bytes to vernaux array */
+ Elf64_Word vn_next; /* Offset in bytes to next verneed
+ entry */
+} Elf64_Verneed;
+
+
+/* Legal values for vn_version (version revision). */
+#define VER_NEED_NONE 0 /* No version */
+#define VER_NEED_CURRENT 1 /* Current version */
+#define VER_NEED_NUM 2 /* Given version number */
+
+/* Auxiliary needed version information. */
+
+typedef struct
+{
+ Elf32_Word vna_hash; /* Hash value of dependency name */
+ Elf32_Half vna_flags; /* Dependency specific information */
+ Elf32_Half vna_other; /* Unused */
+ Elf32_Word vna_name; /* Dependency name string offset */
+ Elf32_Word vna_next; /* Offset in bytes to next vernaux
+ entry */
+} Elf32_Vernaux;
+
+typedef struct
+{
+ Elf64_Word vna_hash; /* Hash value of dependency name */
+ Elf64_Half vna_flags; /* Dependency specific information */
+ Elf64_Half vna_other; /* Unused */
+ Elf64_Word vna_name; /* Dependency name string offset */
+ Elf64_Word vna_next; /* Offset in bytes to next vernaux
+ entry */
+} Elf64_Vernaux;
+
+
+/* Legal values for vna_flags. */
+#define VER_FLG_WEAK 0x2 /* Weak version identifier */
+
+
+/* Auxiliary vector. */
+
+/* This vector is normally only used by the program interpreter. The
+ usual definition in an ABI supplement uses the name auxv_t. The
+ vector is not usually defined in a standard <elf.h> file, but it
+ can't hurt. We rename it to avoid conflicts. The sizes of these
+ types are an arrangement between the exec server and the program
+ interpreter, so we don't fully specify them here. */
+
+typedef struct
+{
+ int a_type; /* Entry type */
+ union
+ {
+ long int a_val; /* Integer value */
+ void *a_ptr; /* Pointer value */
+ void (*a_fcn) (void); /* Function pointer value */
+ } a_un;
+} Elf32_auxv_t;
+
+typedef struct
+{
+ long int a_type; /* Entry type */
+ union
+ {
+ long int a_val; /* Integer value */
+ void *a_ptr; /* Pointer value */
+ void (*a_fcn) (void); /* Function pointer value */
+ } a_un;
+} Elf64_auxv_t;
+
+/* Legal values for a_type (entry type). */
+
+#define AT_NULL 0 /* End of vector */
+#define AT_IGNORE 1 /* Entry should be ignored */
+#define AT_EXECFD 2 /* File descriptor of program */
+#define AT_PHDR 3 /* Program headers for program */
+#define AT_PHENT 4 /* Size of program header entry */
+#define AT_PHNUM 5 /* Number of program headers */
+#define AT_PAGESZ 6 /* System page size */
+#define AT_BASE 7 /* Base address of interpreter */
+#define AT_FLAGS 8 /* Flags */
+#define AT_ENTRY 9 /* Entry point of program */
+#define AT_NOTELF 10 /* Program is not ELF */
+#define AT_UID 11 /* Real uid */
+#define AT_EUID 12 /* Effective uid */
+#define AT_GID 13 /* Real gid */
+#define AT_EGID 14 /* Effective gid */
+#define AT_CLKTCK 17 /* Frequency of times() */
+
+/* Some more special a_type values describing the hardware. */
+#define AT_PLATFORM 15 /* String identifying platform. */
+#define AT_HWCAP 16 /* Machine dependent hints about
+ processor capabilities. */
+
+/* This entry gives some information about the FPU initialization
+ performed by the kernel. */
+#define AT_FPUCW 18 /* Used FPU control word. */
+
+/* Cache block sizes. */
+#define AT_DCACHEBSIZE 19 /* Data cache block size. */
+#define AT_ICACHEBSIZE 20 /* Instruction cache block size. */
+#define AT_UCACHEBSIZE 21 /* Unified cache block size. */
+
+/* A special ignored value for PPC, used by the kernel to control the
+ interpretation of the AUXV. Must be > 16. */
+#define AT_IGNOREPPC 22 /* Entry should be ignored. */
+
+#define AT_SECURE 23 /* Boolean, was exec setuid-like? */
+
+/* Pointer to the global system page used for system calls and other
+ nice things. */
+#define AT_SYSINFO 32
+#define AT_SYSINFO_EHDR 33
+
+/* Shapes of the caches. Bits 0-3 contains associativity; bits 4-7 contains
+ log2 of line size; mask those to get cache size. */
+#define AT_L1I_CACHESHAPE 34
+#define AT_L1D_CACHESHAPE 35
+#define AT_L2_CACHESHAPE 36
+#define AT_L3_CACHESHAPE 37
+
+/* Note section contents. Each entry in the note section begins with
+ a header of a fixed form. */
+
+typedef struct
+{
+ Elf32_Word n_namesz; /* Length of the note's name. */
+ Elf32_Word n_descsz; /* Length of the note's descriptor. */
+ Elf32_Word n_type; /* Type of the note. */
+} Elf32_Nhdr;
+
+typedef struct
+{
+ Elf64_Word n_namesz; /* Length of the note's name. */
+ Elf64_Word n_descsz; /* Length of the note's descriptor. */
+ Elf64_Word n_type; /* Type of the note. */
+} Elf64_Nhdr;
+
+/* Known names of notes. */
+
+/* Solaris entries in the note section have this name. */
+#define ELF_NOTE_SOLARIS "SUNW Solaris"
+
+/* Note entries for GNU systems have this name. */
+#define ELF_NOTE_GNU "GNU"
+
+
+/* Defined types of notes for Solaris. */
+
+/* Value of descriptor (one word) is desired pagesize for the binary. */
+#define ELF_NOTE_PAGESIZE_HINT 1
+
+
+/* Defined note types for GNU systems. */
+
+/* ABI information. The descriptor consists of words:
+ word 0: OS descriptor
+ word 1: major version of the ABI
+ word 2: minor version of the ABI
+ word 3: subminor version of the ABI
+*/
+#define ELF_NOTE_ABI 1
+
+/* Known OSes. These value can appear in word 0 of an ELF_NOTE_ABI
+ note section entry. */
+#define ELF_NOTE_OS_LINUX 0
+#define ELF_NOTE_OS_GNU 1
+#define ELF_NOTE_OS_SOLARIS2 2
+#define ELF_NOTE_OS_FREEBSD 3
+
+
+/* Move records. */
+typedef struct
+{
+ Elf32_Xword m_value; /* Symbol value. */
+ Elf32_Word m_info; /* Size and index. */
+ Elf32_Word m_poffset; /* Symbol offset. */
+ Elf32_Half m_repeat; /* Repeat count. */
+ Elf32_Half m_stride; /* Stride info. */
+} Elf32_Move;
+
+typedef struct
+{
+ Elf64_Xword m_value; /* Symbol value. */
+ Elf64_Xword m_info; /* Size and index. */
+ Elf64_Xword m_poffset; /* Symbol offset. */
+ Elf64_Half m_repeat; /* Repeat count. */
+ Elf64_Half m_stride; /* Stride info. */
+} Elf64_Move;
+
+/* Macro to construct move records. */
+#define ELF32_M_SYM(info) ((info) >> 8)
+#define ELF32_M_SIZE(info) ((unsigned char) (info))
+#define ELF32_M_INFO(sym, size) (((sym) << 8) + (unsigned char) (size))
+
+#define ELF64_M_SYM(info) ELF32_M_SYM (info)
+#define ELF64_M_SIZE(info) ELF32_M_SIZE (info)
+#define ELF64_M_INFO(sym, size) ELF32_M_INFO (sym, size)
+
+
+/* Motorola 68k specific definitions. */
+
+/* Values for Elf32_Ehdr.e_flags. */
+#define EF_CPU32 0x00810000
+
+/* m68k relocs. */
+
+#define R_68K_NONE 0 /* No reloc */
+#define R_68K_32 1 /* Direct 32 bit */
+#define R_68K_16 2 /* Direct 16 bit */
+#define R_68K_8 3 /* Direct 8 bit */
+#define R_68K_PC32 4 /* PC relative 32 bit */
+#define R_68K_PC16 5 /* PC relative 16 bit */
+#define R_68K_PC8 6 /* PC relative 8 bit */
+#define R_68K_GOT32 7 /* 32 bit PC relative GOT entry */
+#define R_68K_GOT16 8 /* 16 bit PC relative GOT entry */
+#define R_68K_GOT8 9 /* 8 bit PC relative GOT entry */
+#define R_68K_GOT32O 10 /* 32 bit GOT offset */
+#define R_68K_GOT16O 11 /* 16 bit GOT offset */
+#define R_68K_GOT8O 12 /* 8 bit GOT offset */
+#define R_68K_PLT32 13 /* 32 bit PC relative PLT address */
+#define R_68K_PLT16 14 /* 16 bit PC relative PLT address */
+#define R_68K_PLT8 15 /* 8 bit PC relative PLT address */
+#define R_68K_PLT32O 16 /* 32 bit PLT offset */
+#define R_68K_PLT16O 17 /* 16 bit PLT offset */
+#define R_68K_PLT8O 18 /* 8 bit PLT offset */
+#define R_68K_COPY 19 /* Copy symbol at runtime */
+#define R_68K_GLOB_DAT 20 /* Create GOT entry */
+#define R_68K_JMP_SLOT 21 /* Create PLT entry */
+#define R_68K_RELATIVE 22 /* Adjust by program base */
+/* Keep this the last entry. */
+#define R_68K_NUM 23
+
+/* Intel 80386 specific definitions. */
+
+/* i386 relocs. */
+
+#define R_386_NONE 0 /* No reloc */
+#define R_386_32 1 /* Direct 32 bit */
+#define R_386_PC32 2 /* PC relative 32 bit */
+#define R_386_GOT32 3 /* 32 bit GOT entry */
+#define R_386_PLT32 4 /* 32 bit PLT address */
+#define R_386_COPY 5 /* Copy symbol at runtime */
+#define R_386_GLOB_DAT 6 /* Create GOT entry */
+#define R_386_JMP_SLOT 7 /* Create PLT entry */
+#define R_386_RELATIVE 8 /* Adjust by program base */
+#define R_386_GOTOFF 9 /* 32 bit offset to GOT */
+#define R_386_GOTPC 10 /* 32 bit PC relative offset to GOT */
+#define R_386_32PLT 11
+#define R_386_TLS_TPOFF 14 /* Offset in static TLS block */
+#define R_386_TLS_IE 15 /* Address of GOT entry for static TLS
+ block offset */
+#define R_386_TLS_GOTIE 16 /* GOT entry for static TLS block
+ offset */
+#define R_386_TLS_LE 17 /* Offset relative to static TLS
+ block */
+#define R_386_TLS_GD 18 /* Direct 32 bit for GNU version of
+ general dynamic thread local data */
+#define R_386_TLS_LDM 19 /* Direct 32 bit for GNU version of
+ local dynamic thread local data
+ in LE code */
+#define R_386_16 20
+#define R_386_PC16 21
+#define R_386_8 22
+#define R_386_PC8 23
+#define R_386_TLS_GD_32 24 /* Direct 32 bit for general dynamic
+ thread local data */
+#define R_386_TLS_GD_PUSH 25 /* Tag for pushl in GD TLS code */
+#define R_386_TLS_GD_CALL 26 /* Relocation for call to
+ __tls_get_addr() */
+#define R_386_TLS_GD_POP 27 /* Tag for popl in GD TLS code */
+#define R_386_TLS_LDM_32 28 /* Direct 32 bit for local dynamic
+ thread local data in LE code */
+#define R_386_TLS_LDM_PUSH 29 /* Tag for pushl in LDM TLS code */
+#define R_386_TLS_LDM_CALL 30 /* Relocation for call to
+ __tls_get_addr() in LDM code */
+#define R_386_TLS_LDM_POP 31 /* Tag for popl in LDM TLS code */
+#define R_386_TLS_LDO_32 32 /* Offset relative to TLS block */
+#define R_386_TLS_IE_32 33 /* GOT entry for negated static TLS
+ block offset */
+#define R_386_TLS_LE_32 34 /* Negated offset relative to static
+ TLS block */
+#define R_386_TLS_DTPMOD32 35 /* ID of module containing symbol */
+#define R_386_TLS_DTPOFF32 36 /* Offset in TLS block */
+#define R_386_TLS_TPOFF32 37 /* Negated offset in static TLS block */
+/* Keep this the last entry. */
+#define R_386_NUM 38
+
+/* SUN SPARC specific definitions. */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_SPARC_REGISTER 13 /* Global register reserved to app. */
+
+/* Values for Elf64_Ehdr.e_flags. */
+
+#define EF_SPARCV9_MM 3
+#define EF_SPARCV9_TSO 0
+#define EF_SPARCV9_PSO 1
+#define EF_SPARCV9_RMO 2
+#define EF_SPARC_LEDATA 0x800000 /* little endian data */
+#define EF_SPARC_EXT_MASK 0xFFFF00
+#define EF_SPARC_32PLUS 0x000100 /* generic V8+ features */
+#define EF_SPARC_SUN_US1 0x000200 /* Sun UltraSPARC1 extensions */
+#define EF_SPARC_HAL_R1 0x000400 /* HAL R1 extensions */
+#define EF_SPARC_SUN_US3 0x000800 /* Sun UltraSPARCIII extensions */
+
+/* SPARC relocs. */
+
+#define R_SPARC_NONE 0 /* No reloc */
+#define R_SPARC_8 1 /* Direct 8 bit */
+#define R_SPARC_16 2 /* Direct 16 bit */
+#define R_SPARC_32 3 /* Direct 32 bit */
+#define R_SPARC_DISP8 4 /* PC relative 8 bit */
+#define R_SPARC_DISP16 5 /* PC relative 16 bit */
+#define R_SPARC_DISP32 6 /* PC relative 32 bit */
+#define R_SPARC_WDISP30 7 /* PC relative 30 bit shifted */
+#define R_SPARC_WDISP22 8 /* PC relative 22 bit shifted */
+#define R_SPARC_HI22 9 /* High 22 bit */
+#define R_SPARC_22 10 /* Direct 22 bit */
+#define R_SPARC_13 11 /* Direct 13 bit */
+#define R_SPARC_LO10 12 /* Truncated 10 bit */
+#define R_SPARC_GOT10 13 /* Truncated 10 bit GOT entry */
+#define R_SPARC_GOT13 14 /* 13 bit GOT entry */
+#define R_SPARC_GOT22 15 /* 22 bit GOT entry shifted */
+#define R_SPARC_PC10 16 /* PC relative 10 bit truncated */
+#define R_SPARC_PC22 17 /* PC relative 22 bit shifted */
+#define R_SPARC_WPLT30 18 /* 30 bit PC relative PLT address */
+#define R_SPARC_COPY 19 /* Copy symbol at runtime */
+#define R_SPARC_GLOB_DAT 20 /* Create GOT entry */
+#define R_SPARC_JMP_SLOT 21 /* Create PLT entry */
+#define R_SPARC_RELATIVE 22 /* Adjust by program base */
+#define R_SPARC_UA32 23 /* Direct 32 bit unaligned */
+
+/* Additional Sparc64 relocs. */
+
+#define R_SPARC_PLT32 24 /* Direct 32 bit ref to PLT entry */
+#define R_SPARC_HIPLT22 25 /* High 22 bit PLT entry */
+#define R_SPARC_LOPLT10 26 /* Truncated 10 bit PLT entry */
+#define R_SPARC_PCPLT32 27 /* PC rel 32 bit ref to PLT entry */
+#define R_SPARC_PCPLT22 28 /* PC rel high 22 bit PLT entry */
+#define R_SPARC_PCPLT10 29 /* PC rel trunc 10 bit PLT entry */
+#define R_SPARC_10 30 /* Direct 10 bit */
+#define R_SPARC_11 31 /* Direct 11 bit */
+#define R_SPARC_64 32 /* Direct 64 bit */
+#define R_SPARC_OLO10 33 /* 10bit with secondary 13bit addend */
+#define R_SPARC_HH22 34 /* Top 22 bits of direct 64 bit */
+#define R_SPARC_HM10 35 /* High middle 10 bits of ... */
+#define R_SPARC_LM22 36 /* Low middle 22 bits of ... */
+#define R_SPARC_PC_HH22 37 /* Top 22 bits of pc rel 64 bit */
+#define R_SPARC_PC_HM10 38 /* High middle 10 bit of ... */
+#define R_SPARC_PC_LM22 39 /* Low miggle 22 bits of ... */
+#define R_SPARC_WDISP16 40 /* PC relative 16 bit shifted */
+#define R_SPARC_WDISP19 41 /* PC relative 19 bit shifted */
+#define R_SPARC_7 43 /* Direct 7 bit */
+#define R_SPARC_5 44 /* Direct 5 bit */
+#define R_SPARC_6 45 /* Direct 6 bit */
+#define R_SPARC_DISP64 46 /* PC relative 64 bit */
+#define R_SPARC_PLT64 47 /* Direct 64 bit ref to PLT entry */
+#define R_SPARC_HIX22 48 /* High 22 bit complemented */
+#define R_SPARC_LOX10 49 /* Truncated 11 bit complemented */
+#define R_SPARC_H44 50 /* Direct high 12 of 44 bit */
+#define R_SPARC_M44 51 /* Direct mid 22 of 44 bit */
+#define R_SPARC_L44 52 /* Direct low 10 of 44 bit */
+#define R_SPARC_REGISTER 53 /* Global register usage */
+#define R_SPARC_UA64 54 /* Direct 64 bit unaligned */
+#define R_SPARC_UA16 55 /* Direct 16 bit unaligned */
+#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
+/* Keep this the last entry. */
+#define R_SPARC_NUM 80
+
+/* For Sparc64, legal values for d_tag of Elf64_Dyn. */
+
+#define DT_SPARC_REGISTER 0x70000001
+#define DT_SPARC_NUM 2
+
+/* Bits present in AT_HWCAP, primarily for Sparc32. */
+
+#define HWCAP_SPARC_FLUSH 1 /* The cpu supports flush insn. */
+#define HWCAP_SPARC_STBAR 2
+#define HWCAP_SPARC_SWAP 4
+#define HWCAP_SPARC_MULDIV 8
+#define HWCAP_SPARC_V9 16 /* The cpu is v9, so v8plus is ok. */
+#define HWCAP_SPARC_ULTRA3 32
+
+/* MIPS R3000 specific definitions. */
+
+/* Legal values for e_flags field of Elf32_Ehdr. */
+
+#define EF_MIPS_NOREORDER 1 /* A .noreorder directive was used */
+#define EF_MIPS_PIC 2 /* Contains PIC code */
+#define EF_MIPS_CPIC 4 /* Uses PIC calling sequence */
+#define EF_MIPS_XGOT 8
+#define EF_MIPS_64BIT_WHIRL 16
+#define EF_MIPS_ABI2 32
+#define EF_MIPS_ABI_ON32 64
+#define EF_MIPS_ARCH 0xf0000000 /* MIPS architecture level */
+
+/* Legal values for MIPS architecture level. */
+
+#define EF_MIPS_ARCH_1 0x00000000 /* -mips1 code. */
+#define EF_MIPS_ARCH_2 0x10000000 /* -mips2 code. */
+#define EF_MIPS_ARCH_3 0x20000000 /* -mips3 code. */
+#define EF_MIPS_ARCH_4 0x30000000 /* -mips4 code. */
+#define EF_MIPS_ARCH_5 0x40000000 /* -mips5 code. */
+#define EF_MIPS_ARCH_32 0x60000000 /* MIPS32 code. */
+#define EF_MIPS_ARCH_64 0x70000000 /* MIPS64 code. */
+
+/* The following are non-official names and should not be used. */
+
+#define E_MIPS_ARCH_1 0x00000000 /* -mips1 code. */
+#define E_MIPS_ARCH_2 0x10000000 /* -mips2 code. */
+#define E_MIPS_ARCH_3 0x20000000 /* -mips3 code. */
+#define E_MIPS_ARCH_4 0x30000000 /* -mips4 code. */
+#define E_MIPS_ARCH_5 0x40000000 /* -mips5 code. */
+#define E_MIPS_ARCH_32 0x60000000 /* MIPS32 code. */
+#define E_MIPS_ARCH_64 0x70000000 /* MIPS64 code. */
+
+/* Special section indices. */
+
+#define SHN_MIPS_ACOMMON 0xff00 /* Allocated common symbols */
+#define SHN_MIPS_TEXT 0xff01 /* Allocated test symbols. */
+#define SHN_MIPS_DATA 0xff02 /* Allocated data symbols. */
+#define SHN_MIPS_SCOMMON 0xff03 /* Small common symbols */
+#define SHN_MIPS_SUNDEFINED 0xff04 /* Small undefined symbols */
+
+/* Legal values for sh_type field of Elf32_Shdr. */
+
+#define SHT_MIPS_LIBLIST 0x70000000 /* Shared objects used in link */
+#define SHT_MIPS_MSYM 0x70000001
+#define SHT_MIPS_CONFLICT 0x70000002 /* Conflicting symbols */
+#define SHT_MIPS_GPTAB 0x70000003 /* Global data area sizes */
+#define SHT_MIPS_UCODE 0x70000004 /* Reserved for SGI/MIPS compilers */
+#define SHT_MIPS_DEBUG 0x70000005 /* MIPS ECOFF debugging information*/
+#define SHT_MIPS_REGINFO 0x70000006 /* Register usage information */
+#define SHT_MIPS_PACKAGE 0x70000007
+#define SHT_MIPS_PACKSYM 0x70000008
+#define SHT_MIPS_RELD 0x70000009
+#define SHT_MIPS_IFACE 0x7000000b
+#define SHT_MIPS_CONTENT 0x7000000c
+#define SHT_MIPS_OPTIONS 0x7000000d /* Miscellaneous options. */
+#define SHT_MIPS_SHDR 0x70000010
+#define SHT_MIPS_FDESC 0x70000011
+#define SHT_MIPS_EXTSYM 0x70000012
+#define SHT_MIPS_DENSE 0x70000013
+#define SHT_MIPS_PDESC 0x70000014
+#define SHT_MIPS_LOCSYM 0x70000015
+#define SHT_MIPS_AUXSYM 0x70000016
+#define SHT_MIPS_OPTSYM 0x70000017
+#define SHT_MIPS_LOCSTR 0x70000018
+#define SHT_MIPS_LINE 0x70000019
+#define SHT_MIPS_RFDESC 0x7000001a
+#define SHT_MIPS_DELTASYM 0x7000001b
+#define SHT_MIPS_DELTAINST 0x7000001c
+#define SHT_MIPS_DELTACLASS 0x7000001d
+#define SHT_MIPS_DWARF 0x7000001e /* DWARF debugging information. */
+#define SHT_MIPS_DELTADECL 0x7000001f
+#define SHT_MIPS_SYMBOL_LIB 0x70000020
+#define SHT_MIPS_EVENTS 0x70000021 /* Event section. */
+#define SHT_MIPS_TRANSLATE 0x70000022
+#define SHT_MIPS_PIXIE 0x70000023
+#define SHT_MIPS_XLATE 0x70000024
+#define SHT_MIPS_XLATE_DEBUG 0x70000025
+#define SHT_MIPS_WHIRL 0x70000026
+#define SHT_MIPS_EH_REGION 0x70000027
+#define SHT_MIPS_XLATE_OLD 0x70000028
+#define SHT_MIPS_PDR_EXCEPTION 0x70000029
+
+/* Legal values for sh_flags field of Elf32_Shdr. */
+
+#define SHF_MIPS_GPREL 0x10000000 /* Must be part of global data area */
+#define SHF_MIPS_MERGE 0x20000000
+#define SHF_MIPS_ADDR 0x40000000
+#define SHF_MIPS_STRINGS 0x80000000
+#define SHF_MIPS_NOSTRIP 0x08000000
+#define SHF_MIPS_LOCAL 0x04000000
+#define SHF_MIPS_NAMES 0x02000000
+#define SHF_MIPS_NODUPE 0x01000000
+
+
+/* Symbol tables. */
+
+/* MIPS specific values for `st_other'. */
+#define STO_MIPS_DEFAULT 0x0
+#define STO_MIPS_INTERNAL 0x1
+#define STO_MIPS_HIDDEN 0x2
+#define STO_MIPS_PROTECTED 0x3
+#define STO_MIPS_SC_ALIGN_UNUSED 0xff
+
+/* MIPS specific values for `st_info'. */
+#define STB_MIPS_SPLIT_COMMON 13
+
+/* Entries found in sections of type SHT_MIPS_GPTAB. */
+
+typedef union
+{
+ struct
+ {
+ Elf32_Word gt_current_g_value; /* -G value used for compilation */
+ Elf32_Word gt_unused; /* Not used */
+ } gt_header; /* First entry in section */
+ struct
+ {
+ Elf32_Word gt_g_value; /* If this value were used for -G */
+ Elf32_Word gt_bytes; /* This many bytes would be used */
+ } gt_entry; /* Subsequent entries in section */
+} Elf32_gptab;
+
+/* Entry found in sections of type SHT_MIPS_REGINFO. */
+
+typedef struct
+{
+ Elf32_Word ri_gprmask; /* General registers used */
+ Elf32_Word ri_cprmask[4]; /* Coprocessor registers used */
+ Elf32_Sword ri_gp_value; /* $gp register value */
+} Elf32_RegInfo;
+
+/* Entries found in sections of type SHT_MIPS_OPTIONS. */
+
+typedef struct
+{
+ unsigned char kind; /* Determines interpretation of the
+ variable part of descriptor. */
+ unsigned char size; /* Size of descriptor, including header. */
+ Elf32_Section section; /* Section header index of section affected,
+ 0 for global options. */
+ Elf32_Word info; /* Kind-specific information. */
+} Elf_Options;
+
+/* Values for `kind' field in Elf_Options. */
+
+#define ODK_NULL 0 /* Undefined. */
+#define ODK_REGINFO 1 /* Register usage information. */
+#define ODK_EXCEPTIONS 2 /* Exception processing options. */
+#define ODK_PAD 3 /* Section padding options. */
+#define ODK_HWPATCH 4 /* Hardware workarounds performed */
+#define ODK_FILL 5 /* record the fill value used by the linker. */
+#define ODK_TAGS 6 /* reserve space for desktop tools to write. */
+#define ODK_HWAND 7 /* HW workarounds. 'AND' bits when merging. */
+#define ODK_HWOR 8 /* HW workarounds. 'OR' bits when merging. */
+
+/* Values for `info' in Elf_Options for ODK_EXCEPTIONS entries. */
+
+#define OEX_FPU_MIN 0x1f /* FPE's which MUST be enabled. */
+#define OEX_FPU_MAX 0x1f00 /* FPE's which MAY be enabled. */
+#define OEX_PAGE0 0x10000 /* page zero must be mapped. */
+#define OEX_SMM 0x20000 /* Force sequential memory mode? */
+#define OEX_FPDBUG 0x40000 /* Force floating point debug mode? */
+#define OEX_PRECISEFP OEX_FPDBUG
+#define OEX_DISMISS 0x80000 /* Dismiss invalid address faults? */
+
+#define OEX_FPU_INVAL 0x10
+#define OEX_FPU_DIV0 0x08
+#define OEX_FPU_OFLO 0x04
+#define OEX_FPU_UFLO 0x02
+#define OEX_FPU_INEX 0x01
+
+/* Masks for `info' in Elf_Options for an ODK_HWPATCH entry. */
+
+#define OHW_R4KEOP 0x1 /* R4000 end-of-page patch. */
+#define OHW_R8KPFETCH 0x2 /* may need R8000 prefetch patch. */
+#define OHW_R5KEOP 0x4 /* R5000 end-of-page patch. */
+#define OHW_R5KCVTL 0x8 /* R5000 cvt.[ds].l bug. clean=1. */
+
+#define OPAD_PREFIX 0x1
+#define OPAD_POSTFIX 0x2
+#define OPAD_SYMBOL 0x4
+
+/* Entry found in `.options' section. */
+
+typedef struct
+{
+ Elf32_Word hwp_flags1; /* Extra flags. */
+ Elf32_Word hwp_flags2; /* Extra flags. */
+} Elf_Options_Hw;
+
+/* Masks for `info' in ElfOptions for ODK_HWAND and ODK_HWOR entries. */
+
+#define OHWA0_R4KEOP_CHECKED 0x00000001
+#define OHWA1_R4KEOP_CLEAN 0x00000002
+
+/* MIPS relocs. */
+
+#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_SHIFT5 16
+#define R_MIPS_SHIFT6 17
+#define R_MIPS_64 18
+#define R_MIPS_GOT_DISP 19
+#define R_MIPS_GOT_PAGE 20
+#define R_MIPS_GOT_OFST 21
+#define R_MIPS_GOT_HI16 22
+#define R_MIPS_GOT_LO16 23
+#define R_MIPS_SUB 24
+#define R_MIPS_INSERT_A 25
+#define R_MIPS_INSERT_B 26
+#define R_MIPS_DELETE 27
+#define R_MIPS_HIGHER 28
+#define R_MIPS_HIGHEST 29
+#define R_MIPS_CALL_HI16 30
+#define R_MIPS_CALL_LO16 31
+#define R_MIPS_SCN_DISP 32
+#define R_MIPS_REL16 33
+#define R_MIPS_ADD_IMMEDIATE 34
+#define R_MIPS_PJUMP 35
+#define R_MIPS_RELGOT 36
+#define R_MIPS_JALR 37
+/* Keep this the last entry. */
+#define R_MIPS_NUM 38
+
+/* Legal values for p_type field of Elf32_Phdr. */
+
+#define PT_MIPS_REGINFO 0x70000000 /* Register usage information */
+#define PT_MIPS_RTPROC 0x70000001 /* Runtime procedure table. */
+#define PT_MIPS_OPTIONS 0x70000002
+
+/* Special program header types. */
+
+#define PF_MIPS_LOCAL 0x10000000
+
+/* Legal values for d_tag field of Elf32_Dyn. */
+
+#define DT_MIPS_RLD_VERSION 0x70000001 /* Runtime linker interface version */
+#define DT_MIPS_TIME_STAMP 0x70000002 /* Timestamp */
+#define DT_MIPS_ICHECKSUM 0x70000003 /* Checksum */
+#define DT_MIPS_IVERSION 0x70000004 /* Version string (string tbl index) */
+#define DT_MIPS_FLAGS 0x70000005 /* Flags */
+#define DT_MIPS_BASE_ADDRESS 0x70000006 /* Base address */
+#define DT_MIPS_MSYM 0x70000007
+#define DT_MIPS_CONFLICT 0x70000008 /* Address of CONFLICT section */
+#define DT_MIPS_LIBLIST 0x70000009 /* Address of LIBLIST section */
+#define DT_MIPS_LOCAL_GOTNO 0x7000000a /* Number of local GOT entries */
+#define DT_MIPS_CONFLICTNO 0x7000000b /* Number of CONFLICT entries */
+#define DT_MIPS_LIBLISTNO 0x70000010 /* Number of LIBLIST entries */
+#define DT_MIPS_SYMTABNO 0x70000011 /* Number of DYNSYM entries */
+#define DT_MIPS_UNREFEXTNO 0x70000012 /* First external DYNSYM */
+#define DT_MIPS_GOTSYM 0x70000013 /* First GOT entry in DYNSYM */
+#define DT_MIPS_HIPAGENO 0x70000014 /* Number of GOT page table entries */
+#define DT_MIPS_RLD_MAP 0x70000016 /* Address of run time loader map. */
+#define DT_MIPS_DELTA_CLASS 0x70000017 /* Delta C++ class definition. */
+#define DT_MIPS_DELTA_CLASS_NO 0x70000018 /* Number of entries in
+ DT_MIPS_DELTA_CLASS. */
+#define DT_MIPS_DELTA_INSTANCE 0x70000019 /* Delta C++ class instances. */
+#define DT_MIPS_DELTA_INSTANCE_NO 0x7000001a /* Number of entries in
+ DT_MIPS_DELTA_INSTANCE. */
+#define DT_MIPS_DELTA_RELOC 0x7000001b /* Delta relocations. */
+#define DT_MIPS_DELTA_RELOC_NO 0x7000001c /* Number of entries in
+ DT_MIPS_DELTA_RELOC. */
+#define DT_MIPS_DELTA_SYM 0x7000001d /* Delta symbols that Delta
+ relocations refer to. */
+#define DT_MIPS_DELTA_SYM_NO 0x7000001e /* Number of entries in
+ DT_MIPS_DELTA_SYM. */
+#define DT_MIPS_DELTA_CLASSSYM 0x70000020 /* Delta symbols that hold the
+ class declaration. */
+#define DT_MIPS_DELTA_CLASSSYM_NO 0x70000021 /* Number of entries in
+ DT_MIPS_DELTA_CLASSSYM. */
+#define DT_MIPS_CXX_FLAGS 0x70000022 /* Flags indicating for C++ flavor. */
+#define DT_MIPS_PIXIE_INIT 0x70000023
+#define DT_MIPS_SYMBOL_LIB 0x70000024
+#define DT_MIPS_LOCALPAGE_GOTIDX 0x70000025
+#define DT_MIPS_LOCAL_GOTIDX 0x70000026
+#define DT_MIPS_HIDDEN_GOTIDX 0x70000027
+#define DT_MIPS_PROTECTED_GOTIDX 0x70000028
+#define DT_MIPS_OPTIONS 0x70000029 /* Address of .options. */
+#define DT_MIPS_INTERFACE 0x7000002a /* Address of .interface. */
+#define DT_MIPS_DYNSTR_ALIGN 0x7000002b
+#define DT_MIPS_INTERFACE_SIZE 0x7000002c /* Size of the .interface section. */
+#define DT_MIPS_RLD_TEXT_RESOLVE_ADDR 0x7000002d /* Address of rld_text_rsolve
+ function stored in GOT. */
+#define DT_MIPS_PERF_SUFFIX 0x7000002e /* Default suffix of dso to be added
+ by rld on dlopen() calls. */
+#define DT_MIPS_COMPACT_SIZE 0x7000002f /* (O32)Size of compact rel section. */
+#define DT_MIPS_GP_VALUE 0x70000030 /* GP value for aux GOTs. */
+#define DT_MIPS_AUX_DYNAMIC 0x70000031 /* Address of aux .dynamic. */
+#define DT_MIPS_NUM 0x32
+
+/* Legal values for DT_MIPS_FLAGS Elf32_Dyn entry. */
+
+#define RHF_NONE 0 /* No flags */
+#define RHF_QUICKSTART (1 << 0) /* Use quickstart */
+#define RHF_NOTPOT (1 << 1) /* Hash size not power of 2 */
+#define RHF_NO_LIBRARY_REPLACEMENT (1 << 2) /* Ignore LD_LIBRARY_PATH */
+#define RHF_NO_MOVE (1 << 3)
+#define RHF_SGI_ONLY (1 << 4)
+#define RHF_GUARANTEE_INIT (1 << 5)
+#define RHF_DELTA_C_PLUS_PLUS (1 << 6)
+#define RHF_GUARANTEE_START_INIT (1 << 7)
+#define RHF_PIXIE (1 << 8)
+#define RHF_DEFAULT_DELAY_LOAD (1 << 9)
+#define RHF_REQUICKSTART (1 << 10)
+#define RHF_REQUICKSTARTED (1 << 11)
+#define RHF_CORD (1 << 12)
+#define RHF_NO_UNRES_UNDEF (1 << 13)
+#define RHF_RLD_ORDER_SAFE (1 << 14)
+
+/* Entries found in sections of type SHT_MIPS_LIBLIST. */
+
+typedef struct
+{
+ Elf32_Word l_name; /* Name (string table index) */
+ Elf32_Word l_time_stamp; /* Timestamp */
+ Elf32_Word l_checksum; /* Checksum */
+ Elf32_Word l_version; /* Interface version */
+ Elf32_Word l_flags; /* Flags */
+} Elf32_Lib;
+
+typedef struct
+{
+ Elf64_Word l_name; /* Name (string table index) */
+ Elf64_Word l_time_stamp; /* Timestamp */
+ Elf64_Word l_checksum; /* Checksum */
+ Elf64_Word l_version; /* Interface version */
+ Elf64_Word l_flags; /* Flags */
+} Elf64_Lib;
+
+
+/* Legal values for l_flags. */
+
+#define LL_NONE 0
+#define LL_EXACT_MATCH (1 << 0) /* Require exact match */
+#define LL_IGNORE_INT_VER (1 << 1) /* Ignore interface version */
+#define LL_REQUIRE_MINOR (1 << 2)
+#define LL_EXPORTS (1 << 3)
+#define LL_DELAY_LOAD (1 << 4)
+#define LL_DELTA (1 << 5)
+
+/* Entries found in sections of type SHT_MIPS_CONFLICT. */
+
+typedef Elf32_Addr Elf32_Conflict;
+
+
+/* HPPA specific definitions. */
+
+/* Legal values for e_flags field of Elf32_Ehdr. */
+
+#define EF_PARISC_TRAPNIL 0x00010000 /* Trap nil pointer dereference. */
+#define EF_PARISC_EXT 0x00020000 /* Program uses arch. extensions. */
+#define EF_PARISC_LSB 0x00040000 /* Program expects little endian. */
+#define EF_PARISC_WIDE 0x00080000 /* Program expects wide mode. */
+#define EF_PARISC_NO_KABP 0x00100000 /* No kernel assisted branch
+ prediction. */
+#define EF_PARISC_LAZYSWAP 0x00400000 /* Allow lazy swapping. */
+#define EF_PARISC_ARCH 0x0000ffff /* Architecture version. */
+
+/* Defined values for `e_flags & EF_PARISC_ARCH' are: */
+
+#define EFA_PARISC_1_0 0x020b /* PA-RISC 1.0 big-endian. */
+#define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */
+#define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */
+
+/* Additional section indeces. */
+
+#define SHN_PARISC_ANSI_COMMON 0xff00 /* Section for tenatively declared
+ symbols in ANSI C. */
+#define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */
+
+/* Legal values for sh_type field of Elf32_Shdr. */
+
+#define SHT_PARISC_EXT 0x70000000 /* Contains product specific ext. */
+#define SHT_PARISC_UNWIND 0x70000001 /* Unwind information. */
+#define SHT_PARISC_DOC 0x70000002 /* Debug info for optimized code. */
+
+/* Legal values for sh_flags field of Elf32_Shdr. */
+
+#define SHF_PARISC_SHORT 0x20000000 /* Section with short addressing. */
+#define SHF_PARISC_HUGE 0x40000000 /* Section far from gp. */
+#define SHF_PARISC_SBP 0x80000000 /* Static branch prediction code. */
+
+/* Legal values for ST_TYPE subfield of st_info (symbol type). */
+
+#define STT_PARISC_MILLICODE 13 /* Millicode function entry point. */
+
+#define STT_HP_OPAQUE (STT_LOOS + 0x1)
+#define STT_HP_STUB (STT_LOOS + 0x2)
+
+/* HPPA relocs. */
+
+#define R_PARISC_NONE 0 /* No reloc. */
+#define R_PARISC_DIR32 1 /* Direct 32-bit reference. */
+#define R_PARISC_DIR21L 2 /* Left 21 bits of eff. address. */
+#define R_PARISC_DIR17R 3 /* Right 17 bits of eff. address. */
+#define R_PARISC_DIR17F 4 /* 17 bits of eff. address. */
+#define R_PARISC_DIR14R 6 /* Right 14 bits of eff. address. */
+#define R_PARISC_PCREL32 9 /* 32-bit rel. address. */
+#define R_PARISC_PCREL21L 10 /* Left 21 bits of rel. address. */
+#define R_PARISC_PCREL17R 11 /* Right 17 bits of rel. address. */
+#define R_PARISC_PCREL17F 12 /* 17 bits of rel. address. */
+#define R_PARISC_PCREL14R 14 /* Right 14 bits of rel. address. */
+#define R_PARISC_DPREL21L 18 /* Left 21 bits of rel. address. */
+#define R_PARISC_DPREL14R 22 /* Right 14 bits of rel. address. */
+#define R_PARISC_GPREL21L 26 /* GP-relative, left 21 bits. */
+#define R_PARISC_GPREL14R 30 /* GP-relative, right 14 bits. */
+#define R_PARISC_LTOFF21L 34 /* LT-relative, left 21 bits. */
+#define R_PARISC_LTOFF14R 38 /* LT-relative, right 14 bits. */
+#define R_PARISC_SECREL32 41 /* 32 bits section rel. address. */
+#define R_PARISC_SEGBASE 48 /* No relocation, set segment base. */
+#define R_PARISC_SEGREL32 49 /* 32 bits segment rel. address. */
+#define R_PARISC_PLTOFF21L 50 /* PLT rel. address, left 21 bits. */
+#define R_PARISC_PLTOFF14R 54 /* PLT rel. address, right 14 bits. */
+#define R_PARISC_LTOFF_FPTR32 57 /* 32 bits LT-rel. function pointer. */
+#define R_PARISC_LTOFF_FPTR21L 58 /* LT-rel. fct ptr, left 21 bits. */
+#define R_PARISC_LTOFF_FPTR14R 62 /* LT-rel. fct ptr, right 14 bits. */
+#define R_PARISC_FPTR64 64 /* 64 bits function address. */
+#define R_PARISC_PLABEL32 65 /* 32 bits function address. */
+#define R_PARISC_PLABEL21L 66 /* Left 21 bits of fct ptr. */
+#define R_PARISC_PLABEL14R 70 /* Left 21 bits of fct ptr. */
+#define R_PARISC_PCREL64 72 /* 64 bits PC-rel. address. */
+#define R_PARISC_PCREL22F 74 /* 22 bits PC-rel. address. */
+#define R_PARISC_PCREL14WR 75 /* PC-rel. address, right 14 bits. */
+#define R_PARISC_PCREL14DR 76 /* PC rel. address, right 14 bits. */
+#define R_PARISC_PCREL16F 77 /* 16 bits PC-rel. address. */
+#define R_PARISC_PCREL16WF 78 /* 16 bits PC-rel. address. */
+#define R_PARISC_PCREL16DF 79 /* 16 bits PC-rel. address. */
+#define R_PARISC_DIR64 80 /* 64 bits of eff. address. */
+#define R_PARISC_DIR14WR 83 /* 14 bits of eff. address. */
+#define R_PARISC_DIR14DR 84 /* 14 bits of eff. address. */
+#define R_PARISC_DIR16F 85 /* 16 bits of eff. address. */
+#define R_PARISC_DIR16WF 86 /* 16 bits of eff. address. */
+#define R_PARISC_DIR16DF 87 /* 16 bits of eff. address. */
+#define R_PARISC_GPREL64 88 /* 64 bits of GP-rel. address. */
+#define R_PARISC_GPREL14WR 91 /* GP-rel. address, right 14 bits. */
+#define R_PARISC_GPREL14DR 92 /* GP-rel. address, right 14 bits. */
+#define R_PARISC_GPREL16F 93 /* 16 bits GP-rel. address. */
+#define R_PARISC_GPREL16WF 94 /* 16 bits GP-rel. address. */
+#define R_PARISC_GPREL16DF 95 /* 16 bits GP-rel. address. */
+#define R_PARISC_LTOFF64 96 /* 64 bits LT-rel. address. */
+#define R_PARISC_LTOFF14WR 99 /* LT-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF14DR 100 /* LT-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF16F 101 /* 16 bits LT-rel. address. */
+#define R_PARISC_LTOFF16WF 102 /* 16 bits LT-rel. address. */
+#define R_PARISC_LTOFF16DF 103 /* 16 bits LT-rel. address. */
+#define R_PARISC_SECREL64 104 /* 64 bits section rel. address. */
+#define R_PARISC_SEGREL64 112 /* 64 bits segment rel. address. */
+#define R_PARISC_PLTOFF14WR 115 /* PLT-rel. address, right 14 bits. */
+#define R_PARISC_PLTOFF14DR 116 /* PLT-rel. address, right 14 bits. */
+#define R_PARISC_PLTOFF16F 117 /* 16 bits LT-rel. address. */
+#define R_PARISC_PLTOFF16WF 118 /* 16 bits PLT-rel. address. */
+#define R_PARISC_PLTOFF16DF 119 /* 16 bits PLT-rel. address. */
+#define R_PARISC_LTOFF_FPTR64 120 /* 64 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR14WR 123 /* LT-rel. fct. ptr., right 14 bits. */
+#define R_PARISC_LTOFF_FPTR14DR 124 /* LT-rel. fct. ptr., right 14 bits. */
+#define R_PARISC_LTOFF_FPTR16F 125 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR16WF 126 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LTOFF_FPTR16DF 127 /* 16 bits LT-rel. function ptr. */
+#define R_PARISC_LORESERVE 128
+#define R_PARISC_COPY 128 /* Copy relocation. */
+#define R_PARISC_IPLT 129 /* Dynamic reloc, imported PLT */
+#define R_PARISC_EPLT 130 /* Dynamic reloc, exported PLT */
+#define R_PARISC_TPREL32 153 /* 32 bits TP-rel. address. */
+#define R_PARISC_TPREL21L 154 /* TP-rel. address, left 21 bits. */
+#define R_PARISC_TPREL14R 158 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_LTOFF_TP21L 162 /* LT-TP-rel. address, left 21 bits. */
+#define R_PARISC_LTOFF_TP14R 166 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP14F 167 /* 14 bits LT-TP-rel. address. */
+#define R_PARISC_TPREL64 216 /* 64 bits TP-rel. address. */
+#define R_PARISC_TPREL14WR 219 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_TPREL14DR 220 /* TP-rel. address, right 14 bits. */
+#define R_PARISC_TPREL16F 221 /* 16 bits TP-rel. address. */
+#define R_PARISC_TPREL16WF 222 /* 16 bits TP-rel. address. */
+#define R_PARISC_TPREL16DF 223 /* 16 bits TP-rel. address. */
+#define R_PARISC_LTOFF_TP64 224 /* 64 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP14WR 227 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP14DR 228 /* LT-TP-rel. address, right 14 bits.*/
+#define R_PARISC_LTOFF_TP16F 229 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP16WF 230 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_LTOFF_TP16DF 231 /* 16 bits LT-TP-rel. address. */
+#define R_PARISC_HIRESERVE 255
+
+/* Legal values for p_type field of Elf32_Phdr/Elf64_Phdr. */
+
+#define PT_HP_TLS (PT_LOOS + 0x0)
+#define PT_HP_CORE_NONE (PT_LOOS + 0x1)
+#define PT_HP_CORE_VERSION (PT_LOOS + 0x2)
+#define PT_HP_CORE_KERNEL (PT_LOOS + 0x3)
+#define PT_HP_CORE_COMM (PT_LOOS + 0x4)
+#define PT_HP_CORE_PROC (PT_LOOS + 0x5)
+#define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6)
+#define PT_HP_CORE_STACK (PT_LOOS + 0x7)
+#define PT_HP_CORE_SHM (PT_LOOS + 0x8)
+#define PT_HP_CORE_MMF (PT_LOOS + 0x9)
+#define PT_HP_PARALLEL (PT_LOOS + 0x10)
+#define PT_HP_FASTBIND (PT_LOOS + 0x11)
+#define PT_HP_OPT_ANNOT (PT_LOOS + 0x12)
+#define PT_HP_HSL_ANNOT (PT_LOOS + 0x13)
+#define PT_HP_STACK (PT_LOOS + 0x14)
+
+#define PT_PARISC_ARCHEXT 0x70000000
+#define PT_PARISC_UNWIND 0x70000001
+
+/* Legal values for p_flags field of Elf32_Phdr/Elf64_Phdr. */
+
+#define PF_PARISC_SBP 0x08000000
+
+#define PF_HP_PAGE_SIZE 0x00100000
+#define PF_HP_FAR_SHARED 0x00200000
+#define PF_HP_NEAR_SHARED 0x00400000
+#define PF_HP_CODE 0x01000000
+#define PF_HP_MODIFY 0x02000000
+#define PF_HP_LAZYSWAP 0x04000000
+#define PF_HP_SBP 0x08000000
+
+
+/* Alpha specific definitions. */
+
+/* Legal values for e_flags field of Elf64_Ehdr. */
+
+#define EF_ALPHA_32BIT 1 /* All addresses must be < 2GB. */
+#define EF_ALPHA_CANRELAX 2 /* Relocations for relaxing exist. */
+
+/* Legal values for sh_type field of Elf64_Shdr. */
+
+/* These two are primerily concerned with ECOFF debugging info. */
+#define SHT_ALPHA_DEBUG 0x70000001
+#define SHT_ALPHA_REGINFO 0x70000002
+
+/* Legal values for sh_flags field of Elf64_Shdr. */
+
+#define SHF_ALPHA_GPREL 0x10000000
+
+/* Legal values for st_other field of Elf64_Sym. */
+#define STO_ALPHA_NOPV 0x80 /* No PV required. */
+#define STO_ALPHA_STD_GPLOAD 0x88 /* PV only used for initial ldgp. */
+
+/* Alpha relocs. */
+
+#define R_ALPHA_NONE 0 /* No reloc */
+#define R_ALPHA_REFLONG 1 /* Direct 32 bit */
+#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */
+#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */
+#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */
+#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */
+#define R_ALPHA_GPDISP 6 /* Add displacement to GP */
+#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */
+#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */
+#define R_ALPHA_SREL16 9 /* PC relative 16 bit */
+#define R_ALPHA_SREL32 10 /* PC relative 32 bit */
+#define R_ALPHA_SREL64 11 /* PC relative 64 bit */
+#define R_ALPHA_GPRELHIGH 17 /* GP relative 32 bit, high 16 bits */
+#define R_ALPHA_GPRELLOW 18 /* GP relative 32 bit, low 16 bits */
+#define R_ALPHA_GPREL16 19 /* GP relative 16 bit */
+#define R_ALPHA_COPY 24 /* Copy symbol at runtime */
+#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */
+#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */
+#define R_ALPHA_RELATIVE 27 /* Adjust by program base */
+#define R_ALPHA_TLS_GD_HI 28
+#define R_ALPHA_TLSGD 29
+#define R_ALPHA_TLS_LDM 30
+#define R_ALPHA_DTPMOD64 31
+#define R_ALPHA_GOTDTPREL 32
+#define R_ALPHA_DTPREL64 33
+#define R_ALPHA_DTPRELHI 34
+#define R_ALPHA_DTPRELLO 35
+#define R_ALPHA_DTPREL16 36
+#define R_ALPHA_GOTTPREL 37
+#define R_ALPHA_TPREL64 38
+#define R_ALPHA_TPRELHI 39
+#define R_ALPHA_TPRELLO 40
+#define R_ALPHA_TPREL16 41
+/* Keep this the last entry. */
+#define R_ALPHA_NUM 46
+
+/* Magic values of the LITUSE relocation addend. */
+#define LITUSE_ALPHA_ADDR 0
+#define LITUSE_ALPHA_BASE 1
+#define LITUSE_ALPHA_BYTOFF 2
+#define LITUSE_ALPHA_JSR 3
+#define LITUSE_ALPHA_TLS_GD 4
+#define LITUSE_ALPHA_TLS_LDM 5
+
+
+/* PowerPC specific declarations */
+
+/* Values for Elf32/64_Ehdr.e_flags. */
+#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */
+
+/* Cygnus local bits below */
+#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/
+#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib
+ flag */
+
+/* PowerPC relocations defined by the ABIs */
+#define R_PPC_NONE 0
+#define R_PPC_ADDR32 1 /* 32bit absolute address */
+#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */
+#define R_PPC_ADDR16 3 /* 16bit absolute address */
+#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */
+#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */
+#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */
+#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */
+#define R_PPC_ADDR14_BRTAKEN 8
+#define R_PPC_ADDR14_BRNTAKEN 9
+#define R_PPC_REL24 10 /* PC relative 26 bit */
+#define R_PPC_REL14 11 /* PC relative 16 bit */
+#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
+
+/* PowerPC relocations defined for the TLS access ABI. */
+#define R_PPC_TLS 67 /* none (sym+add)@tls */
+#define R_PPC_DTPMOD32 68 /* word32 (sym+add)@dtpmod */
+#define R_PPC_TPREL16 69 /* half16* (sym+add)@tprel */
+#define R_PPC_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */
+#define R_PPC_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */
+#define R_PPC_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */
+#define R_PPC_TPREL32 73 /* word32 (sym+add)@tprel */
+#define R_PPC_DTPREL16 74 /* half16* (sym+add)@dtprel */
+#define R_PPC_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */
+#define R_PPC_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */
+#define R_PPC_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */
+#define R_PPC_DTPREL32 78 /* word32 (sym+add)@dtprel */
+#define R_PPC_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */
+#define R_PPC_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */
+#define R_PPC_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */
+#define R_PPC_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */
+#define R_PPC_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */
+#define R_PPC_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */
+#define R_PPC_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */
+#define R_PPC_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */
+#define R_PPC_GOT_TPREL16 87 /* half16* (sym+add)@got@tprel */
+#define R_PPC_GOT_TPREL16_LO 88 /* half16 (sym+add)@got@tprel@l */
+#define R_PPC_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */
+#define R_PPC_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */
+#define R_PPC_GOT_DTPREL16 91 /* half16* (sym+add)@got@dtprel */
+#define R_PPC_GOT_DTPREL16_LO 92 /* half16* (sym+add)@got@dtprel@l */
+#define R_PPC_GOT_DTPREL16_HI 93 /* half16* (sym+add)@got@dtprel@h */
+#define R_PPC_GOT_DTPREL16_HA 94 /* half16* (sym+add)@got@dtprel@ha */
+
+/* Keep this the last entry. */
+#define R_PPC_NUM 95
+
+/* 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 /* 16 bit offset in SDA */
+#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 /* 16 bit relative offset in SDA */
+
+/* Diab tool relocations. */
+#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */
+#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */
+#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */
+#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */
+#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */
+#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */
+
+/* This is a phony reloc to handle any old fashioned TOC16 references
+ that may still be in object files. */
+#define R_PPC_TOC16 255
+
+
+/* PowerPC64 relocations defined by the ABIs */
+#define R_PPC64_NONE R_PPC_NONE
+#define R_PPC64_ADDR32 R_PPC_ADDR32 /* 32bit absolute address */
+#define R_PPC64_ADDR24 R_PPC_ADDR24 /* 26bit address, word aligned */
+#define R_PPC64_ADDR16 R_PPC_ADDR16 /* 16bit absolute address */
+#define R_PPC64_ADDR16_LO R_PPC_ADDR16_LO /* lower 16bits of address */
+#define R_PPC64_ADDR16_HI R_PPC_ADDR16_HI /* high 16bits of address. */
+#define R_PPC64_ADDR16_HA R_PPC_ADDR16_HA /* adjusted high 16bits. */
+#define R_PPC64_ADDR14 R_PPC_ADDR14 /* 16bit address, word aligned */
+#define R_PPC64_ADDR14_BRTAKEN R_PPC_ADDR14_BRTAKEN
+#define R_PPC64_ADDR14_BRNTAKEN R_PPC_ADDR14_BRNTAKEN
+#define R_PPC64_REL24 R_PPC_REL24 /* PC-rel. 26 bit, word aligned */
+#define R_PPC64_REL14 R_PPC_REL14 /* PC relative 16 bit */
+#define R_PPC64_REL14_BRTAKEN R_PPC_REL14_BRTAKEN
+#define R_PPC64_REL14_BRNTAKEN R_PPC_REL14_BRNTAKEN
+#define R_PPC64_GOT16 R_PPC_GOT16
+#define R_PPC64_GOT16_LO R_PPC_GOT16_LO
+#define R_PPC64_GOT16_HI R_PPC_GOT16_HI
+#define R_PPC64_GOT16_HA R_PPC_GOT16_HA
+
+#define R_PPC64_COPY R_PPC_COPY
+#define R_PPC64_GLOB_DAT R_PPC_GLOB_DAT
+#define R_PPC64_JMP_SLOT R_PPC_JMP_SLOT
+#define R_PPC64_RELATIVE R_PPC_RELATIVE
+
+#define R_PPC64_UADDR32 R_PPC_UADDR32
+#define R_PPC64_UADDR16 R_PPC_UADDR16
+#define R_PPC64_REL32 R_PPC_REL32
+#define R_PPC64_PLT32 R_PPC_PLT32
+#define R_PPC64_PLTREL32 R_PPC_PLTREL32
+#define R_PPC64_PLT16_LO R_PPC_PLT16_LO
+#define R_PPC64_PLT16_HI R_PPC_PLT16_HI
+#define R_PPC64_PLT16_HA R_PPC_PLT16_HA
+
+#define R_PPC64_SECTOFF R_PPC_SECTOFF
+#define R_PPC64_SECTOFF_LO R_PPC_SECTOFF_LO
+#define R_PPC64_SECTOFF_HI R_PPC_SECTOFF_HI
+#define R_PPC64_SECTOFF_HA R_PPC_SECTOFF_HA
+#define R_PPC64_ADDR30 37 /* word30 (S + A - P) >> 2 */
+#define R_PPC64_ADDR64 38 /* doubleword64 S + A */
+#define R_PPC64_ADDR16_HIGHER 39 /* half16 #higher(S + A) */
+#define R_PPC64_ADDR16_HIGHERA 40 /* half16 #highera(S + A) */
+#define R_PPC64_ADDR16_HIGHEST 41 /* half16 #highest(S + A) */
+#define R_PPC64_ADDR16_HIGHESTA 42 /* half16 #highesta(S + A) */
+#define R_PPC64_UADDR64 43 /* doubleword64 S + A */
+#define R_PPC64_REL64 44 /* doubleword64 S + A - P */
+#define R_PPC64_PLT64 45 /* doubleword64 L + A */
+#define R_PPC64_PLTREL64 46 /* doubleword64 L + A - P */
+#define R_PPC64_TOC16 47 /* half16* S + A - .TOC */
+#define R_PPC64_TOC16_LO 48 /* half16 #lo(S + A - .TOC.) */
+#define R_PPC64_TOC16_HI 49 /* half16 #hi(S + A - .TOC.) */
+#define R_PPC64_TOC16_HA 50 /* half16 #ha(S + A - .TOC.) */
+#define R_PPC64_TOC 51 /* doubleword64 .TOC */
+#define R_PPC64_PLTGOT16 52 /* half16* M + A */
+#define R_PPC64_PLTGOT16_LO 53 /* half16 #lo(M + A) */
+#define R_PPC64_PLTGOT16_HI 54 /* half16 #hi(M + A) */
+#define R_PPC64_PLTGOT16_HA 55 /* half16 #ha(M + A) */
+
+#define R_PPC64_ADDR16_DS 56 /* half16ds* (S + A) >> 2 */
+#define R_PPC64_ADDR16_LO_DS 57 /* half16ds #lo(S + A) >> 2 */
+#define R_PPC64_GOT16_DS 58 /* half16ds* (G + A) >> 2 */
+#define R_PPC64_GOT16_LO_DS 59 /* half16ds #lo(G + A) >> 2 */
+#define R_PPC64_PLT16_LO_DS 60 /* half16ds #lo(L + A) >> 2 */
+#define R_PPC64_SECTOFF_DS 61 /* half16ds* (R + A) >> 2 */
+#define R_PPC64_SECTOFF_LO_DS 62 /* half16ds #lo(R + A) >> 2 */
+#define R_PPC64_TOC16_DS 63 /* half16ds* (S + A - .TOC.) >> 2 */
+#define R_PPC64_TOC16_LO_DS 64 /* half16ds #lo(S + A - .TOC.) >> 2 */
+#define R_PPC64_PLTGOT16_DS 65 /* half16ds* (M + A) >> 2 */
+#define R_PPC64_PLTGOT16_LO_DS 66 /* half16ds #lo(M + A) >> 2 */
+
+/* PowerPC64 relocations defined for the TLS access ABI. */
+#define R_PPC64_TLS 67 /* none (sym+add)@tls */
+#define R_PPC64_DTPMOD64 68 /* doubleword64 (sym+add)@dtpmod */
+#define R_PPC64_TPREL16 69 /* half16* (sym+add)@tprel */
+#define R_PPC64_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */
+#define R_PPC64_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */
+#define R_PPC64_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */
+#define R_PPC64_TPREL64 73 /* doubleword64 (sym+add)@tprel */
+#define R_PPC64_DTPREL16 74 /* half16* (sym+add)@dtprel */
+#define R_PPC64_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */
+#define R_PPC64_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */
+#define R_PPC64_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */
+#define R_PPC64_DTPREL64 78 /* doubleword64 (sym+add)@dtprel */
+#define R_PPC64_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */
+#define R_PPC64_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */
+#define R_PPC64_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */
+#define R_PPC64_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */
+#define R_PPC64_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */
+#define R_PPC64_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */
+#define R_PPC64_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */
+#define R_PPC64_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */
+#define R_PPC64_GOT_TPREL16_DS 87 /* half16ds* (sym+add)@got@tprel */
+#define R_PPC64_GOT_TPREL16_LO_DS 88 /* half16ds (sym+add)@got@tprel@l */
+#define R_PPC64_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */
+#define R_PPC64_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */
+#define R_PPC64_GOT_DTPREL16_DS 91 /* half16ds* (sym+add)@got@dtprel */
+#define R_PPC64_GOT_DTPREL16_LO_DS 92 /* half16ds (sym+add)@got@dtprel@l */
+#define R_PPC64_GOT_DTPREL16_HI 93 /* half16 (sym+add)@got@dtprel@h */
+#define R_PPC64_GOT_DTPREL16_HA 94 /* half16 (sym+add)@got@dtprel@ha */
+#define R_PPC64_TPREL16_DS 95 /* half16ds* (sym+add)@tprel */
+#define R_PPC64_TPREL16_LO_DS 96 /* half16ds (sym+add)@tprel@l */
+#define R_PPC64_TPREL16_HIGHER 97 /* half16 (sym+add)@tprel@higher */
+#define R_PPC64_TPREL16_HIGHERA 98 /* half16 (sym+add)@tprel@highera */
+#define R_PPC64_TPREL16_HIGHEST 99 /* half16 (sym+add)@tprel@highest */
+#define R_PPC64_TPREL16_HIGHESTA 100 /* half16 (sym+add)@tprel@highesta */
+#define R_PPC64_DTPREL16_DS 101 /* half16ds* (sym+add)@dtprel */
+#define R_PPC64_DTPREL16_LO_DS 102 /* half16ds (sym+add)@dtprel@l */
+#define R_PPC64_DTPREL16_HIGHER 103 /* half16 (sym+add)@dtprel@higher */
+#define R_PPC64_DTPREL16_HIGHERA 104 /* half16 (sym+add)@dtprel@highera */
+#define R_PPC64_DTPREL16_HIGHEST 105 /* half16 (sym+add)@dtprel@highest */
+#define R_PPC64_DTPREL16_HIGHESTA 106 /* half16 (sym+add)@dtprel@highesta */
+
+/* Keep this the last entry. */
+#define R_PPC64_NUM 107
+
+/* PowerPC64 specific values for the Dyn d_tag field. */
+#define DT_PPC64_GLINK (DT_LOPROC + 0)
+#define DT_PPC64_OPD (DT_LOPROC + 1)
+#define DT_PPC64_OPDSZ (DT_LOPROC + 2)
+#define DT_PPC64_NUM 3
+
+
+/* ARM specific declarations */
+
+/* Processor specific flags for the ELF header e_flags field. */
+#define EF_ARM_RELEXEC 0x01
+#define EF_ARM_HASENTRY 0x02
+#define EF_ARM_INTERWORK 0x04
+#define EF_ARM_APCS_26 0x08
+#define EF_ARM_APCS_FLOAT 0x10
+#define EF_ARM_PIC 0x20
+#define EF_ARM_ALIGN8 0x40 /* 8-bit structure alignment is in use */
+#define EF_ARM_NEW_ABI 0x80
+#define EF_ARM_OLD_ABI 0x100
+
+/* Other constants defined in the ARM ELF spec. version B-01. */
+/* NB. These conflict with values defined above. */
+#define EF_ARM_SYMSARESORTED 0x04
+#define EF_ARM_DYNSYMSUSESEGIDX 0x08
+#define EF_ARM_MAPSYMSFIRST 0x10
+#define EF_ARM_EABIMASK 0XFF000000
+
+#define EF_ARM_EABI_VERSION(flags) ((flags) & EF_ARM_EABIMASK)
+#define EF_ARM_EABI_UNKNOWN 0x00000000
+#define EF_ARM_EABI_VER1 0x01000000
+#define EF_ARM_EABI_VER2 0x02000000
+
+/* Additional symbol types for Thumb */
+#define STT_ARM_TFUNC 0xd
+
+/* ARM-specific values for sh_flags */
+#define SHF_ARM_ENTRYSECT 0x10000000 /* Section contains an entry point */
+#define SHF_ARM_COMDEF 0x80000000 /* Section may be multiply defined
+ in the input to a link step */
+
+/* ARM-specific program header flags */
+#define PF_ARM_SB 0x10000000 /* Segment contains the location
+ addressed by the static base */
+
+/* ARM relocs. */
+#define R_ARM_NONE 0 /* No reloc */
+#define R_ARM_PC24 1 /* PC relative 26 bit branch */
+#define R_ARM_ABS32 2 /* Direct 32 bit */
+#define R_ARM_REL32 3 /* PC relative 32 bit */
+#define R_ARM_PC13 4
+#define R_ARM_ABS16 5 /* Direct 16 bit */
+#define R_ARM_ABS12 6 /* Direct 12 bit */
+#define R_ARM_THM_ABS5 7
+#define R_ARM_ABS8 8 /* Direct 8 bit */
+#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
+#define R_ARM_COPY 20 /* Copy symbol at runtime */
+#define R_ARM_GLOB_DAT 21 /* Create GOT entry */
+#define R_ARM_JUMP_SLOT 22 /* Create PLT entry */
+#define R_ARM_RELATIVE 23 /* Adjust by program base */
+#define R_ARM_GOTOFF 24 /* 32 bit offset to GOT */
+#define R_ARM_GOTPC 25 /* 32 bit PC relative offset to GOT */
+#define R_ARM_GOT32 26 /* 32 bit GOT entry */
+#define R_ARM_PLT32 27 /* 32 bit PLT address */
+#define R_ARM_ALU_PCREL_7_0 32
+#define R_ARM_ALU_PCREL_15_8 33
+#define R_ARM_ALU_PCREL_23_15 34
+#define R_ARM_LDR_SBREL_11_0 35
+#define R_ARM_ALU_SBREL_19_12 36
+#define R_ARM_ALU_SBREL_27_20 37
+#define R_ARM_GNU_VTENTRY 100
+#define R_ARM_GNU_VTINHERIT 101
+#define R_ARM_THM_PC11 102 /* thumb unconditional branch */
+#define R_ARM_THM_PC9 103 /* thumb conditional branch */
+#define R_ARM_RXPC25 249
+#define R_ARM_RSBREL32 250
+#define R_ARM_THM_RPC22 251
+#define R_ARM_RREL32 252
+#define R_ARM_RABS22 253
+#define R_ARM_RPC24 254
+#define R_ARM_RBASE 255
+/* Keep this the last entry. */
+#define R_ARM_NUM 256
+
+/* IA-64 specific declarations. */
+
+/* Processor specific flags for the Ehdr e_flags field. */
+#define EF_IA_64_MASKOS 0x0000000f /* os-specific flags */
+#define EF_IA_64_ABI64 0x00000010 /* 64-bit ABI */
+#define EF_IA_64_ARCH 0xff000000 /* arch. version mask */
+
+/* Processor specific values for the Phdr p_type field. */
+#define PT_IA_64_ARCHEXT (PT_LOPROC + 0) /* arch extension bits */
+#define PT_IA_64_UNWIND (PT_LOPROC + 1) /* ia64 unwind bits */
+#define PT_IA_64_HP_OPT_ANOT (PT_LOOS + 0x12)
+#define PT_IA_64_HP_HSL_ANOT (PT_LOOS + 0x13)
+#define PT_IA_64_HP_STACK (PT_LOOS + 0x14)
+
+/* Processor specific flags for the Phdr p_flags field. */
+#define PF_IA_64_NORECOV 0x80000000 /* spec insns w/o recovery */
+
+/* Processor specific values for the Shdr sh_type field. */
+#define SHT_IA_64_EXT (SHT_LOPROC + 0) /* extension bits */
+#define SHT_IA_64_UNWIND (SHT_LOPROC + 1) /* unwind bits */
+
+/* Processor specific flags for the Shdr sh_flags field. */
+#define SHF_IA_64_SHORT 0x10000000 /* section near gp */
+#define SHF_IA_64_NORECOV 0x20000000 /* spec insns w/o recovery */
+
+/* Processor specific values for the Dyn d_tag field. */
+#define DT_IA_64_PLT_RESERVE (DT_LOPROC + 0)
+#define DT_IA_64_NUM 1
+
+/* IA-64 relocations. */
+#define R_IA64_NONE 0x00 /* none */
+#define R_IA64_IMM14 0x21 /* symbol + addend, add imm14 */
+#define R_IA64_IMM22 0x22 /* symbol + addend, add imm22 */
+#define R_IA64_IMM64 0x23 /* symbol + addend, mov imm64 */
+#define R_IA64_DIR32MSB 0x24 /* symbol + addend, data4 MSB */
+#define R_IA64_DIR32LSB 0x25 /* symbol + addend, data4 LSB */
+#define R_IA64_DIR64MSB 0x26 /* symbol + addend, data8 MSB */
+#define R_IA64_DIR64LSB 0x27 /* symbol + addend, data8 LSB */
+#define R_IA64_GPREL22 0x2a /* @gprel(sym + add), add imm22 */
+#define R_IA64_GPREL64I 0x2b /* @gprel(sym + add), mov imm64 */
+#define R_IA64_GPREL32MSB 0x2c /* @gprel(sym + add), data4 MSB */
+#define R_IA64_GPREL32LSB 0x2d /* @gprel(sym + add), data4 LSB */
+#define R_IA64_GPREL64MSB 0x2e /* @gprel(sym + add), data8 MSB */
+#define R_IA64_GPREL64LSB 0x2f /* @gprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF22 0x32 /* @ltoff(sym + add), add imm22 */
+#define R_IA64_LTOFF64I 0x33 /* @ltoff(sym + add), mov imm64 */
+#define R_IA64_PLTOFF22 0x3a /* @pltoff(sym + add), add imm22 */
+#define R_IA64_PLTOFF64I 0x3b /* @pltoff(sym + add), mov imm64 */
+#define R_IA64_PLTOFF64MSB 0x3e /* @pltoff(sym + add), data8 MSB */
+#define R_IA64_PLTOFF64LSB 0x3f /* @pltoff(sym + add), data8 LSB */
+#define R_IA64_FPTR64I 0x43 /* @fptr(sym + add), mov imm64 */
+#define R_IA64_FPTR32MSB 0x44 /* @fptr(sym + add), data4 MSB */
+#define R_IA64_FPTR32LSB 0x45 /* @fptr(sym + add), data4 LSB */
+#define R_IA64_FPTR64MSB 0x46 /* @fptr(sym + add), data8 MSB */
+#define R_IA64_FPTR64LSB 0x47 /* @fptr(sym + add), data8 LSB */
+#define R_IA64_PCREL60B 0x48 /* @pcrel(sym + add), brl */
+#define R_IA64_PCREL21B 0x49 /* @pcrel(sym + add), ptb, call */
+#define R_IA64_PCREL21M 0x4a /* @pcrel(sym + add), chk.s */
+#define R_IA64_PCREL21F 0x4b /* @pcrel(sym + add), fchkf */
+#define R_IA64_PCREL32MSB 0x4c /* @pcrel(sym + add), data4 MSB */
+#define R_IA64_PCREL32LSB 0x4d /* @pcrel(sym + add), data4 LSB */
+#define R_IA64_PCREL64MSB 0x4e /* @pcrel(sym + add), data8 MSB */
+#define R_IA64_PCREL64LSB 0x4f /* @pcrel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_FPTR22 0x52 /* @ltoff(@fptr(s+a)), imm22 */
+#define R_IA64_LTOFF_FPTR64I 0x53 /* @ltoff(@fptr(s+a)), imm64 */
+#define R_IA64_LTOFF_FPTR32MSB 0x54 /* @ltoff(@fptr(s+a)), data4 MSB */
+#define R_IA64_LTOFF_FPTR32LSB 0x55 /* @ltoff(@fptr(s+a)), data4 LSB */
+#define R_IA64_LTOFF_FPTR64MSB 0x56 /* @ltoff(@fptr(s+a)), data8 MSB */
+#define R_IA64_LTOFF_FPTR64LSB 0x57 /* @ltoff(@fptr(s+a)), data8 LSB */
+#define R_IA64_SEGREL32MSB 0x5c /* @segrel(sym + add), data4 MSB */
+#define R_IA64_SEGREL32LSB 0x5d /* @segrel(sym + add), data4 LSB */
+#define R_IA64_SEGREL64MSB 0x5e /* @segrel(sym + add), data8 MSB */
+#define R_IA64_SEGREL64LSB 0x5f /* @segrel(sym + add), data8 LSB */
+#define R_IA64_SECREL32MSB 0x64 /* @secrel(sym + add), data4 MSB */
+#define R_IA64_SECREL32LSB 0x65 /* @secrel(sym + add), data4 LSB */
+#define R_IA64_SECREL64MSB 0x66 /* @secrel(sym + add), data8 MSB */
+#define R_IA64_SECREL64LSB 0x67 /* @secrel(sym + add), data8 LSB */
+#define R_IA64_REL32MSB 0x6c /* data 4 + REL */
+#define R_IA64_REL32LSB 0x6d /* data 4 + REL */
+#define R_IA64_REL64MSB 0x6e /* data 8 + REL */
+#define R_IA64_REL64LSB 0x6f /* data 8 + REL */
+#define R_IA64_LTV32MSB 0x74 /* symbol + addend, data4 MSB */
+#define R_IA64_LTV32LSB 0x75 /* symbol + addend, data4 LSB */
+#define R_IA64_LTV64MSB 0x76 /* symbol + addend, data8 MSB */
+#define R_IA64_LTV64LSB 0x77 /* symbol + addend, data8 LSB */
+#define R_IA64_PCREL21BI 0x79 /* @pcrel(sym + add), 21bit inst */
+#define R_IA64_PCREL22 0x7a /* @pcrel(sym + add), 22bit inst */
+#define R_IA64_PCREL64I 0x7b /* @pcrel(sym + add), 64bit inst */
+#define R_IA64_IPLTMSB 0x80 /* dynamic reloc, imported PLT, MSB */
+#define R_IA64_IPLTLSB 0x81 /* dynamic reloc, imported PLT, LSB */
+#define R_IA64_COPY 0x84 /* copy relocation */
+#define R_IA64_SUB 0x85 /* Addend and symbol difference */
+#define R_IA64_LTOFF22X 0x86 /* LTOFF22, relaxable. */
+#define R_IA64_LDXMOV 0x87 /* Use of LTOFF22X. */
+#define R_IA64_TPREL14 0x91 /* @tprel(sym + add), imm14 */
+#define R_IA64_TPREL22 0x92 /* @tprel(sym + add), imm22 */
+#define R_IA64_TPREL64I 0x93 /* @tprel(sym + add), imm64 */
+#define R_IA64_TPREL64MSB 0x96 /* @tprel(sym + add), data8 MSB */
+#define R_IA64_TPREL64LSB 0x97 /* @tprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_TPREL22 0x9a /* @ltoff(@tprel(s+a)), imm2 */
+#define R_IA64_DTPMOD64MSB 0xa6 /* @dtpmod(sym + add), data8 MSB */
+#define R_IA64_DTPMOD64LSB 0xa7 /* @dtpmod(sym + add), data8 LSB */
+#define R_IA64_LTOFF_DTPMOD22 0xaa /* @ltoff(@dtpmod(sym + add)), imm22 */
+#define R_IA64_DTPREL14 0xb1 /* @dtprel(sym + add), imm14 */
+#define R_IA64_DTPREL22 0xb2 /* @dtprel(sym + add), imm22 */
+#define R_IA64_DTPREL64I 0xb3 /* @dtprel(sym + add), imm64 */
+#define R_IA64_DTPREL32MSB 0xb4 /* @dtprel(sym + add), data4 MSB */
+#define R_IA64_DTPREL32LSB 0xb5 /* @dtprel(sym + add), data4 LSB */
+#define R_IA64_DTPREL64MSB 0xb6 /* @dtprel(sym + add), data8 MSB */
+#define R_IA64_DTPREL64LSB 0xb7 /* @dtprel(sym + add), data8 LSB */
+#define R_IA64_LTOFF_DTPREL22 0xba /* @ltoff(@dtprel(s+a)), imm22 */
+
+/* SH specific declarations */
+
+/* SH relocs. */
+#define R_SH_NONE 0
+#define R_SH_DIR32 1
+#define R_SH_REL32 2
+#define R_SH_DIR8WPN 3
+#define R_SH_IND12W 4
+#define R_SH_DIR8WPL 5
+#define R_SH_DIR8WPZ 6
+#define R_SH_DIR8BP 7
+#define R_SH_DIR8W 8
+#define R_SH_DIR8L 9
+#define R_SH_SWITCH16 25
+#define R_SH_SWITCH32 26
+#define R_SH_USES 27
+#define R_SH_COUNT 28
+#define R_SH_ALIGN 29
+#define R_SH_CODE 30
+#define R_SH_DATA 31
+#define R_SH_LABEL 32
+#define R_SH_SWITCH8 33
+#define R_SH_GNU_VTINHERIT 34
+#define R_SH_GNU_VTENTRY 35
+#define R_SH_TLS_GD_32 144
+#define R_SH_TLS_LD_32 145
+#define R_SH_TLS_LDO_32 146
+#define R_SH_TLS_IE_32 147
+#define R_SH_TLS_LE_32 148
+#define R_SH_TLS_DTPMOD32 149
+#define R_SH_TLS_DTPOFF32 150
+#define R_SH_TLS_TPOFF32 151
+#define R_SH_GOT32 160
+#define R_SH_PLT32 161
+#define R_SH_COPY 162
+#define R_SH_GLOB_DAT 163
+#define R_SH_JMP_SLOT 164
+#define R_SH_RELATIVE 165
+#define R_SH_GOTOFF 166
+#define R_SH_GOTPC 167
+/* Keep this the last entry. */
+#define R_SH_NUM 256
+
+/* Additional s390 relocs */
+
+#define R_390_NONE 0 /* No reloc. */
+#define R_390_8 1 /* Direct 8 bit. */
+#define R_390_12 2 /* Direct 12 bit. */
+#define R_390_16 3 /* Direct 16 bit. */
+#define R_390_32 4 /* Direct 32 bit. */
+#define R_390_PC32 5 /* PC relative 32 bit. */
+#define R_390_GOT12 6 /* 12 bit GOT offset. */
+#define R_390_GOT32 7 /* 32 bit GOT offset. */
+#define R_390_PLT32 8 /* 32 bit PC relative PLT address. */
+#define R_390_COPY 9 /* Copy symbol at runtime. */
+#define R_390_GLOB_DAT 10 /* Create GOT entry. */
+#define R_390_JMP_SLOT 11 /* Create PLT entry. */
+#define R_390_RELATIVE 12 /* Adjust by program base. */
+#define R_390_GOTOFF32 13 /* 32 bit offset to GOT. */
+#define R_390_GOTPC 14 /* 32 bit PC relative offset to GOT. */
+#define R_390_GOT16 15 /* 16 bit GOT offset. */
+#define R_390_PC16 16 /* PC relative 16 bit. */
+#define R_390_PC16DBL 17 /* PC relative 16 bit shifted by 1. */
+#define R_390_PLT16DBL 18 /* 16 bit PC rel. PLT shifted by 1. */
+#define R_390_PC32DBL 19 /* PC relative 32 bit shifted by 1. */
+#define R_390_PLT32DBL 20 /* 32 bit PC rel. PLT shifted by 1. */
+#define R_390_GOTPCDBL 21 /* 32 bit PC rel. GOT shifted by 1. */
+#define R_390_64 22 /* Direct 64 bit. */
+#define R_390_PC64 23 /* PC relative 64 bit. */
+#define R_390_GOT64 24 /* 64 bit GOT offset. */
+#define R_390_PLT64 25 /* 64 bit PC relative PLT address. */
+#define R_390_GOTENT 26 /* 32 bit PC rel. to GOT entry >> 1. */
+#define R_390_GOTOFF16 27 /* 16 bit offset to GOT. */
+#define R_390_GOTOFF64 28 /* 64 bit offset to GOT. */
+#define R_390_GOTPLT12 29 /* 12 bit offset to jump slot. */
+#define R_390_GOTPLT16 30 /* 16 bit offset to jump slot. */
+#define R_390_GOTPLT32 31 /* 32 bit offset to jump slot. */
+#define R_390_GOTPLT64 32 /* 64 bit offset to jump slot. */
+#define R_390_GOTPLTENT 33 /* 32 bit rel. offset to jump slot. */
+#define R_390_PLTOFF16 34 /* 16 bit offset from GOT to PLT. */
+#define R_390_PLTOFF32 35 /* 32 bit offset from GOT to PLT. */
+#define R_390_PLTOFF64 36 /* 16 bit offset from GOT to PLT. */
+#define R_390_TLS_LOAD 37 /* Tag for load insn in TLS code. */
+#define R_390_TLS_GDCALL 38 /* Tag for function call in general
+ dynamic TLS code. */
+#define R_390_TLS_LDCALL 39 /* Tag for function call in local
+ dynamic TLS code. */
+#define R_390_TLS_GD32 40 /* Direct 32 bit for general dynamic
+ thread local data. */
+#define R_390_TLS_GD64 41 /* Direct 64 bit for general dynamic
+ thread local data. */
+#define R_390_TLS_GOTIE12 42 /* 12 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_GOTIE32 43 /* 32 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_GOTIE64 44 /* 64 bit GOT offset for static TLS
+ block offset. */
+#define R_390_TLS_LDM32 45 /* Direct 32 bit for local dynamic
+ thread local data in LE code. */
+#define R_390_TLS_LDM64 46 /* Direct 64 bit for local dynamic
+ thread local data in LE code. */
+#define R_390_TLS_IE32 47 /* 32 bit address of GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_IE64 48 /* 64 bit address of GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_IEENT 49 /* 32 bit rel. offset to GOT entry for
+ negated static TLS block offset. */
+#define R_390_TLS_LE32 50 /* 32 bit negated offset relative to
+ static TLS block. */
+#define R_390_TLS_LE64 51 /* 64 bit negated offset relative to
+ static TLS block. */
+#define R_390_TLS_LDO32 52 /* 32 bit offset relative to TLS
+ block. */
+#define R_390_TLS_LDO64 53 /* 64 bit offset relative to TLS
+ block. */
+#define R_390_TLS_DTPMOD 54 /* ID of module containing symbol. */
+#define R_390_TLS_DTPOFF 55 /* Offset in TLS block. */
+#define R_390_TLS_TPOFF 56 /* Negated offset in static TLS
+ block. */
+#define R_390_20 57 /* Direct 20 bit. */
+#define R_390_GOT20 58 /* 20 bit GOT offset. */
+#define R_390_GOTPLT20 59 /* 20 bit offset to jump slot. */
+#define R_390_TLS_GOTIE20 60 /* 20 bit GOT offset for static TLS
+ block offset. */
+/* Keep this the last entry. */
+#define R_390_NUM 61
+
+
+/* CRIS relocations. */
+#define R_CRIS_NONE 0
+#define R_CRIS_8 1
+#define R_CRIS_16 2
+#define R_CRIS_32 3
+#define R_CRIS_8_PCREL 4
+#define R_CRIS_16_PCREL 5
+#define R_CRIS_32_PCREL 6
+#define R_CRIS_GNU_VTINHERIT 7
+#define R_CRIS_GNU_VTENTRY 8
+#define R_CRIS_COPY 9
+#define R_CRIS_GLOB_DAT 10
+#define R_CRIS_JUMP_SLOT 11
+#define R_CRIS_RELATIVE 12
+#define R_CRIS_16_GOT 13
+#define R_CRIS_32_GOT 14
+#define R_CRIS_16_GOTPLT 15
+#define R_CRIS_32_GOTPLT 16
+#define R_CRIS_32_GOTREL 17
+#define R_CRIS_32_PLT_GOTREL 18
+#define R_CRIS_32_PLT_PCREL 19
+
+#define R_CRIS_NUM 20
+
+
+/* AMD x86-64 relocations. */
+#define R_X86_64_NONE 0 /* No reloc */
+#define R_X86_64_64 1 /* Direct 64 bit */
+#define R_X86_64_PC32 2 /* PC relative 32 bit signed */
+#define R_X86_64_GOT32 3 /* 32 bit GOT entry */
+#define R_X86_64_PLT32 4 /* 32 bit PLT address */
+#define R_X86_64_COPY 5 /* Copy symbol at runtime */
+#define R_X86_64_GLOB_DAT 6 /* Create GOT entry */
+#define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */
+#define R_X86_64_RELATIVE 8 /* Adjust by program base */
+#define R_X86_64_GOTPCREL 9 /* 32 bit signed PC relative
+ offset to GOT */
+#define R_X86_64_32 10 /* Direct 32 bit zero extended */
+#define R_X86_64_32S 11 /* Direct 32 bit sign extended */
+#define R_X86_64_16 12 /* Direct 16 bit zero extended */
+#define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */
+#define R_X86_64_8 14 /* Direct 8 bit sign extended */
+#define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */
+#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */
+#define R_X86_64_DTPOFF64 17 /* Offset in module's TLS block */
+#define R_X86_64_TPOFF64 18 /* Offset in initial TLS block */
+#define R_X86_64_TLSGD 19 /* 32 bit signed PC relative offset
+ to two GOT entries for GD symbol */
+#define R_X86_64_TLSLD 20 /* 32 bit signed PC relative offset
+ to two GOT entries for LD symbol */
+#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */
+#define R_X86_64_GOTTPOFF 22 /* 32 bit signed PC relative offset
+ to GOT entry for IE symbol */
+#define R_X86_64_TPOFF32 23 /* Offset in initial TLS block */
+
+#define R_X86_64_NUM 24
+
+
+/* AM33 relocations. */
+#define R_MN10300_NONE 0 /* No reloc. */
+#define R_MN10300_32 1 /* Direct 32 bit. */
+#define R_MN10300_16 2 /* Direct 16 bit. */
+#define R_MN10300_8 3 /* Direct 8 bit. */
+#define R_MN10300_PCREL32 4 /* PC-relative 32-bit. */
+#define R_MN10300_PCREL16 5 /* PC-relative 16-bit signed. */
+#define R_MN10300_PCREL8 6 /* PC-relative 8-bit signed. */
+#define R_MN10300_GNU_VTINHERIT 7 /* Ancient C++ vtable garbage... */
+#define R_MN10300_GNU_VTENTRY 8 /* ... collection annotation. */
+#define R_MN10300_24 9 /* Direct 24 bit. */
+#define R_MN10300_GOTPC32 10 /* 32-bit PCrel offset to GOT. */
+#define R_MN10300_GOTPC16 11 /* 16-bit PCrel offset to GOT. */
+#define R_MN10300_GOTOFF32 12 /* 32-bit offset from GOT. */
+#define R_MN10300_GOTOFF24 13 /* 24-bit offset from GOT. */
+#define R_MN10300_GOTOFF16 14 /* 16-bit offset from GOT. */
+#define R_MN10300_PLT32 15 /* 32-bit PCrel to PLT entry. */
+#define R_MN10300_PLT16 16 /* 16-bit PCrel to PLT entry. */
+#define R_MN10300_GOT32 17 /* 32-bit offset to GOT entry. */
+#define R_MN10300_GOT24 18 /* 24-bit offset to GOT entry. */
+#define R_MN10300_GOT16 19 /* 16-bit offset to GOT entry. */
+#define R_MN10300_COPY 20 /* Copy symbol at runtime. */
+#define R_MN10300_GLOB_DAT 21 /* Create GOT entry. */
+#define R_MN10300_JMP_SLOT 22 /* Create PLT entry. */
+#define R_MN10300_RELATIVE 23 /* Adjust by program base. */
+
+#define R_MN10300_NUM 24
+
+
+/* M32R relocs. */
+#define R_M32R_NONE 0 /* No reloc. */
+#define R_M32R_16 1 /* Direct 16 bit. */
+#define R_M32R_32 2 /* Direct 32 bit. */
+#define R_M32R_24 3 /* Direct 24 bit. */
+#define R_M32R_10_PCREL 4 /* PC relative 10 bit shifted. */
+#define R_M32R_18_PCREL 5 /* PC relative 18 bit shifted. */
+#define R_M32R_26_PCREL 6 /* PC relative 26 bit shifted. */
+#define R_M32R_HI16_ULO 7 /* High 16 bit with unsigned low. */
+#define R_M32R_HI16_SLO 8 /* High 16 bit with signed low. */
+#define R_M32R_LO16 9 /* Low 16 bit. */
+#define R_M32R_SDA16 10 /* 16 bit offset in SDA. */
+#define R_M32R_GNU_VTINHERIT 11
+#define R_M32R_GNU_VTENTRY 12
+/* M32R relocs use SHT_RELA. */
+#define R_M32R_16_RELA 33 /* Direct 16 bit. */
+#define R_M32R_32_RELA 34 /* Direct 32 bit. */
+#define R_M32R_24_RELA 35 /* Direct 24 bit. */
+#define R_M32R_10_PCREL_RELA 36 /* PC relative 10 bit shifted. */
+#define R_M32R_18_PCREL_RELA 37 /* PC relative 18 bit shifted. */
+#define R_M32R_26_PCREL_RELA 38 /* PC relative 26 bit shifted. */
+#define R_M32R_HI16_ULO_RELA 39 /* High 16 bit with unsigned low */
+#define R_M32R_HI16_SLO_RELA 40 /* High 16 bit with signed low */
+#define R_M32R_LO16_RELA 41 /* Low 16 bit */
+#define R_M32R_SDA16_RELA 42 /* 16 bit offset in SDA */
+#define R_M32R_RELA_GNU_VTINHERIT 43
+#define R_M32R_RELA_GNU_VTENTRY 44
+#define R_M32R_REL32 45 /* PC relative 32 bit */
+
+#define R_M32R_GOT24 48 /* 24 bit GOT entry */
+#define R_M32R_26_PLTREL 49 /* 26 bit PC relative to PLT shifted */
+#define R_M32R_COPY 50 /* Copy symbol at runtime */
+#define R_M32R_GLOB_DAT 51 /* Create GOT entry */
+#define R_M32R_JMP_SLOT 52 /* Create PLT entry */
+#define R_M32R_RELATIVE 53 /* Adjust by program base */
+#define R_M32R_GOTOFF 54 /* 24 bit offset to GOT */
+#define R_M32R_GOTPC24 55 /* 24 bit PC relative offset to GOT */
+#define R_M32R_GOT16_HI_ULO 56 /* High 16 bit GOT entry with unsigned
+ low */
+#define R_M32R_GOT16_HI_SLO 57 /* High 16 bit GOT entry with signed
+ low */
+#define R_M32R_GOT16_LO 58 /* Low 16 bit GOT entry */
+#define R_M32R_GOTPC_HI_ULO 59 /* High 16 bit PC relative offset to
+ GOT with unsigned low */
+#define R_M32R_GOTPC_HI_SLO 60 /* High 16 bit PC relative offset to
+ GOT with signed low */
+#define R_M32R_GOTPC_LO 61 /* Low 16 bit PC relative offset to
+ GOT */
+#define R_M32R_GOTOFF_HI_ULO 62 /* High 16 bit offset to GOT
+ with unsigned low */
+#define R_M32R_GOTOFF_HI_SLO 63 /* High 16 bit offset to GOT
+ with signed low */
+#define R_M32R_GOTOFF_LO 64 /* Low 16 bit offset to GOT */
+#define R_M32R_NUM 256 /* Keep this the last entry. */
+
+
+__END_DECLS
+
+#endif /* elf.h */
diff --git a/tools/mklibs/patches/001-compile.patch b/tools/mklibs/patches/001-compile.patch
new file mode 100644
index 0000000..09b831a
--- /dev/null
+++ b/tools/mklibs/patches/001-compile.patch
@@ -0,0 +1,8 @@
+--- a/configure.ac
++++ b/configure.ac
+@@ -1,4 +1,4 @@
+-AC_INIT([mklibs],m4_esyscmd(dpkg-parsechangelog | perl -ne 'print $1 if m/^Version: (.*)$/;'))
++AC_INIT([mklibs],m4_esyscmd([head -n1 debian/changelog | awk -F'[\\\\(\\\\)]' '{ print $2 }' | xargs -I{} echo -n {}]))
+ AM_INIT_AUTOMAKE([foreign no-define])
+ AC_CONFIG_HEADERS([config.h])
+ AM_MAINTAINER_MODE
diff --git a/tools/mklibs/patches/002-disable_symbol_checks.patch b/tools/mklibs/patches/002-disable_symbol_checks.patch
new file mode 100644
index 0000000..96ca7a5
--- /dev/null
+++ b/tools/mklibs/patches/002-disable_symbol_checks.patch
@@ -0,0 +1,20 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -533,7 +533,7 @@ while 1:
+ # No progress in last pass. Verify all remaining symbols are weak.
+ for name in unresolved:
+ if not needed_symbols[name].weak:
+- raise Exception("Unresolvable symbol %s" % name)
++ print("WARNING: Unresolvable symbol %s" % name)
+ break
+
+ previous_pass_unresolved = unresolved
+@@ -568,7 +568,7 @@ while 1:
+ for name in needed_symbols:
+ if not name in symbol_provider:
+ if not needed_symbols[name].weak:
+- raise Exception("No library provides non-weak %s" % name)
++ print("WARNING: Unresolvable symbol %s" % name)
+ else:
+ lib = symbol_provider[name]
+ library_symbols_used[lib].add(library_symbols[lib][name])
diff --git a/tools/mklibs/patches/003-no_copy.patch b/tools/mklibs/patches/003-no_copy.patch
new file mode 100644
index 0000000..bc1ae8d
--- /dev/null
+++ b/tools/mklibs/patches/003-no_copy.patch
@@ -0,0 +1,50 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -472,7 +472,7 @@ while 1:
+ passnr = passnr + 1
+ # Gather all already reduced libraries and treat them as objects as well
+ small_libs = []
+- for lib in regexpfilter(os.listdir(dest_path), "(.*-so-stripped)$"):
++ for lib in regexpfilter(os.listdir(dest_path), "(.*-so)$"):
+ obj = dest_path + "/" + lib
+ small_libs.append(obj)
+ inode = os.stat(obj)[ST_INO]
+@@ -588,12 +588,7 @@ while 1:
+ if not so_file:
+ sys.exit("File not found:" + library)
+ pic_file = find_pic(library)
+- if not pic_file:
+- # No pic file, so we have to use the .so file, no reduction
+- debug(DEBUG_VERBOSE, "No pic file found for", so_file, "; copying")
+- command(target + "objcopy", "--strip-unneeded -R .note -R .comment",
+- so_file, dest_path + "/" + so_file_name + "-so-stripped")
+- else:
++ if pic_file:
+ # we have a pic file, recompile
+ debug(DEBUG_SPAM, "extracting from:", pic_file, "so_file:", so_file)
+ soname = extract_soname(so_file)
+@@ -636,22 +631,14 @@ while 1:
+ cmd.append(library_depends_gcc_libnames(so_file))
+ command(target + "gcc", *cmd)
+
+- # strip result
+- command(target + "objcopy", "--strip-unneeded -R .note -R .comment",
+- dest_path + "/" + so_file_name + "-so",
+- dest_path + "/" + so_file_name + "-so-stripped")
+ ## DEBUG
+ debug(DEBUG_VERBOSE, so_file, "\t", str(os.stat(so_file)[ST_SIZE]))
+ debug(DEBUG_VERBOSE, dest_path + "/" + so_file_name + "-so", "\t",
+ str(os.stat(dest_path + "/" + so_file_name + "-so")[ST_SIZE]))
+- debug(DEBUG_VERBOSE, dest_path + "/" + so_file_name + "-so-stripped",
+- "\t", str(os.stat(dest_path + "/" + so_file_name + "-so-stripped")[ST_SIZE]))
+
+ # Finalising libs and cleaning up
+-for lib in regexpfilter(os.listdir(dest_path), "(.*)-so-stripped$"):
+- os.rename(dest_path + "/" + lib + "-so-stripped", dest_path + "/" + lib)
+-for lib in regexpfilter(os.listdir(dest_path), "(.*-so)$"):
+- os.remove(dest_path + "/" + lib)
++for lib in regexpfilter(os.listdir(dest_path), "(.*)-so$"):
++ os.rename(dest_path + "/" + lib + "-so", dest_path + "/" + lib)
+
+ # Canonicalize library names.
+ for lib in sorted(regexpfilter(os.listdir(dest_path), "(.*so[.\d]*)$")):
diff --git a/tools/mklibs/patches/004-libpthread_link.patch b/tools/mklibs/patches/004-libpthread_link.patch
new file mode 100644
index 0000000..3a630ea
--- /dev/null
+++ b/tools/mklibs/patches/004-libpthread_link.patch
@@ -0,0 +1,28 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -106,14 +106,14 @@ def library_depends(obj):
+
+ # Return a list of libraries the passed objects depend on. The
+ # libraries are in "-lfoo" format suitable for passing to gcc.
+-def library_depends_gcc_libnames(obj):
++def library_depends_gcc_libnames(obj, soname):
+ if not os.access(obj, os.F_OK):
+ raise Exception("Cannot find lib: " + obj)
+ libs = library_depends(obj)
+ ret = []
+ for i in libs:
+ match = re.match("^(((?P<ld>ld\S*)|(lib(?P<lib>\S+))))\.so.*$", i)
+- if match:
++ if match and not soname in ("libpthread.so.0"):
+ if match.group('ld'):
+ ret.append(find_lib(match.group(0)))
+ elif match.group('lib'):
+@@ -628,7 +628,7 @@ while 1:
+ cmd.extend(extra_flags)
+ cmd.append("-lgcc")
+ cmd.extend(["-L%s" % a for a in [dest_path] + [sysroot + b for b in lib_path if sysroot == "" or b not in ("/" + libdir + "/", "/usr/" + libdir + "/")]])
+- cmd.append(library_depends_gcc_libnames(so_file))
++ cmd.append(library_depends_gcc_libnames(so_file, soname))
+ command(target + "gcc", *cmd)
+
+ ## DEBUG
diff --git a/tools/mklibs/patches/005-duplicate_syms.patch b/tools/mklibs/patches/005-duplicate_syms.patch
new file mode 100644
index 0000000..2627203
--- /dev/null
+++ b/tools/mklibs/patches/005-duplicate_syms.patch
@@ -0,0 +1,35 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -540,7 +540,6 @@ while 1:
+
+ library_symbols = {}
+ library_symbols_used = {}
+- symbol_provider = {}
+
+ # WORKAROUND: Always add libgcc on old-abi arm
+ header = elf_header(find_lib(libraries.copy().pop()))
+@@ -558,20 +557,13 @@ while 1:
+ library_symbols_used[library] = set()
+ for symbol in symbols:
+ for name in symbol.base_names():
+- if name in symbol_provider:
+- debug(DEBUG_SPAM, "duplicate symbol %s in %s and %s" % (symbol, symbol_provider[name], library))
+- else:
+- library_symbols[library][name] = symbol
+- symbol_provider[name] = library
++ library_symbols[library][name] = symbol
+
+ # which symbols are actually used from each lib
+ for name in needed_symbols:
+- if not name in symbol_provider:
+- if not needed_symbols[name].weak:
+- print("WARNING: Unresolvable symbol %s" % name)
+- else:
+- lib = symbol_provider[name]
+- library_symbols_used[lib].add(library_symbols[lib][name])
++ for lib in libraries:
++ if name in library_symbols[lib]:
++ library_symbols_used[lib].add(library_symbols[lib][name])
+
+ # reduce libraries
+ for library in sorted(libraries):
diff --git a/tools/mklibs/patches/007-gc_sections.patch b/tools/mklibs/patches/007-gc_sections.patch
new file mode 100644
index 0000000..3d098ae
--- /dev/null
+++ b/tools/mklibs/patches/007-gc_sections.patch
@@ -0,0 +1,11 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -611,7 +611,7 @@ while 1:
+ # compile in only used symbols
+ cmd = []
+ cmd.extend(gcc_options)
+- cmd.append("-nostdlib -nostartfiles -shared -Wl,-soname=" + soname)
++ cmd.append("-nostdlib -nostartfiles -shared -Wl,--gc-sections -Wl,-soname=" + soname)
+ cmd.extend(["-u%s" % a.linker_name() for a in symbols])
+ cmd.extend(["-o", dest_path + "/" + so_file_name + "-so"])
+ cmd.extend(extra_pre_obj)
diff --git a/tools/mklibs/patches/008-uclibc_libgcc_link.patch b/tools/mklibs/patches/008-uclibc_libgcc_link.patch
new file mode 100644
index 0000000..a221278
--- /dev/null
+++ b/tools/mklibs/patches/008-uclibc_libgcc_link.patch
@@ -0,0 +1,37 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -113,11 +113,8 @@ def library_depends_gcc_libnames(obj, so
+ ret = []
+ for i in libs:
+ match = re.match("^(((?P<ld>ld\S*)|(lib(?P<lib>\S+))))\.so.*$", i)
+- if match and not soname in ("libpthread.so.0"):
+- if match.group('ld'):
+- ret.append(find_lib(match.group(0)))
+- elif match.group('lib'):
+- ret.append('-l%s' % match.group('lib'))
++ if match:
++ ret.append(find_lib(match.group(0)))
+ return ' '.join(ret)
+
+ class Symbol(object):
+@@ -593,6 +590,7 @@ while 1:
+ extra_flags = []
+ extra_pre_obj = []
+ extra_post_obj = []
++ libgcc_link = find_lib("libgcc_s.so.1")
+
+ symbols.update(library_symbols_used[library])
+
+@@ -618,9 +616,10 @@ while 1:
+ cmd.append(pic_file)
+ cmd.extend(extra_post_obj)
+ cmd.extend(extra_flags)
+- cmd.append("-lgcc")
+ cmd.extend(["-L%s" % a for a in [dest_path] + [sysroot + b for b in lib_path if sysroot == "" or b not in ("/" + libdir + "/", "/usr/" + libdir + "/")]])
+- cmd.append(library_depends_gcc_libnames(so_file, soname))
++ if soname != "libgcc_s.so.1":
++ cmd.append(library_depends_gcc_libnames(so_file, soname))
++ cmd.append(libgcc_link)
+ command(target + "gcc", *cmd)
+
+ ## DEBUG
diff --git a/tools/mklibs/patches/010-remove_STT_GNU_IFUNC.patch b/tools/mklibs/patches/010-remove_STT_GNU_IFUNC.patch
new file mode 100644
index 0000000..6bae8c7
--- /dev/null
+++ b/tools/mklibs/patches/010-remove_STT_GNU_IFUNC.patch
@@ -0,0 +1,20 @@
+--- a/src/mklibs-readelf/main.cpp
++++ b/src/mklibs-readelf/main.cpp
+@@ -84,7 +84,7 @@ static void process_symbols_provided (co
+ continue;
+ if (shndx == SHN_UNDEF || shndx == SHN_ABS)
+ continue;
+- if (type != STT_NOTYPE && type != STT_OBJECT && type != STT_FUNC && type != STT_GNU_IFUNC && type != STT_COMMON && type != STT_TLS)
++ if (type != STT_NOTYPE && type != STT_OBJECT && type != STT_FUNC && type != STT_COMMON && type != STT_TLS)
+ continue;
+ if (!name.size())
+ continue;
+@@ -115,7 +115,7 @@ static void process_symbols_undefined (c
+ continue;
+ if (shndx != SHN_UNDEF)
+ continue;
+- if (type != STT_NOTYPE && type != STT_OBJECT && type != STT_FUNC && type != STT_GNU_IFUNC && type != STT_COMMON && type != STT_TLS)
++ if (type != STT_NOTYPE && type != STT_OBJECT && type != STT_FUNC && type != STT_COMMON && type != STT_TLS)
+ continue;
+ if (!name.size())
+ continue;
diff --git a/tools/mklibs/patches/011-remove_multiarch.patch b/tools/mklibs/patches/011-remove_multiarch.patch
new file mode 100644
index 0000000..8c0bfdf
--- /dev/null
+++ b/tools/mklibs/patches/011-remove_multiarch.patch
@@ -0,0 +1,10 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -269,6 +269,7 @@ def extract_soname(so_file):
+ return ""
+
+ def multiarch(paths):
++ return paths
+ devnull = open('/dev/null', 'w')
+ dpkg_architecture = subprocess.Popen(
+ ['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
diff --git a/tools/mklibs/patches/100-apply-2to3.patch b/tools/mklibs/patches/100-apply-2to3.patch
new file mode 100644
index 0000000..dcacbab
--- /dev/null
+++ b/tools/mklibs/patches/100-apply-2to3.patch
@@ -0,0 +1,154 @@
+--- a/src/mklibs
++++ b/src/mklibs
+@@ -57,17 +57,17 @@ debuglevel = DEBUG_NORMAL
+
+ def debug(level, *msg):
+ if debuglevel >= level:
+- print(string.join(msg))
++ print(' '.join(msg))
+
+ # return a list of lines of output of the command
+ def command(command, *args):
+- debug(DEBUG_SPAM, "calling", command, string.join(args))
++ debug(DEBUG_SPAM, "calling", command, ' '.join(args))
+ pipe = os.popen(command + ' ' + ' '.join(args), 'r')
+ output = pipe.read().strip()
+ status = pipe.close()
+ if status is not None and os.WEXITSTATUS(status) != 0:
+ print("Command failed with status", os.WEXITSTATUS(status), ":", \
+- command, string.join(args))
++ command, ' '.join(args))
+ print("With output:", output)
+ sys.exit(1)
+ return [i for i in output.split('\n') if i]
+@@ -296,7 +296,7 @@ def usage(was_err):
+ print("Make a set of minimal libraries for FILE(s, file=outfd) in DEST.", file=outfd)
+ print("" , file=outfd)
+ print(" -d, --dest-dir DIRECTORY create libraries in DIRECTORY", file=outfd)
+- print(" -D, --no-default-lib omit default libpath (", ':'.join(default_lib_path, file=outfd), ", file=outfd)", file=outfd)
++ print(" -D, --no-default-lib omit default libpath (", ':'.join(default_lib_path), ")", file=outfd)
+ print(" -L DIRECTORY[:DIRECTORY]... add DIRECTORY(s, file=outfd) to the library search path", file=outfd)
+ print(" -l LIBRARY add LIBRARY always", file=outfd)
+ print(" --ldlib LDLIB use LDLIB for the dynamic linker", file=outfd)
+@@ -372,7 +372,7 @@ for opt, arg in optlist:
+ if debuglevel < DEBUG_SPAM:
+ debuglevel = debuglevel + 1
+ elif opt == "-L":
+- lib_path.extend(string.split(arg, ":"))
++ lib_path.extend(arg.split(":"))
+ elif opt in ("-d", "--dest-dir"):
+ dest_path = arg
+ elif opt in ("-D", "--no-default-lib"):
+@@ -391,7 +391,7 @@ for opt, arg in optlist:
+ elif opt in ("-l",):
+ force_libs.append(arg)
+ elif opt == "--gcc-options":
+- gcc_options.extend(string.split(arg, " "))
++ gcc_options.extend(arg.split(" "))
+ elif opt == "--libdir":
+ libdir = arg
+ elif opt in ("--help", "-h"):
+@@ -419,17 +419,17 @@ if ldlib == "LDLIB":
+ objects = {} # map from inode to filename
+ for prog in proglist:
+ inode = os.stat(prog)[ST_INO]
+- if objects.has_key(inode):
++ if inode in objects:
+ debug(DEBUG_SPAM, prog, "is a hardlink to", objects[inode])
+ elif so_pattern.match(prog):
+ debug(DEBUG_SPAM, prog, "is a library")
+- elif script_pattern.match(open(prog).read(256)):
++ elif script_pattern.match(open(prog, 'r', encoding='iso-8859-1').read(256)):
+ debug(DEBUG_SPAM, prog, "is a script")
+ else:
+ objects[inode] = prog
+
+ if not ldlib:
+- for obj in objects.values():
++ for obj in list(objects.values()):
+ output = command("mklibs-readelf", "--print-interp", obj)
+ if output:
+ ldlib = output.pop()
+@@ -462,9 +462,9 @@ previous_pass_unresolved = set()
+ while 1:
+ debug(DEBUG_NORMAL, "I: library reduction pass", str(passnr))
+ if debuglevel >= DEBUG_VERBOSE:
+- print("Objects:",)
+- for obj in sorted([x[string.rfind(x, '/') + 1:] for x in objects.values()]):
+- print(obj,)
++ print("Objects:", end=' ')
++ for obj in sorted([x[x.rfind('/') + 1:] for x in list(objects.values())]):
++ print(obj, end=' ')
+ print()
+
+ passnr = passnr + 1
+@@ -474,7 +474,7 @@ while 1:
+ obj = dest_path + "/" + lib
+ small_libs.append(obj)
+ inode = os.stat(obj)[ST_INO]
+- if objects.has_key(inode):
++ if inode in objects:
+ debug(DEBUG_SPAM, obj, "is hardlink to", objects[inode])
+ else:
+ objects[inode] = obj
+@@ -504,7 +504,7 @@ while 1:
+ present_symbols = {}
+ checked_libs = small_libs
+ checked_libs.extend(available_libs)
+- checked_libs.append(ldlib)
++ checked_libs.append(sysroot + "/" + ldlib)
+ for lib in checked_libs:
+ for symbol in provided_symbols(lib):
+ debug(DEBUG_SPAM, "present_symbols adding %s" % symbol)
+--- a/src/mklibs-copy
++++ b/src/mklibs-copy
+@@ -159,7 +159,7 @@ if include_default_lib_path:
+ objects = {} # map from inode to filename
+ for prog in proglist:
+ inode = os.stat(prog)[ST_INO]
+- if objects.has_key(inode):
++ if inode in objects:
+ logger.debug("%s is a hardlink to %s", prog, objects[inode])
+ elif so_pattern.match(prog):
+ logger.debug("%s is a library", prog)
+@@ -169,7 +169,7 @@ for prog in proglist:
+ logger.debug("%s is no ELF", prog)
+
+ if not ldlib:
+- for obj in objects.values():
++ for obj in list(objects.values()):
+ output = command("mklibs-readelf", "-i", obj)
+ for x in output:
+ ldlib = x
+@@ -182,7 +182,7 @@ if not ldlib:
+ logger.info('Using %s as dynamic linker', ldlib)
+
+ # Check for rpaths
+-for obj in objects.values():
++for obj in list(objects.values()):
+ rpath_val = rpath(obj)
+ if rpath_val:
+ if root:
+@@ -208,18 +208,18 @@ while 1:
+ obj = dest_path + "/" + lib
+ small_libs.append(obj)
+ inode = os.stat(obj)[ST_INO]
+- if objects.has_key(inode):
++ if inode in objects:
+ logger.debug("%s is hardlink to %s", obj, objects[inode])
+ else:
+ objects[inode] = obj
+
+- for obj in objects.values():
++ for obj in list(objects.values()):
+ small_libs.append(obj)
+
+- logger.verbose('Objects: %r', ' '.join([i[i.rfind('/') + 1:] for i in objects.itervalues()]))
++ logger.verbose('Objects: %r', ' '.join([i[i.rfind('/') + 1:] for i in objects.values()]))
+
+ libraries = set()
+- for obj in objects.values():
++ for obj in list(objects.values()):
+ libraries.update(library_depends(obj))
+
+ if libraries == previous_pass_libraries:
diff --git a/tools/mold/Makefile b/tools/mold/Makefile
new file mode 100644
index 0000000..28d760d
--- /dev/null
+++ b/tools/mold/Makefile
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mold
+PKG_VERSION:=2.33.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL_FILE:=v$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/rui314/mold/archive/refs/tags
+PKG_HASH:=37b3aacbd9b6accf581b92ba1a98ca418672ae330b78fe56ae542c2dcb10a155
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_HOST_OPTIONS += \
+ -DMOLD_LTO=ON \
+ -DMOLD_MOSTLY_STATIC=ON \
+ -DMOLD_USE_SYSTEM_MIMALLOC=OFF \
+ -DMOLD_USE_SYSTEM_TBB=OFF
+
+$(eval $(call HostBuild))
diff --git a/tools/mpc/Makefile b/tools/mpc/Makefile
new file mode 100644
index 0000000..97e9429
--- /dev/null
+++ b/tools/mpc/Makefile
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2009-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mpc
+PKG_VERSION:=1.3.1
+
+PKG_SOURCE_URL:=@GNU/mpc/
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_HASH:=ab642492f5cf882b74aa0cb730cd410a81edcdbec895183ce930e706c1c759b8
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+unexport CFLAGS
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static \
+ --disable-shared \
+ --with-mpfr=$(STAGING_DIR_HOST) \
+ --with-gmp=$(STAGING_DIR_HOST)
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/mpfr/Makefile b/tools/mpfr/Makefile
new file mode 100644
index 0000000..bfbbf39
--- /dev/null
+++ b/tools/mpfr/Makefile
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2009-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mpfr
+PKG_VERSION:=4.2.1
+PKG_CPE_ID:=cpe:/a:mpfr:gnu_mpfr
+
+PKG_SOURCE_URL:=@GNU/mpfr http://www.mpfr.org/mpfr-$(PKG_VERSION)
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_HASH:=116715552bd966c85b417c424db1bbdf639f53836eb361549d1f8d6ded5cb4c6
+
+HOST_BUILD_PARALLEL:=1
+HOST_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static \
+ --disable-shared \
+ --enable-thread-safe \
+ --with-gmp=$(STAGING_DIR_HOST)
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/mpfr/patches/001-only_src.patch b/tools/mpfr/patches/001-only_src.patch
new file mode 100644
index 0000000..bd9e38a
--- /dev/null
+++ b/tools/mpfr/patches/001-only_src.patch
@@ -0,0 +1,22 @@
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -38,7 +38,7 @@ AUTOMAKE_OPTIONS = gnu
+ # old Automake version.
+ ACLOCAL_AMFLAGS = -I m4
+
+-SUBDIRS = doc src tests tune tools/bench
++SUBDIRS = src
+
+ pkgconfigdir = $(libdir)/pkgconfig
+ pkgconfig_DATA = mpfr.pc
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -401,7 +401,7 @@ AUTOMAKE_OPTIONS = gnu
+ # libtoolize and in case some developer needs to switch back to an
+ # old Automake version.
+ ACLOCAL_AMFLAGS = -I m4
+-SUBDIRS = doc src tests tune tools/bench
++SUBDIRS = src
+ pkgconfigdir = $(libdir)/pkgconfig
+ pkgconfig_DATA = mpfr.pc
+ nobase_dist_doc_DATA = AUTHORS BUGS COPYING COPYING.LESSER NEWS TODO \
diff --git a/tools/mpfr/patches/100-freebsd-compat.patch b/tools/mpfr/patches/100-freebsd-compat.patch
new file mode 100644
index 0000000..8a7c6b0
--- /dev/null
+++ b/tools/mpfr/patches/100-freebsd-compat.patch
@@ -0,0 +1,10 @@
+--- a/src/vasprintf.c
++++ b/src/vasprintf.c
+@@ -72,6 +72,7 @@ https://www.gnu.org/licenses/ or write t
+ #endif /* HAVE_VA_COPY */
+
+ #ifdef HAVE_WCHAR_H
++#include <stddef.h>
+ #include <wchar.h>
+ #endif
+
diff --git a/tools/mtd-utils/Makefile b/tools/mtd-utils/Makefile
new file mode 100644
index 0000000..43c5ac1
--- /dev/null
+++ b/tools/mtd-utils/Makefile
@@ -0,0 +1,57 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mtd-utils
+PKG_VERSION:=2.2.1
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=https://infraroot.at/pub/mtd/
+PKG_HASH:=f7ae20b2eb79ee83441468f0b99d897024cd96ff853eea59106fb1952065c803
+PKG_CPE_ID:=cpe:/a:mtd-utils_project:mtd-utils
+
+PKG_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+ifneq ($(HOST_OS),Linux)
+ HOST_CFLAGS += \
+ -I$(CURDIR)/include \
+ -Dloff_t=off_t \
+ -D__BYTE_ORDER=BYTE_ORDER \
+ -include endian.h \
+ -DNO_NATIVE_SUPPORT \
+ -include fls.h
+endif
+
+HOST_LDFLAGS += -pthread
+
+HOST_CONFIGURE_ARGS+= \
+ --without-tests \
+ --without-crypto \
+ --without-xattr \
+ --without-zstd \
+ --without-lzo \
+ --with-lzma
+
+HOST_MAKE_FLAGS += \
+ PROGRAMS="mkfs.jffs2 ubinize mkfs.ubifs"
+
+define Host/Install
+ $(CP) \
+ $(HOST_BUILD_DIR)/mkfs.jffs2 \
+ $(HOST_BUILD_DIR)/mkfs.ubifs \
+ $(HOST_BUILD_DIR)/ubinize \
+ $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/{mkfs.jffs2,mkfs.ubifs,ubinize}
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/mtd-utils/include/fls.h b/tools/mtd-utils/include/fls.h
new file mode 100644
index 0000000..7514253
--- /dev/null
+++ b/tools/mtd-utils/include/fls.h
@@ -0,0 +1,2 @@
+#include <string.h>
+#define fls local_fls
diff --git a/tools/mtd-utils/include/linux/types.h b/tools/mtd-utils/include/linux/types.h
new file mode 100644
index 0000000..559fac7
--- /dev/null
+++ b/tools/mtd-utils/include/linux/types.h
@@ -0,0 +1,18 @@
+#ifndef _LINUX_TYPES_H
+#define _LINUX_TYPES_H
+
+#include <mtd/ubi-media.h>
+
+typedef uint16_t __u16;
+typedef uint32_t __u32;
+typedef uint64_t __u64;
+
+typedef __u16 __le16;
+typedef __u32 __le32;
+typedef __u64 __le64;
+typedef __u64 off64_t;
+
+typedef __u16 __sum16;
+typedef __u32 __wsum;
+
+#endif /* _LINUX_TYPES_H */
diff --git a/tools/mtd-utils/patches/100-sscanf_fix.patch b/tools/mtd-utils/patches/100-sscanf_fix.patch
new file mode 100644
index 0000000..a36be07
--- /dev/null
+++ b/tools/mtd-utils/patches/100-sscanf_fix.patch
@@ -0,0 +1,11 @@
+--- a/jffsX-utils/mkfs.jffs2.c
++++ b/jffsX-utils/mkfs.jffs2.c
+@@ -428,7 +428,7 @@ static int interpret_table_entry(struct
+
+ if (sscanf (line, "%" SCANF_PREFIX "s %c %lo %lu %lu %lu %lu %lu %lu %lu",
+ SCANF_STRING(name), &type, &mode, &uid, &gid, &major, &minor,
+- &start, &increment, &count) < 0)
++ &start, &increment, &count) < 10)
+ {
+ return 1;
+ }
diff --git a/tools/mtd-utils/patches/110-portability.patch b/tools/mtd-utils/patches/110-portability.patch
new file mode 100644
index 0000000..cf5f0c8
--- /dev/null
+++ b/tools/mtd-utils/patches/110-portability.patch
@@ -0,0 +1,175 @@
+--- a/jffsX-utils/compr_lzo.c
++++ b/jffsX-utils/compr_lzo.c
+@@ -24,7 +24,6 @@
+ #include <stdint.h>
+ #include <stdio.h>
+ #include <string.h>
+-#include <asm/types.h>
+ #include <linux/jffs2.h>
+ #include <lzo/lzo1x.h>
+ #include "compr.h"
+--- a/jffsX-utils/compr_zlib.c
++++ b/jffsX-utils/compr_zlib.c
+@@ -39,7 +39,6 @@
+ #include <zlib.h>
+ #undef crc32
+ #include <stdio.h>
+-#include <asm/types.h>
+ #include <linux/jffs2.h>
+ #include "common.h"
+ #include "compr.h"
+--- a/include/rbtree.h
++++ b/include/rbtree.h
+@@ -94,8 +94,7 @@ static inline struct page * rb_insert_pa
+ #ifndef _LINUX_RBTREE_H
+ #define _LINUX_RBTREE_H
+
+-#include <linux/kernel.h>
+-#include <linux/stddef.h>
++#include <stddef.h>
+
+ struct rb_node
+ {
+--- a/include/mtd/ubi-media.h
++++ b/include/mtd/ubi-media.h
+@@ -30,7 +30,15 @@
+ #ifndef __UBI_MEDIA_H__
+ #define __UBI_MEDIA_H__
+
++#ifdef __linux__
+ #include <asm/byteorder.h>
++#else
++#include <stdint.h>
++typedef uint8_t __u8;
++typedef uint16_t __be16;
++typedef uint32_t __be32;
++typedef uint64_t __be64;
++#endif
+
+ /* The version of UBI images supported by this implementation */
+ #define UBI_VERSION 1
+--- a/ubifs-utils/mkfs.ubifs/mkfs.ubifs.h
++++ b/ubifs-utils/mkfs.ubifs/mkfs.ubifs.h
+@@ -32,7 +32,17 @@
+ #include <endian.h>
+ #include <byteswap.h>
+ #include <linux/types.h>
++#ifdef __linux__
+ #include <linux/fs.h>
++# if defined(__x86_64__) && defined(__ILP32__)
++# define llseek lseek64
++# endif
++#else
++# ifndef O_LARGEFILE
++# define O_LARGEFILE 0
++# endif
++# define llseek lseek
++#endif
+
+ #include <getopt.h>
+ #include <sys/types.h>
+--- a/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c
++++ b/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c
+@@ -1568,6 +1568,7 @@ static int add_inode(struct stat *st, in
+
+ if (c->default_compr != UBIFS_COMPR_NONE)
+ use_flags |= UBIFS_COMPR_FL;
++#ifndef NO_NATIVE_SUPPORT
+ if (flags & FS_COMPR_FL)
+ use_flags |= UBIFS_COMPR_FL;
+ if (flags & FS_SYNC_FL)
+@@ -1580,6 +1581,7 @@ static int add_inode(struct stat *st, in
+ use_flags |= UBIFS_DIRSYNC_FL;
+ if (fctx)
+ use_flags |= UBIFS_CRYPT_FL;
++#endif
+ memset(ino, 0, UBIFS_INO_NODE_SZ);
+
+ ino_key_init(&key, inum);
+@@ -1665,7 +1667,9 @@ static int add_dir_inode(const char *pat
+ fd = dirfd(dir);
+ if (fd == -1)
+ return sys_err_msg("dirfd failed");
++#ifndef NO_NATIVE_SUPPORT
+ if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
++#endif
+ flags = 0;
+ }
+
+@@ -1878,6 +1882,7 @@ static int add_file(const char *path_nam
+ dn->ch.node_type = UBIFS_DATA_NODE;
+ key_write(&key, &dn->key);
+ out_len = NODE_BUFFER_SIZE - UBIFS_DATA_NODE_SZ;
++#ifndef NO_NATIVE_SUPPORT
+ if (c->default_compr == UBIFS_COMPR_NONE &&
+ !c->encrypted && (flags & FS_COMPR_FL))
+ #ifdef WITH_LZO
+@@ -1888,6 +1893,7 @@ static int add_file(const char *path_nam
+ use_compr = UBIFS_COMPR_NONE;
+ #endif
+ else
++#endif
+ use_compr = c->default_compr;
+ compr_type = compress_data(buf, bytes_read, &dn->data,
+ &out_len, use_compr);
+@@ -1947,7 +1953,9 @@ static int add_non_dir(const char *path_
+ if (fd == -1)
+ return sys_err_msg("failed to open file '%s'",
+ path_name);
++#ifndef NO_NATIVE_SUPPORT
+ if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
++#endif
+ flags = 0;
+ if (close(fd) == -1)
+ return sys_err_msg("failed to close file '%s'",
+--- a/ubifs-utils/mkfs.ubifs/devtable.c
++++ b/ubifs-utils/mkfs.ubifs/devtable.c
+@@ -135,6 +135,7 @@ static int interpret_table_entry(const c
+ unsigned int mode = 0755, uid = 0, gid = 0, major = 0, minor = 0;
+ unsigned int start = 0, increment = 0, count = 0;
+
++ buf[1023] = 0;
+ if (sscanf(line, "%1023s %c %o %u %u %u %u %u %u %u",
+ buf, &type, &mode, &uid, &gid, &major, &minor,
+ &start, &increment, &count) < 0)
+@@ -145,10 +146,10 @@ static int interpret_table_entry(const c
+ buf, type, mode, uid, gid, major, minor, start,
+ increment, count);
+
+- len = strnlen(buf, 1024);
++ len = strlen(buf);
+ if (len == 0)
+ return err_msg("empty path");
+- if (len == 1024)
++ if (len == 1023)
+ return err_msg("too long path");
+
+ if (buf[0] != '/')
+--- a/include/common.h
++++ b/include/common.h
+@@ -26,7 +26,6 @@
+ #include <string.h>
+ #include <fcntl.h>
+ #include <errno.h>
+-#include <features.h>
+ #include <inttypes.h>
+ #include <unistd.h>
+ #include <sys/sysmacros.h>
+--- a/include/mtd/ubifs-media.h
++++ b/include/mtd/ubifs-media.h
+@@ -33,7 +33,15 @@
+ #ifndef __UBIFS_MEDIA_H__
+ #define __UBIFS_MEDIA_H__
+
++#ifdef __linux__
+ #include <asm/byteorder.h>
++#else
++#include <stdint.h>
++typedef uint8_t __u8;
++typedef uint16_t __be16;
++typedef uint32_t __be32;
++typedef uint64_t __be64;
++#endif
+
+ /* UBIFS node magic number (must not have the padding byte first or last) */
+ #define UBIFS_NODE_MAGIC 0x06101831
diff --git a/tools/mtd-utils/patches/130-lzma_jffs2.patch b/tools/mtd-utils/patches/130-lzma_jffs2.patch
new file mode 100644
index 0000000..b03265a
--- /dev/null
+++ b/tools/mtd-utils/patches/130-lzma_jffs2.patch
@@ -0,0 +1,5073 @@
+--- a/jffsX-utils/Makemodule.am
++++ b/jffsX-utils/Makemodule.am
+@@ -9,8 +9,9 @@ mkfs_jffs2_SOURCES = \
+ include/mtd/jffs2-user.h \
+ include/list.h \
+ include/rbtree.h
++
+ mkfs_jffs2_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
+-mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS)
++mkfs_jffs2_CPPFLAGS = $(AM_CPPFLAGS) $(ZLIB_CFLAGS) $(LZO_CFLAGS) -I./include/linux/lzma
+
+ jffs2reader_SOURCES = jffsX-utils/jffs2reader.c include/mtd/jffs2-user.h
+ jffs2reader_LDADD = libmtd.a $(ZLIB_LIBS) $(LZO_LIBS)
+@@ -32,6 +33,14 @@ if WITH_ZLIB
+ mkfs_jffs2_SOURCES += jffsX-utils/compr_zlib.c
+ endif
+
++if WITH_LZMA
++mkfs_jffs2_SOURCES += \
++ jffsX-utils/compr_lzma.c \
++ jffsX-utils/lzma/LzFind.c \
++ jffsX-utils/lzma/LzmaEnc.c \
++ jffsX-utils/lzma/LzmaDec.c
++endif
++
+ EXTRA_DIST += jffsX-utils/device_table.txt jffsX-utils/mkfs.jffs2.1
+
+ dist_man1_MANS += jffsX-utils/mkfs.jffs2.1
+--- a/jffsX-utils/compr.c
++++ b/jffsX-utils/compr.c
+@@ -471,6 +471,9 @@ int jffs2_compressors_init(void)
+ #ifdef WITH_LZO
+ jffs2_lzo_init();
+ #endif
++#ifdef WITH_LZMA
++ jffs2_lzma_init();
++#endif
+ return 0;
+ }
+
+@@ -485,5 +488,8 @@ int jffs2_compressors_exit(void)
+ #ifdef WITH_LZO
+ jffs2_lzo_exit();
+ #endif
++#ifdef WITH_LZMA
++ jffs2_lzma_exit();
++#endif
+ return 0;
+ }
+--- a/jffsX-utils/compr.h
++++ b/jffsX-utils/compr.h
+@@ -22,8 +22,9 @@
+ #define JFFS2_RUBINMIPS_PRIORITY 10
+ #define JFFS2_DYNRUBIN_PRIORITY 20
+ #define JFFS2_RTIME_PRIORITY 50
+-#define JFFS2_ZLIB_PRIORITY 60
+-#define JFFS2_LZO_PRIORITY 80
++#define JFFS2_LZMA_PRIORITY 70
++#define JFFS2_ZLIB_PRIORITY 80
++#define JFFS2_LZO_PRIORITY 90
+
+ #define JFFS2_COMPR_MODE_NONE 0
+ #define JFFS2_COMPR_MODE_PRIORITY 1
+@@ -110,5 +111,10 @@ void jffs2_rtime_exit(void);
+ int jffs2_lzo_init(void);
+ void jffs2_lzo_exit(void);
+ #endif
++#ifdef WITH_LZMA
++int jffs2_lzma_init(void);
++void jffs2_lzma_exit(void);
++#endif
++
+
+ #endif /* __JFFS2_COMPR_H__ */
+--- /dev/null
++++ b/jffsX-utils/compr_lzma.c
+@@ -0,0 +1,128 @@
++/*
++ * JFFS2 -- Journalling Flash File System, Version 2.
++ *
++ * For licensing information, see the file 'LICENCE' in this directory.
++ *
++ * JFFS2 wrapper to the LZMA C SDK
++ *
++ */
++
++#include <linux/lzma.h>
++#include "compr.h"
++
++#ifdef __KERNEL__
++ static DEFINE_MUTEX(deflate_mutex);
++#endif
++
++CLzmaEncHandle *p;
++Byte propsEncoded[LZMA_PROPS_SIZE];
++SizeT propsSize = sizeof(propsEncoded);
++
++STATIC void lzma_free_workspace(void)
++{
++ LzmaEnc_Destroy(p, &lzma_alloc, &lzma_alloc);
++}
++
++STATIC int INIT lzma_alloc_workspace(CLzmaEncProps *props)
++{
++ if ((p = (CLzmaEncHandle *)LzmaEnc_Create(&lzma_alloc)) == NULL)
++ {
++ PRINT_ERROR("Failed to allocate lzma deflate workspace\n");
++ return -ENOMEM;
++ }
++
++ if (LzmaEnc_SetProps(p, props) != SZ_OK)
++ {
++ lzma_free_workspace();
++ return -1;
++ }
++
++ if (LzmaEnc_WriteProperties(p, propsEncoded, &propsSize) != SZ_OK)
++ {
++ lzma_free_workspace();
++ return -1;
++ }
++
++ return 0;
++}
++
++STATIC int jffs2_lzma_compress(unsigned char *data_in, unsigned char *cpage_out,
++ uint32_t *sourcelen, uint32_t *dstlen)
++{
++ SizeT compress_size = (SizeT)(*dstlen);
++ int ret;
++
++ #ifdef __KERNEL__
++ mutex_lock(&deflate_mutex);
++ #endif
++
++ ret = LzmaEnc_MemEncode(p, cpage_out, &compress_size, data_in, *sourcelen,
++ 0, NULL, &lzma_alloc, &lzma_alloc);
++
++ #ifdef __KERNEL__
++ mutex_unlock(&deflate_mutex);
++ #endif
++
++ if (ret != SZ_OK)
++ return -1;
++
++ *dstlen = (uint32_t)compress_size;
++
++ return 0;
++}
++
++STATIC int jffs2_lzma_decompress(unsigned char *data_in, unsigned char *cpage_out,
++ uint32_t srclen, uint32_t destlen)
++{
++ int ret;
++ SizeT dl = (SizeT)destlen;
++ SizeT sl = (SizeT)srclen;
++ ELzmaStatus status;
++
++ ret = LzmaDecode(cpage_out, &dl, data_in, &sl, propsEncoded,
++ propsSize, LZMA_FINISH_ANY, &status, &lzma_alloc);
++
++ if (ret != SZ_OK || status == LZMA_STATUS_NOT_FINISHED || dl != (SizeT)destlen)
++ return -1;
++
++ return 0;
++}
++
++static struct jffs2_compressor jffs2_lzma_comp = {
++ .priority = JFFS2_LZMA_PRIORITY,
++ .name = "lzma",
++ .compr = JFFS2_COMPR_LZMA,
++ .compress = &jffs2_lzma_compress,
++ .decompress = &jffs2_lzma_decompress,
++ .disabled = 0,
++};
++
++int INIT jffs2_lzma_init(void)
++{
++ int ret;
++ CLzmaEncProps props;
++ LzmaEncProps_Init(&props);
++
++ props.dictSize = LZMA_BEST_DICT(0x2000);
++ props.level = LZMA_BEST_LEVEL;
++ props.lc = LZMA_BEST_LC;
++ props.lp = LZMA_BEST_LP;
++ props.pb = LZMA_BEST_PB;
++ props.fb = LZMA_BEST_FB;
++
++ ret = lzma_alloc_workspace(&props);
++ if (ret < 0)
++ return ret;
++
++ ret = jffs2_register_compressor(&jffs2_lzma_comp);
++ if (ret)
++ lzma_free_workspace();
++
++ return ret;
++}
++
++void jffs2_lzma_exit(void)
++{
++ jffs2_unregister_compressor(&jffs2_lzma_comp);
++ lzma_free_workspace();
++}
+--- a/include/linux/jffs2.h
++++ b/include/linux/jffs2.h
+@@ -47,6 +47,7 @@
+ #define JFFS2_COMPR_DYNRUBIN 0x05
+ #define JFFS2_COMPR_ZLIB 0x06
+ #define JFFS2_COMPR_LZO 0x07
++#define JFFS2_COMPR_LZMA 0x08
+ /* Compatibility flags. */
+ #define JFFS2_COMPAT_MASK 0xc000 /* What do to if an unknown nodetype is found */
+ #define JFFS2_NODE_ACCURATE 0x2000
+--- /dev/null
++++ b/include/linux/lzma.h
+@@ -0,0 +1,61 @@
++#ifndef __LZMA_H__
++#define __LZMA_H__
++
++#ifdef __KERNEL__
++ #include <linux/kernel.h>
++ #include <linux/sched.h>
++ #include <linux/slab.h>
++ #include <linux/vmalloc.h>
++ #include <linux/init.h>
++ #define LZMA_MALLOC vmalloc
++ #define LZMA_FREE vfree
++ #define PRINT_ERROR(msg) printk(KERN_WARNING #msg)
++ #define INIT __init
++ #define STATIC static
++#else
++ #include <stdint.h>
++ #include <stdlib.h>
++ #include <stdio.h>
++ #include <unistd.h>
++ #include <string.h>
++ #include <errno.h>
++ #include <linux/jffs2.h>
++ #ifndef PAGE_SIZE
++ extern int page_size;
++ #define PAGE_SIZE page_size
++ #endif
++ #define LZMA_MALLOC malloc
++ #define LZMA_FREE free
++ #define PRINT_ERROR(msg) fprintf(stderr, msg)
++ #define INIT
++ #define STATIC static
++#endif
++
++#include "lzma/LzmaDec.h"
++#include "lzma/LzmaEnc.h"
++
++#define LZMA_BEST_LEVEL (9)
++#define LZMA_BEST_LC (0)
++#define LZMA_BEST_LP (0)
++#define LZMA_BEST_PB (0)
++#define LZMA_BEST_FB (273)
++
++#define LZMA_BEST_DICT(n) (((int)((n) / 2)) * 2)
++
++static void *p_lzma_malloc(void *p, size_t size)
++{
++ if (size == 0)
++ return NULL;
++
++ return LZMA_MALLOC(size);
++}
++
++static void p_lzma_free(void *p, void *address)
++{
++ if (address != NULL)
++ LZMA_FREE(address);
++}
++
++static ISzAlloc lzma_alloc = {p_lzma_malloc, p_lzma_free};
++
++#endif
+--- /dev/null
++++ b/include/linux/lzma/LzFind.h
+@@ -0,0 +1,116 @@
++/* LzFind.h -- Match finder for LZ algorithms
++2008-04-04
++Copyright (c) 1999-2008 Igor Pavlov
++You can use any of the following license options:
++ 1) GNU Lesser General Public License (GNU LGPL)
++ 2) Common Public License (CPL)
++ 3) Common Development and Distribution License (CDDL) Version 1.0
++ 4) Igor Pavlov, as the author of this code, expressly permits you to
++ statically or dynamically link your code (or bind by name) to this file,
++ while you keep this file unmodified.
++*/
++
++#ifndef __LZFIND_H
++#define __LZFIND_H
++
++#include "Types.h"
++
++typedef UInt32 CLzRef;
++
++typedef struct _CMatchFinder
++{
++ Byte *buffer;
++ UInt32 pos;
++ UInt32 posLimit;
++ UInt32 streamPos;
++ UInt32 lenLimit;
++
++ UInt32 cyclicBufferPos;
++ UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */
++
++ UInt32 matchMaxLen;
++ CLzRef *hash;
++ CLzRef *son;
++ UInt32 hashMask;
++ UInt32 cutValue;
++
++ Byte *bufferBase;
++ ISeqInStream *stream;
++ int streamEndWasReached;
++
++ UInt32 blockSize;
++ UInt32 keepSizeBefore;
++ UInt32 keepSizeAfter;
++
++ UInt32 numHashBytes;
++ int directInput;
++ int btMode;
++ /* int skipModeBits; */
++ int bigHash;
++ UInt32 historySize;
++ UInt32 fixedHashSize;
++ UInt32 hashSizeSum;
++ UInt32 numSons;
++ SRes result;
++ UInt32 crc[256];
++} CMatchFinder;
++
++#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer)
++#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)])
++
++#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos)
++
++int MatchFinder_NeedMove(CMatchFinder *p);
++Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p);
++void MatchFinder_MoveBlock(CMatchFinder *p);
++void MatchFinder_ReadIfRequired(CMatchFinder *p);
++
++void MatchFinder_Construct(CMatchFinder *p);
++
++/* Conditions:
++ historySize <= 3 GB
++ keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB
++*/
++int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
++ UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
++ ISzAlloc *alloc);
++void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc);
++void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems);
++void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
++
++UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son,
++ UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue,
++ UInt32 *distances, UInt32 maxLen);
++
++/*
++Conditions:
++ Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func.
++ Mf_GetPointerToCurrentPos_Func's result must be used only before any other function
++*/
++
++typedef void (*Mf_Init_Func)(void *object);
++typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index);
++typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object);
++typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
++typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
++typedef void (*Mf_Skip_Func)(void *object, UInt32);
++
++typedef struct _IMatchFinder
++{
++ Mf_Init_Func Init;
++ Mf_GetIndexByte_Func GetIndexByte;
++ Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
++ Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos;
++ Mf_GetMatches_Func GetMatches;
++ Mf_Skip_Func Skip;
++} IMatchFinder;
++
++void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable);
++
++void MatchFinder_Init(CMatchFinder *p);
++UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
++UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances);
++void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
++void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num);
++
++#endif
+--- /dev/null
++++ b/include/linux/lzma/LzHash.h
+@@ -0,0 +1,56 @@
++/* LzHash.h -- HASH functions for LZ algorithms
++2008-03-26
++Copyright (c) 1999-2008 Igor Pavlov
++Read LzFind.h for license options */
++
++#ifndef __LZHASH_H
++#define __LZHASH_H
++
++#define kHash2Size (1 << 10)
++#define kHash3Size (1 << 16)
++#define kHash4Size (1 << 20)
++
++#define kFix3HashSize (kHash2Size)
++#define kFix4HashSize (kHash2Size + kHash3Size)
++#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size)
++
++#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8);
++
++#define HASH3_CALC { \
++ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
++ hash2Value = temp & (kHash2Size - 1); \
++ hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; }
++
++#define HASH4_CALC { \
++ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
++ hash2Value = temp & (kHash2Size - 1); \
++ hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
++ hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; }
++
++#define HASH5_CALC { \
++ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
++ hash2Value = temp & (kHash2Size - 1); \
++ hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
++ hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \
++ hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \
++ hash4Value &= (kHash4Size - 1); }
++
++/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */
++#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF;
++
++
++#define MT_HASH2_CALC \
++ hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1);
++
++#define MT_HASH3_CALC { \
++ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
++ hash2Value = temp & (kHash2Size - 1); \
++ hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
++
++#define MT_HASH4_CALC { \
++ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
++ hash2Value = temp & (kHash2Size - 1); \
++ hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \
++ hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); }
++
++#endif
+--- /dev/null
++++ b/include/linux/lzma/LzmaDec.h
+@@ -0,0 +1,232 @@
++/* LzmaDec.h -- LZMA Decoder
++2008-04-29
++Copyright (c) 1999-2008 Igor Pavlov
++You can use any of the following license options:
++ 1) GNU Lesser General Public License (GNU LGPL)
++ 2) Common Public License (CPL)
++ 3) Common Development and Distribution License (CDDL) Version 1.0
++ 4) Igor Pavlov, as the author of this code, expressly permits you to
++ statically or dynamically link your code (or bind by name) to this file,
++ while you keep this file unmodified.
++*/
++
++#ifndef __LZMADEC_H
++#define __LZMADEC_H
++
++#include "Types.h"
++
++/* #define _LZMA_PROB32 */
++/* _LZMA_PROB32 can increase the speed on some CPUs,
++ but memory usage for CLzmaDec::probs will be doubled in that case */
++
++#ifdef _LZMA_PROB32
++#define CLzmaProb UInt32
++#else
++#define CLzmaProb UInt16
++#endif
++
++
++/* ---------- LZMA Properties ---------- */
++
++#define LZMA_PROPS_SIZE 5
++
++typedef struct _CLzmaProps
++{
++ unsigned lc, lp, pb;
++ UInt32 dicSize;
++} CLzmaProps;
++
++/* LzmaProps_Decode - decodes properties
++Returns:
++ SZ_OK
++ SZ_ERROR_UNSUPPORTED - Unsupported properties
++*/
++
++SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
++
++
++/* ---------- LZMA Decoder state ---------- */
++
++/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
++ Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
++
++#define LZMA_REQUIRED_INPUT_MAX 20
++
++typedef struct
++{
++ CLzmaProps prop;
++ CLzmaProb *probs;
++ Byte *dic;
++ const Byte *buf;
++ UInt32 range, code;
++ SizeT dicPos;
++ SizeT dicBufSize;
++ UInt32 processedPos;
++ UInt32 checkDicSize;
++ unsigned state;
++ UInt32 reps[4];
++ unsigned remainLen;
++ int needFlush;
++ int needInitState;
++ UInt32 numProbs;
++ unsigned tempBufSize;
++ Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
++} CLzmaDec;
++
++#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
++
++void LzmaDec_Init(CLzmaDec *p);
++
++/* There are two types of LZMA streams:
++ 0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
++ 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
++
++typedef enum
++{
++ LZMA_FINISH_ANY, /* finish at any point */
++ LZMA_FINISH_END /* block must be finished at the end */
++} ELzmaFinishMode;
++
++/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
++
++ You must use LZMA_FINISH_END, when you know that current output buffer
++ covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
++
++ If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
++ and output value of destLen will be less than output buffer size limit.
++ You can check status result also.
++
++ You can use multiple checks to test data integrity after full decompression:
++ 1) Check Result and "status" variable.
++ 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
++ 3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
++ You must use correct finish mode in that case. */
++
++typedef enum
++{
++ LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
++ LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
++ LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
++ LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
++ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
++} ELzmaStatus;
++
++/* ELzmaStatus is used only as output value for function call */
++
++
++/* ---------- Interfaces ---------- */
++
++/* There are 3 levels of interfaces:
++ 1) Dictionary Interface
++ 2) Buffer Interface
++ 3) One Call Interface
++ You can select any of these interfaces, but don't mix functions from different
++ groups for same object. */
++
++
++/* There are two variants to allocate state for Dictionary Interface:
++ 1) LzmaDec_Allocate / LzmaDec_Free
++ 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
++ You can use variant 2, if you set dictionary buffer manually.
++ For Buffer Interface you must always use variant 1.
++
++LzmaDec_Allocate* can return:
++ SZ_OK
++ SZ_ERROR_MEM - Memory allocation error
++ SZ_ERROR_UNSUPPORTED - Unsupported properties
++*/
++
++SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
++void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
++
++SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
++void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
++
++/* ---------- Dictionary Interface ---------- */
++
++/* You can use it, if you want to eliminate the overhead for data copying from
++ dictionary to some other external buffer.
++ You must work with CLzmaDec variables directly in this interface.
++
++ STEPS:
++ LzmaDec_Constr()
++ LzmaDec_Allocate()
++ for (each new stream)
++ {
++ LzmaDec_Init()
++ while (it needs more decompression)
++ {
++ LzmaDec_DecodeToDic()
++ use data from CLzmaDec::dic and update CLzmaDec::dicPos
++ }
++ }
++ LzmaDec_Free()
++*/
++
++/* LzmaDec_DecodeToDic
++
++ The decoding to internal dictionary buffer (CLzmaDec::dic).
++ You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
++
++finishMode:
++ It has meaning only if the decoding reaches output limit (dicLimit).
++ LZMA_FINISH_ANY - Decode just dicLimit bytes.
++ LZMA_FINISH_END - Stream must be finished after dicLimit.
++
++Returns:
++ SZ_OK
++ status:
++ LZMA_STATUS_FINISHED_WITH_MARK
++ LZMA_STATUS_NOT_FINISHED
++ LZMA_STATUS_NEEDS_MORE_INPUT
++ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
++ SZ_ERROR_DATA - Data error
++*/
++
++SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
++ const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
++
++
++/* ---------- Buffer Interface ---------- */
++
++/* It's zlib-like interface.
++ See LzmaDec_DecodeToDic description for information about STEPS and return results,
++ but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
++ to work with CLzmaDec variables manually.
++
++finishMode:
++ It has meaning only if the decoding reaches output limit (*destLen).
++ LZMA_FINISH_ANY - Decode just destLen bytes.
++ LZMA_FINISH_END - Stream must be finished after (*destLen).
++*/
++
++SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
++ const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
++
++
++/* ---------- One Call Interface ---------- */
++
++/* LzmaDecode
++
++finishMode:
++ It has meaning only if the decoding reaches output limit (*destLen).
++ LZMA_FINISH_ANY - Decode just destLen bytes.
++ LZMA_FINISH_END - Stream must be finished after (*destLen).
++
++Returns:
++ SZ_OK
++ status:
++ LZMA_STATUS_FINISHED_WITH_MARK
++ LZMA_STATUS_NOT_FINISHED
++ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
++ SZ_ERROR_DATA - Data error
++ SZ_ERROR_MEM - Memory allocation error
++ SZ_ERROR_UNSUPPORTED - Unsupported properties
++ SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
++*/
++
++SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
++ const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
++ ELzmaStatus *status, ISzAlloc *alloc);
++
++#endif
+--- /dev/null
++++ b/include/linux/lzma/LzmaEnc.h
+@@ -0,0 +1,74 @@
++/* LzmaEnc.h -- LZMA Encoder
++2008-04-27
++Copyright (c) 1999-2008 Igor Pavlov
++Read LzFind.h for license options */
++
++#ifndef __LZMAENC_H
++#define __LZMAENC_H
++
++#include "Types.h"
++
++#define LZMA_PROPS_SIZE 5
++
++typedef struct _CLzmaEncProps
++{
++ int level; /* 0 <= level <= 9 */
++ UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
++ (1 << 12) <= dictSize <= (1 << 30) for 64-bit version
++ default = (1 << 24) */
++ int lc; /* 0 <= lc <= 8, default = 3 */
++ int lp; /* 0 <= lp <= 4, default = 0 */
++ int pb; /* 0 <= pb <= 4, default = 2 */
++ int algo; /* 0 - fast, 1 - normal, default = 1 */
++ int fb; /* 5 <= fb <= 273, default = 32 */
++ int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
++ int numHashBytes; /* 2, 3 or 4, default = 4 */
++ UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */
++ unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
++ int numThreads; /* 1 or 2, default = 2 */
++} CLzmaEncProps;
++
++void LzmaEncProps_Init(CLzmaEncProps *p);
++void LzmaEncProps_Normalize(CLzmaEncProps *p);
++UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2);
++
++
++/* ---------- CLzmaEncHandle Interface ---------- */
++
++/* LzmaEnc_* functions can return the following exit codes:
++Returns:
++ SZ_OK - OK
++ SZ_ERROR_MEM - Memory allocation error
++ SZ_ERROR_PARAM - Incorrect paramater in props
++ SZ_ERROR_WRITE - Write callback error.
++ SZ_ERROR_PROGRESS - some break from progress callback
++ SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
++*/
++
++typedef void * CLzmaEncHandle;
++
++CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc);
++void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig);
++SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props);
++SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
++SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream,
++ ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
++SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
++ int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
++
++/* ---------- One Call Interface ---------- */
++
++/* LzmaEncode
++Return code:
++ SZ_OK - OK
++ SZ_ERROR_MEM - Memory allocation error
++ SZ_ERROR_PARAM - Incorrect paramater
++ SZ_ERROR_OUTPUT_EOF - output buffer overflow
++ SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
++*/
++
++SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
++ const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
++ ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig);
++
++#endif
+--- /dev/null
++++ b/include/linux/lzma/Types.h
+@@ -0,0 +1,130 @@
++/* Types.h -- Basic types
++2008-04-11
++Igor Pavlov
++Public domain */
++
++#ifndef __7Z_TYPES_H
++#define __7Z_TYPES_H
++
++#define SZ_OK 0
++
++#define SZ_ERROR_DATA 1
++#define SZ_ERROR_MEM 2
++#define SZ_ERROR_CRC 3
++#define SZ_ERROR_UNSUPPORTED 4
++#define SZ_ERROR_PARAM 5
++#define SZ_ERROR_INPUT_EOF 6
++#define SZ_ERROR_OUTPUT_EOF 7
++#define SZ_ERROR_READ 8
++#define SZ_ERROR_WRITE 9
++#define SZ_ERROR_PROGRESS 10
++#define SZ_ERROR_FAIL 11
++#define SZ_ERROR_THREAD 12
++
++#define SZ_ERROR_ARCHIVE 16
++#define SZ_ERROR_NO_ARCHIVE 17
++
++typedef int SRes;
++
++#ifndef RINOK
++#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
++#endif
++
++typedef unsigned char Byte;
++typedef short Int16;
++typedef unsigned short UInt16;
++
++#ifdef _LZMA_UINT32_IS_ULONG
++typedef long Int32;
++typedef unsigned long UInt32;
++#else
++typedef int Int32;
++typedef unsigned int UInt32;
++#endif
++
++/* #define _SZ_NO_INT_64 */
++/* define it if your compiler doesn't support 64-bit integers */
++
++#ifdef _SZ_NO_INT_64
++
++typedef long Int64;
++typedef unsigned long UInt64;
++
++#else
++
++#if defined(_MSC_VER) || defined(__BORLANDC__)
++typedef __int64 Int64;
++typedef unsigned __int64 UInt64;
++#else
++typedef long long int Int64;
++typedef unsigned long long int UInt64;
++#endif
++
++#endif
++
++#ifdef _LZMA_NO_SYSTEM_SIZE_T
++typedef UInt32 SizeT;
++#else
++#include <stddef.h>
++typedef size_t SizeT;
++#endif
++
++typedef int Bool;
++#define True 1
++#define False 0
++
++
++#ifdef _MSC_VER
++
++#if _MSC_VER >= 1300
++#define MY_NO_INLINE __declspec(noinline)
++#else
++#define MY_NO_INLINE
++#endif
++
++#define MY_CDECL __cdecl
++#define MY_STD_CALL __stdcall
++#define MY_FAST_CALL MY_NO_INLINE __fastcall
++
++#else
++
++#define MY_CDECL
++#define MY_STD_CALL
++#define MY_FAST_CALL
++
++#endif
++
++
++/* The following interfaces use first parameter as pointer to structure */
++
++typedef struct
++{
++ SRes (*Read)(void *p, void *buf, size_t *size);
++ /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
++ (output(*size) < input(*size)) is allowed */
++} ISeqInStream;
++
++typedef struct
++{
++ size_t (*Write)(void *p, const void *buf, size_t size);
++ /* Returns: result - the number of actually written bytes.
++ (result < size) means error */
++} ISeqOutStream;
++
++typedef struct
++{
++ SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
++ /* Returns: result. (result != SZ_OK) means break.
++ Value (UInt64)(Int64)-1 for size means unknown value. */
++} ICompressProgress;
++
++typedef struct
++{
++ void *(*Alloc)(void *p, size_t size);
++ void (*Free)(void *p, void *address); /* address can be 0 */
++} ISzAlloc;
++
++#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
++#define IAlloc_Free(p, a) (p)->Free((p), a)
++
++#endif
+--- /dev/null
++++ b/jffsX-utils/lzma/LzFind.c
+@@ -0,0 +1,753 @@
++/* LzFind.c -- Match finder for LZ algorithms
++2008-04-04
++Copyright (c) 1999-2008 Igor Pavlov
++Read LzFind.h for license options */
++
++#include <string.h>
++
++#include "LzFind.h"
++#include "LzHash.h"
++
++#define kEmptyHashValue 0
++#define kMaxValForNormalize ((UInt32)0xFFFFFFFF)
++#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */
++#define kNormalizeMask (~(kNormalizeStepMin - 1))
++#define kMaxHistorySize ((UInt32)3 << 30)
++
++#define kStartMaxLen 3
++
++static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc)
++{
++ if (!p->directInput)
++ {
++ alloc->Free(alloc, p->bufferBase);
++ p->bufferBase = 0;
++ }
++}
++
++/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */
++
++static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc)
++{
++ UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv;
++ if (p->directInput)
++ {
++ p->blockSize = blockSize;
++ return 1;
++ }
++ if (p->bufferBase == 0 || p->blockSize != blockSize)
++ {
++ LzInWindow_Free(p, alloc);
++ p->blockSize = blockSize;
++ p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize);
++ }
++ return (p->bufferBase != 0);
++}
++
++Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
++static Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; }
++
++static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; }
++
++void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue)
++{
++ p->posLimit -= subValue;
++ p->pos -= subValue;
++ p->streamPos -= subValue;
++}
++
++static void MatchFinder_ReadBlock(CMatchFinder *p)
++{
++ if (p->streamEndWasReached || p->result != SZ_OK)
++ return;
++ for (;;)
++ {
++ Byte *dest = p->buffer + (p->streamPos - p->pos);
++ size_t size = (p->bufferBase + p->blockSize - dest);
++ if (size == 0)
++ return;
++ p->result = p->stream->Read(p->stream, dest, &size);
++ if (p->result != SZ_OK)
++ return;
++ if (size == 0)
++ {
++ p->streamEndWasReached = 1;
++ return;
++ }
++ p->streamPos += (UInt32)size;
++ if (p->streamPos - p->pos > p->keepSizeAfter)
++ return;
++ }
++}
++
++void MatchFinder_MoveBlock(CMatchFinder *p)
++{
++ memmove(p->bufferBase,
++ p->buffer - p->keepSizeBefore,
++ (size_t)(p->streamPos - p->pos + p->keepSizeBefore));
++ p->buffer = p->bufferBase + p->keepSizeBefore;
++}
++
++int MatchFinder_NeedMove(CMatchFinder *p)
++{
++ /* if (p->streamEndWasReached) return 0; */
++ return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
++}
++
++void MatchFinder_ReadIfRequired(CMatchFinder *p)
++{
++ if (p->streamEndWasReached)
++ return;
++ if (p->keepSizeAfter >= p->streamPos - p->pos)
++ MatchFinder_ReadBlock(p);
++}
++
++static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p)
++{
++ if (MatchFinder_NeedMove(p))
++ MatchFinder_MoveBlock(p);
++ MatchFinder_ReadBlock(p);
++}
++
++static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
++{
++ p->cutValue = 32;
++ p->btMode = 1;
++ p->numHashBytes = 4;
++ /* p->skipModeBits = 0; */
++ p->directInput = 0;
++ p->bigHash = 0;
++}
++
++#define kCrcPoly 0xEDB88320
++
++void MatchFinder_Construct(CMatchFinder *p)
++{
++ UInt32 i;
++ p->bufferBase = 0;
++ p->directInput = 0;
++ p->hash = 0;
++ MatchFinder_SetDefaultSettings(p);
++
++ for (i = 0; i < 256; i++)
++ {
++ UInt32 r = i;
++ int j;
++ for (j = 0; j < 8; j++)
++ r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
++ p->crc[i] = r;
++ }
++}
++
++static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc)
++{
++ alloc->Free(alloc, p->hash);
++ p->hash = 0;
++}
++
++void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc)
++{
++ MatchFinder_FreeThisClassMemory(p, alloc);
++ LzInWindow_Free(p, alloc);
++}
++
++static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc)
++{
++ size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
++ if (sizeInBytes / sizeof(CLzRef) != num)
++ return 0;
++ return (CLzRef *)alloc->Alloc(alloc, sizeInBytes);
++}
++
++int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
++ UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
++ ISzAlloc *alloc)
++{
++ UInt32 sizeReserv;
++ if (historySize > kMaxHistorySize)
++ {
++ MatchFinder_Free(p, alloc);
++ return 0;
++ }
++ sizeReserv = historySize >> 1;
++ if (historySize > ((UInt32)2 << 30))
++ sizeReserv = historySize >> 2;
++ sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19);
++
++ p->keepSizeBefore = historySize + keepAddBufferBefore + 1;
++ p->keepSizeAfter = matchMaxLen + keepAddBufferAfter;
++ /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */
++ if (LzInWindow_Create(p, sizeReserv, alloc))
++ {
++ UInt32 newCyclicBufferSize = (historySize /* >> p->skipModeBits */) + 1;
++ UInt32 hs;
++ p->matchMaxLen = matchMaxLen;
++ {
++ p->fixedHashSize = 0;
++ if (p->numHashBytes == 2)
++ hs = (1 << 16) - 1;
++ else
++ {
++ hs = historySize - 1;
++ hs |= (hs >> 1);
++ hs |= (hs >> 2);
++ hs |= (hs >> 4);
++ hs |= (hs >> 8);
++ hs >>= 1;
++ /* hs >>= p->skipModeBits; */
++ hs |= 0xFFFF; /* don't change it! It's required for Deflate */
++ if (hs > (1 << 24))
++ {
++ if (p->numHashBytes == 3)
++ hs = (1 << 24) - 1;
++ else
++ hs >>= 1;
++ }
++ }
++ p->hashMask = hs;
++ hs++;
++ if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size;
++ if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size;
++ if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size;
++ hs += p->fixedHashSize;
++ }
++
++ {
++ UInt32 prevSize = p->hashSizeSum + p->numSons;
++ UInt32 newSize;
++ p->historySize = historySize;
++ p->hashSizeSum = hs;
++ p->cyclicBufferSize = newCyclicBufferSize;
++ p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize);
++ newSize = p->hashSizeSum + p->numSons;
++ if (p->hash != 0 && prevSize == newSize)
++ return 1;
++ MatchFinder_FreeThisClassMemory(p, alloc);
++ p->hash = AllocRefs(newSize, alloc);
++ if (p->hash != 0)
++ {
++ p->son = p->hash + p->hashSizeSum;
++ return 1;
++ }
++ }
++ }
++ MatchFinder_Free(p, alloc);
++ return 0;
++}
++
++static void MatchFinder_SetLimits(CMatchFinder *p)
++{
++ UInt32 limit = kMaxValForNormalize - p->pos;
++ UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos;
++ if (limit2 < limit)
++ limit = limit2;
++ limit2 = p->streamPos - p->pos;
++ if (limit2 <= p->keepSizeAfter)
++ {
++ if (limit2 > 0)
++ limit2 = 1;
++ }
++ else
++ limit2 -= p->keepSizeAfter;
++ if (limit2 < limit)
++ limit = limit2;
++ {
++ UInt32 lenLimit = p->streamPos - p->pos;
++ if (lenLimit > p->matchMaxLen)
++ lenLimit = p->matchMaxLen;
++ p->lenLimit = lenLimit;
++ }
++ p->posLimit = p->pos + limit;
++}
++
++void MatchFinder_Init(CMatchFinder *p)
++{
++ UInt32 i;
++ for(i = 0; i < p->hashSizeSum; i++)
++ p->hash[i] = kEmptyHashValue;
++ p->cyclicBufferPos = 0;
++ p->buffer = p->bufferBase;
++ p->pos = p->streamPos = p->cyclicBufferSize;
++ p->result = SZ_OK;
++ p->streamEndWasReached = 0;
++ MatchFinder_ReadBlock(p);
++ MatchFinder_SetLimits(p);
++}
++
++static UInt32 MatchFinder_GetSubValue(CMatchFinder *p)
++{
++ return (p->pos - p->historySize - 1) & kNormalizeMask;
++}
++
++void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems)
++{
++ UInt32 i;
++ for (i = 0; i < numItems; i++)
++ {
++ UInt32 value = items[i];
++ if (value <= subValue)
++ value = kEmptyHashValue;
++ else
++ value -= subValue;
++ items[i] = value;
++ }
++}
++
++static void MatchFinder_Normalize(CMatchFinder *p)
++{
++ UInt32 subValue = MatchFinder_GetSubValue(p);
++ MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons);
++ MatchFinder_ReduceOffsets(p, subValue);
++}
++
++static void MatchFinder_CheckLimits(CMatchFinder *p)
++{
++ if (p->pos == kMaxValForNormalize)
++ MatchFinder_Normalize(p);
++ if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos)
++ MatchFinder_CheckAndMoveAndRead(p);
++ if (p->cyclicBufferPos == p->cyclicBufferSize)
++ p->cyclicBufferPos = 0;
++ MatchFinder_SetLimits(p);
++}
++
++static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
++ UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
++ UInt32 *distances, UInt32 maxLen)
++{
++ son[_cyclicBufferPos] = curMatch;
++ for (;;)
++ {
++ UInt32 delta = pos - curMatch;
++ if (cutValue-- == 0 || delta >= _cyclicBufferSize)
++ return distances;
++ {
++ const Byte *pb = cur - delta;
++ curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)];
++ if (pb[maxLen] == cur[maxLen] && *pb == *cur)
++ {
++ UInt32 len = 0;
++ while(++len != lenLimit)
++ if (pb[len] != cur[len])
++ break;
++ if (maxLen < len)
++ {
++ *distances++ = maxLen = len;
++ *distances++ = delta - 1;
++ if (len == lenLimit)
++ return distances;
++ }
++ }
++ }
++ }
++}
++
++UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
++ UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
++ UInt32 *distances, UInt32 maxLen)
++{
++ CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
++ CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
++ UInt32 len0 = 0, len1 = 0;
++ for (;;)
++ {
++ UInt32 delta = pos - curMatch;
++ if (cutValue-- == 0 || delta >= _cyclicBufferSize)
++ {
++ *ptr0 = *ptr1 = kEmptyHashValue;
++ return distances;
++ }
++ {
++ CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
++ const Byte *pb = cur - delta;
++ UInt32 len = (len0 < len1 ? len0 : len1);
++ if (pb[len] == cur[len])
++ {
++ if (++len != lenLimit && pb[len] == cur[len])
++ while(++len != lenLimit)
++ if (pb[len] != cur[len])
++ break;
++ if (maxLen < len)
++ {
++ *distances++ = maxLen = len;
++ *distances++ = delta - 1;
++ if (len == lenLimit)
++ {
++ *ptr1 = pair[0];
++ *ptr0 = pair[1];
++ return distances;
++ }
++ }
++ }
++ if (pb[len] < cur[len])
++ {
++ *ptr1 = curMatch;
++ ptr1 = pair + 1;
++ curMatch = *ptr1;
++ len1 = len;
++ }
++ else
++ {
++ *ptr0 = curMatch;
++ ptr0 = pair;
++ curMatch = *ptr0;
++ len0 = len;
++ }
++ }
++ }
++}
++
++static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
++ UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue)
++{
++ CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1;
++ CLzRef *ptr1 = son + (_cyclicBufferPos << 1);
++ UInt32 len0 = 0, len1 = 0;
++ for (;;)
++ {
++ UInt32 delta = pos - curMatch;
++ if (cutValue-- == 0 || delta >= _cyclicBufferSize)
++ {
++ *ptr0 = *ptr1 = kEmptyHashValue;
++ return;
++ }
++ {
++ CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1);
++ const Byte *pb = cur - delta;
++ UInt32 len = (len0 < len1 ? len0 : len1);
++ if (pb[len] == cur[len])
++ {
++ while(++len != lenLimit)
++ if (pb[len] != cur[len])
++ break;
++ {
++ if (len == lenLimit)
++ {
++ *ptr1 = pair[0];
++ *ptr0 = pair[1];
++ return;
++ }
++ }
++ }
++ if (pb[len] < cur[len])
++ {
++ *ptr1 = curMatch;
++ ptr1 = pair + 1;
++ curMatch = *ptr1;
++ len1 = len;
++ }
++ else
++ {
++ *ptr0 = curMatch;
++ ptr0 = pair;
++ curMatch = *ptr0;
++ len0 = len;
++ }
++ }
++ }
++}
++
++#define MOVE_POS \
++ ++p->cyclicBufferPos; \
++ p->buffer++; \
++ if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p);
++
++#define MOVE_POS_RET MOVE_POS return offset;
++
++static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; }
++
++#define GET_MATCHES_HEADER2(minLen, ret_op) \
++ UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \
++ lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
++ cur = p->buffer;
++
++#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0)
++#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue)
++
++#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
++
++#define GET_MATCHES_FOOTER(offset, maxLen) \
++ offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \
++ distances + offset, maxLen) - distances); MOVE_POS_RET;
++
++#define SKIP_FOOTER \
++ SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS;
++
++static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 offset;
++ GET_MATCHES_HEADER(2)
++ HASH2_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ offset = 0;
++ GET_MATCHES_FOOTER(offset, 1)
++}
++
++UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 offset;
++ GET_MATCHES_HEADER(3)
++ HASH_ZIP_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ offset = 0;
++ GET_MATCHES_FOOTER(offset, 2)
++}
++
++static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 hash2Value, delta2, maxLen, offset;
++ GET_MATCHES_HEADER(3)
++
++ HASH3_CALC;
++
++ delta2 = p->pos - p->hash[hash2Value];
++ curMatch = p->hash[kFix3HashSize + hashValue];
++
++ p->hash[hash2Value] =
++ p->hash[kFix3HashSize + hashValue] = p->pos;
++
++
++ maxLen = 2;
++ offset = 0;
++ if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
++ {
++ for (; maxLen != lenLimit; maxLen++)
++ if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
++ break;
++ distances[0] = maxLen;
++ distances[1] = delta2 - 1;
++ offset = 2;
++ if (maxLen == lenLimit)
++ {
++ SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
++ MOVE_POS_RET;
++ }
++ }
++ GET_MATCHES_FOOTER(offset, maxLen)
++}
++
++static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
++ GET_MATCHES_HEADER(4)
++
++ HASH4_CALC;
++
++ delta2 = p->pos - p->hash[ hash2Value];
++ delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
++ curMatch = p->hash[kFix4HashSize + hashValue];
++
++ p->hash[ hash2Value] =
++ p->hash[kFix3HashSize + hash3Value] =
++ p->hash[kFix4HashSize + hashValue] = p->pos;
++
++ maxLen = 1;
++ offset = 0;
++ if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
++ {
++ distances[0] = maxLen = 2;
++ distances[1] = delta2 - 1;
++ offset = 2;
++ }
++ if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
++ {
++ maxLen = 3;
++ distances[offset + 1] = delta3 - 1;
++ offset += 2;
++ delta2 = delta3;
++ }
++ if (offset != 0)
++ {
++ for (; maxLen != lenLimit; maxLen++)
++ if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
++ break;
++ distances[offset - 2] = maxLen;
++ if (maxLen == lenLimit)
++ {
++ SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p));
++ MOVE_POS_RET;
++ }
++ }
++ if (maxLen < 3)
++ maxLen = 3;
++ GET_MATCHES_FOOTER(offset, maxLen)
++}
++
++static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset;
++ GET_MATCHES_HEADER(4)
++
++ HASH4_CALC;
++
++ delta2 = p->pos - p->hash[ hash2Value];
++ delta3 = p->pos - p->hash[kFix3HashSize + hash3Value];
++ curMatch = p->hash[kFix4HashSize + hashValue];
++
++ p->hash[ hash2Value] =
++ p->hash[kFix3HashSize + hash3Value] =
++ p->hash[kFix4HashSize + hashValue] = p->pos;
++
++ maxLen = 1;
++ offset = 0;
++ if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur)
++ {
++ distances[0] = maxLen = 2;
++ distances[1] = delta2 - 1;
++ offset = 2;
++ }
++ if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur)
++ {
++ maxLen = 3;
++ distances[offset + 1] = delta3 - 1;
++ offset += 2;
++ delta2 = delta3;
++ }
++ if (offset != 0)
++ {
++ for (; maxLen != lenLimit; maxLen++)
++ if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen])
++ break;
++ distances[offset - 2] = maxLen;
++ if (maxLen == lenLimit)
++ {
++ p->son[p->cyclicBufferPos] = curMatch;
++ MOVE_POS_RET;
++ }
++ }
++ if (maxLen < 3)
++ maxLen = 3;
++ offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
++ distances + offset, maxLen) - (distances));
++ MOVE_POS_RET
++}
++
++UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
++{
++ UInt32 offset;
++ GET_MATCHES_HEADER(3)
++ HASH_ZIP_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p),
++ distances, 2) - (distances));
++ MOVE_POS_RET
++}
++
++static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ SKIP_HEADER(2)
++ HASH2_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ SKIP_FOOTER
++ }
++ while (--num != 0);
++}
++
++void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ SKIP_HEADER(3)
++ HASH_ZIP_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ SKIP_FOOTER
++ }
++ while (--num != 0);
++}
++
++static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ UInt32 hash2Value;
++ SKIP_HEADER(3)
++ HASH3_CALC;
++ curMatch = p->hash[kFix3HashSize + hashValue];
++ p->hash[hash2Value] =
++ p->hash[kFix3HashSize + hashValue] = p->pos;
++ SKIP_FOOTER
++ }
++ while (--num != 0);
++}
++
++static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ UInt32 hash2Value, hash3Value;
++ SKIP_HEADER(4)
++ HASH4_CALC;
++ curMatch = p->hash[kFix4HashSize + hashValue];
++ p->hash[ hash2Value] =
++ p->hash[kFix3HashSize + hash3Value] = p->pos;
++ p->hash[kFix4HashSize + hashValue] = p->pos;
++ SKIP_FOOTER
++ }
++ while (--num != 0);
++}
++
++static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ UInt32 hash2Value, hash3Value;
++ SKIP_HEADER(4)
++ HASH4_CALC;
++ curMatch = p->hash[kFix4HashSize + hashValue];
++ p->hash[ hash2Value] =
++ p->hash[kFix3HashSize + hash3Value] =
++ p->hash[kFix4HashSize + hashValue] = p->pos;
++ p->son[p->cyclicBufferPos] = curMatch;
++ MOVE_POS
++ }
++ while (--num != 0);
++}
++
++void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
++{
++ do
++ {
++ SKIP_HEADER(3)
++ HASH_ZIP_CALC;
++ curMatch = p->hash[hashValue];
++ p->hash[hashValue] = p->pos;
++ p->son[p->cyclicBufferPos] = curMatch;
++ MOVE_POS
++ }
++ while (--num != 0);
++}
++
++void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable)
++{
++ vTable->Init = (Mf_Init_Func)MatchFinder_Init;
++ vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte;
++ vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes;
++ vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos;
++ if (!p->btMode)
++ {
++ vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches;
++ vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip;
++ }
++ else if (p->numHashBytes == 2)
++ {
++ vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches;
++ vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip;
++ }
++ else if (p->numHashBytes == 3)
++ {
++ vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches;
++ vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip;
++ }
++ else
++ {
++ vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches;
++ vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip;
++ }
++}
+--- /dev/null
++++ b/jffsX-utils/lzma/LzmaDec.c
+@@ -0,0 +1,1014 @@
++/* LzmaDec.c -- LZMA Decoder
++2008-04-29
++Copyright (c) 1999-2008 Igor Pavlov
++Read LzmaDec.h for license options */
++
++#include "LzmaDec.h"
++
++#include <string.h>
++
++#define kNumTopBits 24
++#define kTopValue ((UInt32)1 << kNumTopBits)
++
++#define kNumBitModelTotalBits 11
++#define kBitModelTotal (1 << kNumBitModelTotalBits)
++#define kNumMoveBits 5
++
++#define RC_INIT_SIZE 5
++
++#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
++
++#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
++#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
++#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
++#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
++ { UPDATE_0(p); i = (i + i); A0; } else \
++ { UPDATE_1(p); i = (i + i) + 1; A1; }
++#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;)
++
++#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); }
++#define TREE_DECODE(probs, limit, i) \
++ { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
++
++/* #define _LZMA_SIZE_OPT */
++
++#ifdef _LZMA_SIZE_OPT
++#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
++#else
++#define TREE_6_DECODE(probs, i) \
++ { i = 1; \
++ TREE_GET_BIT(probs, i); \
++ TREE_GET_BIT(probs, i); \
++ TREE_GET_BIT(probs, i); \
++ TREE_GET_BIT(probs, i); \
++ TREE_GET_BIT(probs, i); \
++ TREE_GET_BIT(probs, i); \
++ i -= 0x40; }
++#endif
++
++#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); }
++
++#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
++#define UPDATE_0_CHECK range = bound;
++#define UPDATE_1_CHECK range -= bound; code -= bound;
++#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
++ { UPDATE_0_CHECK; i = (i + i); A0; } else \
++ { UPDATE_1_CHECK; i = (i + i) + 1; A1; }
++#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
++#define TREE_DECODE_CHECK(probs, limit, i) \
++ { i = 1; do { GET_BIT_CHECK(probs + i, i) } while(i < limit); i -= limit; }
++
++
++#define kNumPosBitsMax 4
++#define kNumPosStatesMax (1 << kNumPosBitsMax)
++
++#define kLenNumLowBits 3
++#define kLenNumLowSymbols (1 << kLenNumLowBits)
++#define kLenNumMidBits 3
++#define kLenNumMidSymbols (1 << kLenNumMidBits)
++#define kLenNumHighBits 8
++#define kLenNumHighSymbols (1 << kLenNumHighBits)
++
++#define LenChoice 0
++#define LenChoice2 (LenChoice + 1)
++#define LenLow (LenChoice2 + 1)
++#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
++#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
++#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
++
++
++#define kNumStates 12
++#define kNumLitStates 7
++
++#define kStartPosModelIndex 4
++#define kEndPosModelIndex 14
++#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
++
++#define kNumPosSlotBits 6
++#define kNumLenToPosStates 4
++
++#define kNumAlignBits 4
++#define kAlignTableSize (1 << kNumAlignBits)
++
++#define kMatchMinLen 2
++#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
++
++#define IsMatch 0
++#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
++#define IsRepG0 (IsRep + kNumStates)
++#define IsRepG1 (IsRepG0 + kNumStates)
++#define IsRepG2 (IsRepG1 + kNumStates)
++#define IsRep0Long (IsRepG2 + kNumStates)
++#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
++#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
++#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
++#define LenCoder (Align + kAlignTableSize)
++#define RepLenCoder (LenCoder + kNumLenProbs)
++#define Literal (RepLenCoder + kNumLenProbs)
++
++#define LZMA_BASE_SIZE 1846
++#define LZMA_LIT_SIZE 768
++
++#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp)))
++
++#if Literal != LZMA_BASE_SIZE
++StopCompilingDueBUG
++#endif
++
++/*
++#define LZMA_STREAM_WAS_FINISHED_ID (-1)
++#define LZMA_SPEC_LEN_OFFSET (-3)
++*/
++
++Byte kLiteralNextStates[kNumStates * 2] =
++{
++ 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5,
++ 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10
++};
++
++#define LZMA_DIC_MIN (1 << 12)
++
++/* First LZMA-symbol is always decoded.
++And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization
++Out:
++ Result:
++ 0 - OK
++ 1 - Error
++ p->remainLen:
++ < kMatchSpecLenStart : normal remain
++ = kMatchSpecLenStart : finished
++ = kMatchSpecLenStart + 1 : Flush marker
++ = kMatchSpecLenStart + 2 : State Init Marker
++*/
++
++static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
++{
++ CLzmaProb *probs = p->probs;
++
++ unsigned state = p->state;
++ UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3];
++ unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1;
++ unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1;
++ unsigned lc = p->prop.lc;
++
++ Byte *dic = p->dic;
++ SizeT dicBufSize = p->dicBufSize;
++ SizeT dicPos = p->dicPos;
++
++ UInt32 processedPos = p->processedPos;
++ UInt32 checkDicSize = p->checkDicSize;
++ unsigned len = 0;
++
++ const Byte *buf = p->buf;
++ UInt32 range = p->range;
++ UInt32 code = p->code;
++
++ do
++ {
++ CLzmaProb *prob;
++ UInt32 bound;
++ unsigned ttt;
++ unsigned posState = processedPos & pbMask;
++
++ prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
++ IF_BIT_0(prob)
++ {
++ unsigned symbol;
++ UPDATE_0(prob);
++ prob = probs + Literal;
++ if (checkDicSize != 0 || processedPos != 0)
++ prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) +
++ (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc))));
++
++ if (state < kNumLitStates)
++ {
++ symbol = 1;
++ do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100);
++ }
++ else
++ {
++ unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
++ unsigned offs = 0x100;
++ symbol = 1;
++ do
++ {
++ unsigned bit;
++ CLzmaProb *probLit;
++ matchByte <<= 1;
++ bit = (matchByte & offs);
++ probLit = prob + offs + bit + symbol;
++ GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit)
++ }
++ while (symbol < 0x100);
++ }
++ dic[dicPos++] = (Byte)symbol;
++ processedPos++;
++
++ state = kLiteralNextStates[state];
++ /* if (state < 4) state = 0; else if (state < 10) state -= 3; else state -= 6; */
++ continue;
++ }
++ else
++ {
++ UPDATE_1(prob);
++ prob = probs + IsRep + state;
++ IF_BIT_0(prob)
++ {
++ UPDATE_0(prob);
++ state += kNumStates;
++ prob = probs + LenCoder;
++ }
++ else
++ {
++ UPDATE_1(prob);
++ if (checkDicSize == 0 && processedPos == 0)
++ return SZ_ERROR_DATA;
++ prob = probs + IsRepG0 + state;
++ IF_BIT_0(prob)
++ {
++ UPDATE_0(prob);
++ prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
++ IF_BIT_0(prob)
++ {
++ UPDATE_0(prob);
++ dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
++ dicPos++;
++ processedPos++;
++ state = state < kNumLitStates ? 9 : 11;
++ continue;
++ }
++ UPDATE_1(prob);
++ }
++ else
++ {
++ UInt32 distance;
++ UPDATE_1(prob);
++ prob = probs + IsRepG1 + state;
++ IF_BIT_0(prob)
++ {
++ UPDATE_0(prob);
++ distance = rep1;
++ }
++ else
++ {
++ UPDATE_1(prob);
++ prob = probs + IsRepG2 + state;
++ IF_BIT_0(prob)
++ {
++ UPDATE_0(prob);
++ distance = rep2;
++ }
++ else
++ {
++ UPDATE_1(prob);
++ distance = rep3;
++ rep3 = rep2;
++ }
++ rep2 = rep1;
++ }
++ rep1 = rep0;
++ rep0 = distance;
++ }
++ state = state < kNumLitStates ? 8 : 11;
++ prob = probs + RepLenCoder;
++ }
++ {
++ unsigned limit, offset;
++ CLzmaProb *probLen = prob + LenChoice;
++ IF_BIT_0(probLen)
++ {
++ UPDATE_0(probLen);
++ probLen = prob + LenLow + (posState << kLenNumLowBits);
++ offset = 0;
++ limit = (1 << kLenNumLowBits);
++ }
++ else
++ {
++ UPDATE_1(probLen);
++ probLen = prob + LenChoice2;
++ IF_BIT_0(probLen)
++ {
++ UPDATE_0(probLen);
++ probLen = prob + LenMid + (posState << kLenNumMidBits);
++ offset = kLenNumLowSymbols;
++ limit = (1 << kLenNumMidBits);
++ }
++ else
++ {
++ UPDATE_1(probLen);
++ probLen = prob + LenHigh;
++ offset = kLenNumLowSymbols + kLenNumMidSymbols;
++ limit = (1 << kLenNumHighBits);
++ }
++ }
++ TREE_DECODE(probLen, limit, len);
++ len += offset;
++ }
++
++ if (state >= kNumStates)
++ {
++ UInt32 distance;
++ prob = probs + PosSlot +
++ ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
++ TREE_6_DECODE(prob, distance);
++ if (distance >= kStartPosModelIndex)
++ {
++ unsigned posSlot = (unsigned)distance;
++ int numDirectBits = (int)(((distance >> 1) - 1));
++ distance = (2 | (distance & 1));
++ if (posSlot < kEndPosModelIndex)
++ {
++ distance <<= numDirectBits;
++ prob = probs + SpecPos + distance - posSlot - 1;
++ {
++ UInt32 mask = 1;
++ unsigned i = 1;
++ do
++ {
++ GET_BIT2(prob + i, i, ; , distance |= mask);
++ mask <<= 1;
++ }
++ while(--numDirectBits != 0);
++ }
++ }
++ else
++ {
++ numDirectBits -= kNumAlignBits;
++ do
++ {
++ NORMALIZE
++ range >>= 1;
++
++ {
++ UInt32 t;
++ code -= range;
++ t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */
++ distance = (distance << 1) + (t + 1);
++ code += range & t;
++ }
++ /*
++ distance <<= 1;
++ if (code >= range)
++ {
++ code -= range;
++ distance |= 1;
++ }
++ */
++ }
++ while (--numDirectBits != 0);
++ prob = probs + Align;
++ distance <<= kNumAlignBits;
++ {
++ unsigned i = 1;
++ GET_BIT2(prob + i, i, ; , distance |= 1);
++ GET_BIT2(prob + i, i, ; , distance |= 2);
++ GET_BIT2(prob + i, i, ; , distance |= 4);
++ GET_BIT2(prob + i, i, ; , distance |= 8);
++ }
++ if (distance == (UInt32)0xFFFFFFFF)
++ {
++ len += kMatchSpecLenStart;
++ state -= kNumStates;
++ break;
++ }
++ }
++ }
++ rep3 = rep2;
++ rep2 = rep1;
++ rep1 = rep0;
++ rep0 = distance + 1;
++ if (checkDicSize == 0)
++ {
++ if (distance >= processedPos)
++ return SZ_ERROR_DATA;
++ }
++ else if (distance >= checkDicSize)
++ return SZ_ERROR_DATA;
++ state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3;
++ /* state = kLiteralNextStates[state]; */
++ }
++
++ len += kMatchMinLen;
++
++ {
++ SizeT rem = limit - dicPos;
++ unsigned curLen = ((rem < len) ? (unsigned)rem : len);
++ SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0);
++
++ processedPos += curLen;
++
++ len -= curLen;
++ if (pos + curLen <= dicBufSize)
++ {
++ Byte *dest = dic + dicPos;
++ ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos;
++ const Byte *lim = dest + curLen;
++ dicPos += curLen;
++ do
++ *(dest) = (Byte)*(dest + src);
++ while (++dest != lim);
++ }
++ else
++ {
++ do
++ {
++ dic[dicPos++] = dic[pos];
++ if (++pos == dicBufSize)
++ pos = 0;
++ }
++ while (--curLen != 0);
++ }
++ }
++ }
++ }
++ while (dicPos < limit && buf < bufLimit);
++ NORMALIZE;
++ p->buf = buf;
++ p->range = range;
++ p->code = code;
++ p->remainLen = len;
++ p->dicPos = dicPos;
++ p->processedPos = processedPos;
++ p->reps[0] = rep0;
++ p->reps[1] = rep1;
++ p->reps[2] = rep2;
++ p->reps[3] = rep3;
++ p->state = state;
++
++ return SZ_OK;
++}
++
++static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
++{
++ if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart)
++ {
++ Byte *dic = p->dic;
++ SizeT dicPos = p->dicPos;
++ SizeT dicBufSize = p->dicBufSize;
++ unsigned len = p->remainLen;
++ UInt32 rep0 = p->reps[0];
++ if (limit - dicPos < len)
++ len = (unsigned)(limit - dicPos);
++
++ if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len)
++ p->checkDicSize = p->prop.dicSize;
++
++ p->processedPos += len;
++ p->remainLen -= len;
++ while (len-- != 0)
++ {
++ dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)];
++ dicPos++;
++ }
++ p->dicPos = dicPos;
++ }
++}
++
++/* LzmaDec_DecodeReal2 decodes LZMA-symbols and sets p->needFlush and p->needInit, if required. */
++
++static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
++{
++ do
++ {
++ SizeT limit2 = limit;
++ if (p->checkDicSize == 0)
++ {
++ UInt32 rem = p->prop.dicSize - p->processedPos;
++ if (limit - p->dicPos > rem)
++ limit2 = p->dicPos + rem;
++ }
++ RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit));
++ if (p->processedPos >= p->prop.dicSize)
++ p->checkDicSize = p->prop.dicSize;
++ LzmaDec_WriteRem(p, limit);
++ }
++ while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart);
++
++ if (p->remainLen > kMatchSpecLenStart)
++ {
++ p->remainLen = kMatchSpecLenStart;
++ }
++ return 0;
++}
++
++typedef enum
++{
++ DUMMY_ERROR, /* unexpected end of input stream */
++ DUMMY_LIT,
++ DUMMY_MATCH,
++ DUMMY_REP
++} ELzmaDummy;
++
++static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize)
++{
++ UInt32 range = p->range;
++ UInt32 code = p->code;
++ const Byte *bufLimit = buf + inSize;
++ CLzmaProb *probs = p->probs;
++ unsigned state = p->state;
++ ELzmaDummy res;
++
++ {
++ CLzmaProb *prob;
++ UInt32 bound;
++ unsigned ttt;
++ unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1);
++
++ prob = probs + IsMatch + (state << kNumPosBitsMax) + posState;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK
++
++ /* if (bufLimit - buf >= 7) return DUMMY_LIT; */
++
++ prob = probs + Literal;
++ if (p->checkDicSize != 0 || p->processedPos != 0)
++ prob += (LZMA_LIT_SIZE *
++ ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) +
++ (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc))));
++
++ if (state < kNumLitStates)
++ {
++ unsigned symbol = 1;
++ do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100);
++ }
++ else
++ {
++ unsigned matchByte = p->dic[p->dicPos - p->reps[0] +
++ ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)];
++ unsigned offs = 0x100;
++ unsigned symbol = 1;
++ do
++ {
++ unsigned bit;
++ CLzmaProb *probLit;
++ matchByte <<= 1;
++ bit = (matchByte & offs);
++ probLit = prob + offs + bit + symbol;
++ GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit)
++ }
++ while (symbol < 0x100);
++ }
++ res = DUMMY_LIT;
++ }
++ else
++ {
++ unsigned len;
++ UPDATE_1_CHECK;
++
++ prob = probs + IsRep + state;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK;
++ state = 0;
++ prob = probs + LenCoder;
++ res = DUMMY_MATCH;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ res = DUMMY_REP;
++ prob = probs + IsRepG0 + state;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK;
++ prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK;
++ NORMALIZE_CHECK;
++ return DUMMY_REP;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ }
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ prob = probs + IsRepG1 + state;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ prob = probs + IsRepG2 + state;
++ IF_BIT_0_CHECK(prob)
++ {
++ UPDATE_0_CHECK;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ }
++ }
++ }
++ state = kNumStates;
++ prob = probs + RepLenCoder;
++ }
++ {
++ unsigned limit, offset;
++ CLzmaProb *probLen = prob + LenChoice;
++ IF_BIT_0_CHECK(probLen)
++ {
++ UPDATE_0_CHECK;
++ probLen = prob + LenLow + (posState << kLenNumLowBits);
++ offset = 0;
++ limit = 1 << kLenNumLowBits;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ probLen = prob + LenChoice2;
++ IF_BIT_0_CHECK(probLen)
++ {
++ UPDATE_0_CHECK;
++ probLen = prob + LenMid + (posState << kLenNumMidBits);
++ offset = kLenNumLowSymbols;
++ limit = 1 << kLenNumMidBits;
++ }
++ else
++ {
++ UPDATE_1_CHECK;
++ probLen = prob + LenHigh;
++ offset = kLenNumLowSymbols + kLenNumMidSymbols;
++ limit = 1 << kLenNumHighBits;
++ }
++ }
++ TREE_DECODE_CHECK(probLen, limit, len);
++ len += offset;
++ }
++
++ if (state < 4)
++ {
++ unsigned posSlot;
++ prob = probs + PosSlot +
++ ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
++ kNumPosSlotBits);
++ TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot);
++ if (posSlot >= kStartPosModelIndex)
++ {
++ int numDirectBits = ((posSlot >> 1) - 1);
++
++ /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */
++
++ if (posSlot < kEndPosModelIndex)
++ {
++ prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1;
++ }
++ else
++ {
++ numDirectBits -= kNumAlignBits;
++ do
++ {
++ NORMALIZE_CHECK
++ range >>= 1;
++ code -= range & (((code - range) >> 31) - 1);
++ /* if (code >= range) code -= range; */
++ }
++ while (--numDirectBits != 0);
++ prob = probs + Align;
++ numDirectBits = kNumAlignBits;
++ }
++ {
++ unsigned i = 1;
++ do
++ {
++ GET_BIT_CHECK(prob + i, i);
++ }
++ while(--numDirectBits != 0);
++ }
++ }
++ }
++ }
++ }
++ NORMALIZE_CHECK;
++ return res;
++}
++
++
++static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data)
++{
++ p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]);
++ p->range = 0xFFFFFFFF;
++ p->needFlush = 0;
++}
++
++static void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState)
++{
++ p->needFlush = 1;
++ p->remainLen = 0;
++ p->tempBufSize = 0;
++
++ if (initDic)
++ {
++ p->processedPos = 0;
++ p->checkDicSize = 0;
++ p->needInitState = 1;
++ }
++ if (initState)
++ p->needInitState = 1;
++}
++
++void LzmaDec_Init(CLzmaDec *p)
++{
++ p->dicPos = 0;
++ LzmaDec_InitDicAndState(p, True, True);
++}
++
++static void LzmaDec_InitStateReal(CLzmaDec *p)
++{
++ UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp));
++ UInt32 i;
++ CLzmaProb *probs = p->probs;
++ for (i = 0; i < numProbs; i++)
++ probs[i] = kBitModelTotal >> 1;
++ p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1;
++ p->state = 0;
++ p->needInitState = 0;
++}
++
++SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen,
++ ELzmaFinishMode finishMode, ELzmaStatus *status)
++{
++ SizeT inSize = *srcLen;
++ (*srcLen) = 0;
++ LzmaDec_WriteRem(p, dicLimit);
++
++ *status = LZMA_STATUS_NOT_SPECIFIED;
++
++ while (p->remainLen != kMatchSpecLenStart)
++ {
++ int checkEndMarkNow;
++
++ if (p->needFlush != 0)
++ {
++ for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--)
++ p->tempBuf[p->tempBufSize++] = *src++;
++ if (p->tempBufSize < RC_INIT_SIZE)
++ {
++ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
++ return SZ_OK;
++ }
++ if (p->tempBuf[0] != 0)
++ return SZ_ERROR_DATA;
++
++ LzmaDec_InitRc(p, p->tempBuf);
++ p->tempBufSize = 0;
++ }
++
++ checkEndMarkNow = 0;
++ if (p->dicPos >= dicLimit)
++ {
++ if (p->remainLen == 0 && p->code == 0)
++ {
++ *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK;
++ return SZ_OK;
++ }
++ if (finishMode == LZMA_FINISH_ANY)
++ {
++ *status = LZMA_STATUS_NOT_FINISHED;
++ return SZ_OK;
++ }
++ if (p->remainLen != 0)
++ {
++ *status = LZMA_STATUS_NOT_FINISHED;
++ return SZ_ERROR_DATA;
++ }
++ checkEndMarkNow = 1;
++ }
++
++ if (p->needInitState)
++ LzmaDec_InitStateReal(p);
++
++ if (p->tempBufSize == 0)
++ {
++ SizeT processed;
++ const Byte *bufLimit;
++ if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
++ {
++ int dummyRes = LzmaDec_TryDummy(p, src, inSize);
++ if (dummyRes == DUMMY_ERROR)
++ {
++ memcpy(p->tempBuf, src, inSize);
++ p->tempBufSize = (unsigned)inSize;
++ (*srcLen) += inSize;
++ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
++ return SZ_OK;
++ }
++ if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
++ {
++ *status = LZMA_STATUS_NOT_FINISHED;
++ return SZ_ERROR_DATA;
++ }
++ bufLimit = src;
++ }
++ else
++ bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX;
++ p->buf = src;
++ if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0)
++ return SZ_ERROR_DATA;
++ processed = p->buf - src;
++ (*srcLen) += processed;
++ src += processed;
++ inSize -= processed;
++ }
++ else
++ {
++ unsigned rem = p->tempBufSize, lookAhead = 0;
++ while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize)
++ p->tempBuf[rem++] = src[lookAhead++];
++ p->tempBufSize = rem;
++ if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow)
++ {
++ int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem);
++ if (dummyRes == DUMMY_ERROR)
++ {
++ (*srcLen) += lookAhead;
++ *status = LZMA_STATUS_NEEDS_MORE_INPUT;
++ return SZ_OK;
++ }
++ if (checkEndMarkNow && dummyRes != DUMMY_MATCH)
++ {
++ *status = LZMA_STATUS_NOT_FINISHED;
++ return SZ_ERROR_DATA;
++ }
++ }
++ p->buf = p->tempBuf;
++ if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0)
++ return SZ_ERROR_DATA;
++ lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf));
++ (*srcLen) += lookAhead;
++ src += lookAhead;
++ inSize -= lookAhead;
++ p->tempBufSize = 0;
++ }
++ }
++ if (p->code == 0)
++ *status = LZMA_STATUS_FINISHED_WITH_MARK;
++ return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA;
++}
++
++SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
++{
++ SizeT outSize = *destLen;
++ SizeT inSize = *srcLen;
++ *srcLen = *destLen = 0;
++ for (;;)
++ {
++ SizeT inSizeCur = inSize, outSizeCur, dicPos;
++ ELzmaFinishMode curFinishMode;
++ SRes res;
++ if (p->dicPos == p->dicBufSize)
++ p->dicPos = 0;
++ dicPos = p->dicPos;
++ if (outSize > p->dicBufSize - dicPos)
++ {
++ outSizeCur = p->dicBufSize;
++ curFinishMode = LZMA_FINISH_ANY;
++ }
++ else
++ {
++ outSizeCur = dicPos + outSize;
++ curFinishMode = finishMode;
++ }
++
++ res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status);
++ src += inSizeCur;
++ inSize -= inSizeCur;
++ *srcLen += inSizeCur;
++ outSizeCur = p->dicPos - dicPos;
++ memcpy(dest, p->dic + dicPos, outSizeCur);
++ dest += outSizeCur;
++ outSize -= outSizeCur;
++ *destLen += outSizeCur;
++ if (res != 0)
++ return res;
++ if (outSizeCur == 0 || outSize == 0)
++ return SZ_OK;
++ }
++}
++
++void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc)
++{
++ alloc->Free(alloc, p->probs);
++ p->probs = 0;
++}
++
++static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc)
++{
++ alloc->Free(alloc, p->dic);
++ p->dic = 0;
++}
++
++void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc)
++{
++ LzmaDec_FreeProbs(p, alloc);
++ LzmaDec_FreeDict(p, alloc);
++}
++
++SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size)
++{
++ UInt32 dicSize;
++ Byte d;
++
++ if (size < LZMA_PROPS_SIZE)
++ return SZ_ERROR_UNSUPPORTED;
++ else
++ dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24);
++
++ if (dicSize < LZMA_DIC_MIN)
++ dicSize = LZMA_DIC_MIN;
++ p->dicSize = dicSize;
++
++ d = data[0];
++ if (d >= (9 * 5 * 5))
++ return SZ_ERROR_UNSUPPORTED;
++
++ p->lc = d % 9;
++ d /= 9;
++ p->pb = d / 5;
++ p->lp = d % 5;
++
++ return SZ_OK;
++}
++
++static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc)
++{
++ UInt32 numProbs = LzmaProps_GetNumProbs(propNew);
++ if (p->probs == 0 || numProbs != p->numProbs)
++ {
++ LzmaDec_FreeProbs(p, alloc);
++ p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb));
++ p->numProbs = numProbs;
++ if (p->probs == 0)
++ return SZ_ERROR_MEM;
++ }
++ return SZ_OK;
++}
++
++SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
++{
++ CLzmaProps propNew;
++ RINOK(LzmaProps_Decode(&propNew, props, propsSize));
++ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
++ p->prop = propNew;
++ return SZ_OK;
++}
++
++SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc)
++{
++ CLzmaProps propNew;
++ SizeT dicBufSize;
++ RINOK(LzmaProps_Decode(&propNew, props, propsSize));
++ RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc));
++ dicBufSize = propNew.dicSize;
++ if (p->dic == 0 || dicBufSize != p->dicBufSize)
++ {
++ LzmaDec_FreeDict(p, alloc);
++ p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize);
++ if (p->dic == 0)
++ {
++ LzmaDec_FreeProbs(p, alloc);
++ return SZ_ERROR_MEM;
++ }
++ }
++ p->dicBufSize = dicBufSize;
++ p->prop = propNew;
++ return SZ_OK;
++}
++
++SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
++ const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
++ ELzmaStatus *status, ISzAlloc *alloc)
++{
++ CLzmaDec p;
++ SRes res;
++ SizeT inSize = *srcLen;
++ SizeT outSize = *destLen;
++ *srcLen = *destLen = 0;
++ if (inSize < RC_INIT_SIZE)
++ return SZ_ERROR_INPUT_EOF;
++
++ LzmaDec_Construct(&p);
++ res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc);
++ if (res != 0)
++ return res;
++ p.dic = dest;
++ p.dicBufSize = outSize;
++
++ LzmaDec_Init(&p);
++
++ *srcLen = inSize;
++ res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status);
++
++ if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
++ res = SZ_ERROR_INPUT_EOF;
++
++ (*destLen) = p.dicPos;
++ LzmaDec_FreeProbs(&p, alloc);
++ return res;
++}
+--- /dev/null
++++ b/jffsX-utils/lzma/LzmaEnc.c
+@@ -0,0 +1,2335 @@
++/* LzmaEnc.c -- LZMA Encoder
++2008-04-28
++Copyright (c) 1999-2008 Igor Pavlov
++Read LzmaEnc.h for license options */
++
++#if defined(SHOW_STAT) || defined(SHOW_STAT2)
++#include <stdio.h>
++#endif
++
++#include <string.h>
++
++#include "LzmaEnc.h"
++
++#include "LzFind.h"
++#ifdef COMPRESS_MF_MT
++#include "LzFindMt.h"
++#endif
++
++/* #define SHOW_STAT */
++/* #define SHOW_STAT2 */
++
++#ifdef SHOW_STAT
++static int ttt = 0;
++#endif
++
++#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
++
++#define kBlockSize (9 << 10)
++#define kUnpackBlockSize (1 << 18)
++#define kMatchArraySize (1 << 21)
++#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
++
++#define kNumMaxDirectBits (31)
++
++#define kNumTopBits 24
++#define kTopValue ((UInt32)1 << kNumTopBits)
++
++#define kNumBitModelTotalBits 11
++#define kBitModelTotal (1 << kNumBitModelTotalBits)
++#define kNumMoveBits 5
++#define kProbInitValue (kBitModelTotal >> 1)
++
++#define kNumMoveReducingBits 4
++#define kNumBitPriceShiftBits 4
++#define kBitPrice (1 << kNumBitPriceShiftBits)
++
++void LzmaEncProps_Init(CLzmaEncProps *p)
++{
++ p->level = 5;
++ p->dictSize = p->mc = 0;
++ p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
++ p->writeEndMark = 0;
++}
++
++void LzmaEncProps_Normalize(CLzmaEncProps *p)
++{
++ int level = p->level;
++ if (level < 0) level = 5;
++ p->level = level;
++ if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
++ if (p->lc < 0) p->lc = 3;
++ if (p->lp < 0) p->lp = 0;
++ if (p->pb < 0) p->pb = 2;
++ if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
++ if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
++ if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
++ if (p->numHashBytes < 0) p->numHashBytes = 4;
++ if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
++ if (p->numThreads < 0) p->numThreads = ((p->btMode && p->algo) ? 2 : 1);
++}
++
++UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
++{
++ CLzmaEncProps props = *props2;
++ LzmaEncProps_Normalize(&props);
++ return props.dictSize;
++}
++
++/* #define LZMA_LOG_BSR */
++/* Define it for Intel's CPU */
++
++
++#ifdef LZMA_LOG_BSR
++
++#define kDicLogSizeMaxCompress 30
++
++#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
++
++UInt32 GetPosSlot1(UInt32 pos)
++{
++ UInt32 res;
++ BSR2_RET(pos, res);
++ return res;
++}
++#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
++#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
++
++#else
++
++#define kNumLogBits (9 + (int)sizeof(size_t) / 2)
++#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
++
++static void LzmaEnc_FastPosInit(Byte *g_FastPos)
++{
++ int c = 2, slotFast;
++ g_FastPos[0] = 0;
++ g_FastPos[1] = 1;
++
++ for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
++ {
++ UInt32 k = (1 << ((slotFast >> 1) - 1));
++ UInt32 j;
++ for (j = 0; j < k; j++, c++)
++ g_FastPos[c] = (Byte)slotFast;
++ }
++}
++
++#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \
++ (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
++ res = p->g_FastPos[pos >> i] + (i * 2); }
++/*
++#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
++ p->g_FastPos[pos >> 6] + 12 : \
++ p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
++*/
++
++#define GetPosSlot1(pos) p->g_FastPos[pos]
++#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
++#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
++
++#endif
++
++
++#define LZMA_NUM_REPS 4
++
++typedef unsigned CState;
++
++typedef struct _COptimal
++{
++ UInt32 price;
++
++ CState state;
++ int prev1IsChar;
++ int prev2;
++
++ UInt32 posPrev2;
++ UInt32 backPrev2;
++
++ UInt32 posPrev;
++ UInt32 backPrev;
++ UInt32 backs[LZMA_NUM_REPS];
++} COptimal;
++
++#define kNumOpts (1 << 12)
++
++#define kNumLenToPosStates 4
++#define kNumPosSlotBits 6
++#define kDicLogSizeMin 0
++#define kDicLogSizeMax 32
++#define kDistTableSizeMax (kDicLogSizeMax * 2)
++
++
++#define kNumAlignBits 4
++#define kAlignTableSize (1 << kNumAlignBits)
++#define kAlignMask (kAlignTableSize - 1)
++
++#define kStartPosModelIndex 4
++#define kEndPosModelIndex 14
++#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
++
++#define kNumFullDistances (1 << (kEndPosModelIndex / 2))
++
++#ifdef _LZMA_PROB32
++#define CLzmaProb UInt32
++#else
++#define CLzmaProb UInt16
++#endif
++
++#define LZMA_PB_MAX 4
++#define LZMA_LC_MAX 8
++#define LZMA_LP_MAX 4
++
++#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
++
++
++#define kLenNumLowBits 3
++#define kLenNumLowSymbols (1 << kLenNumLowBits)
++#define kLenNumMidBits 3
++#define kLenNumMidSymbols (1 << kLenNumMidBits)
++#define kLenNumHighBits 8
++#define kLenNumHighSymbols (1 << kLenNumHighBits)
++
++#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
++
++#define LZMA_MATCH_LEN_MIN 2
++#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
++
++#define kNumStates 12
++
++typedef struct
++{
++ CLzmaProb choice;
++ CLzmaProb choice2;
++ CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
++ CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
++ CLzmaProb high[kLenNumHighSymbols];
++} CLenEnc;
++
++typedef struct
++{
++ CLenEnc p;
++ UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
++ UInt32 tableSize;
++ UInt32 counters[LZMA_NUM_PB_STATES_MAX];
++} CLenPriceEnc;
++
++typedef struct _CRangeEnc
++{
++ UInt32 range;
++ Byte cache;
++ UInt64 low;
++ UInt64 cacheSize;
++ Byte *buf;
++ Byte *bufLim;
++ Byte *bufBase;
++ ISeqOutStream *outStream;
++ UInt64 processed;
++ SRes res;
++} CRangeEnc;
++
++typedef struct _CSeqInStreamBuf
++{
++ ISeqInStream funcTable;
++ const Byte *data;
++ SizeT rem;
++} CSeqInStreamBuf;
++
++static SRes MyRead(void *pp, void *data, size_t *size)
++{
++ size_t curSize = *size;
++ CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp;
++ if (p->rem < curSize)
++ curSize = p->rem;
++ memcpy(data, p->data, curSize);
++ p->rem -= curSize;
++ p->data += curSize;
++ *size = curSize;
++ return SZ_OK;
++}
++
++typedef struct
++{
++ CLzmaProb *litProbs;
++
++ CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
++ CLzmaProb isRep[kNumStates];
++ CLzmaProb isRepG0[kNumStates];
++ CLzmaProb isRepG1[kNumStates];
++ CLzmaProb isRepG2[kNumStates];
++ CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
++
++ CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
++ CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
++ CLzmaProb posAlignEncoder[1 << kNumAlignBits];
++
++ CLenPriceEnc lenEnc;
++ CLenPriceEnc repLenEnc;
++
++ UInt32 reps[LZMA_NUM_REPS];
++ UInt32 state;
++} CSaveState;
++
++typedef struct _CLzmaEnc
++{
++ IMatchFinder matchFinder;
++ void *matchFinderObj;
++
++ #ifdef COMPRESS_MF_MT
++ Bool mtMode;
++ CMatchFinderMt matchFinderMt;
++ #endif
++
++ CMatchFinder matchFinderBase;
++
++ #ifdef COMPRESS_MF_MT
++ Byte pad[128];
++ #endif
++
++ UInt32 optimumEndIndex;
++ UInt32 optimumCurrentIndex;
++
++ Bool longestMatchWasFound;
++ UInt32 longestMatchLength;
++ UInt32 numDistancePairs;
++
++ COptimal opt[kNumOpts];
++
++ #ifndef LZMA_LOG_BSR
++ Byte g_FastPos[1 << kNumLogBits];
++ #endif
++
++ UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
++ UInt32 matchDistances[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
++ UInt32 numFastBytes;
++ UInt32 additionalOffset;
++ UInt32 reps[LZMA_NUM_REPS];
++ UInt32 state;
++
++ UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
++ UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
++ UInt32 alignPrices[kAlignTableSize];
++ UInt32 alignPriceCount;
++
++ UInt32 distTableSize;
++
++ unsigned lc, lp, pb;
++ unsigned lpMask, pbMask;
++
++ CLzmaProb *litProbs;
++
++ CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
++ CLzmaProb isRep[kNumStates];
++ CLzmaProb isRepG0[kNumStates];
++ CLzmaProb isRepG1[kNumStates];
++ CLzmaProb isRepG2[kNumStates];
++ CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
++
++ CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
++ CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
++ CLzmaProb posAlignEncoder[1 << kNumAlignBits];
++
++ CLenPriceEnc lenEnc;
++ CLenPriceEnc repLenEnc;
++
++ unsigned lclp;
++
++ Bool fastMode;
++
++ CRangeEnc rc;
++
++ Bool writeEndMark;
++ UInt64 nowPos64;
++ UInt32 matchPriceCount;
++ Bool finished;
++ Bool multiThread;
++
++ SRes result;
++ UInt32 dictSize;
++ UInt32 matchFinderCycles;
++
++ ISeqInStream *inStream;
++ CSeqInStreamBuf seqBufInStream;
++
++ CSaveState saveState;
++} CLzmaEnc;
++
++static void LzmaEnc_SaveState(CLzmaEncHandle pp)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ CSaveState *dest = &p->saveState;
++ int i;
++ dest->lenEnc = p->lenEnc;
++ dest->repLenEnc = p->repLenEnc;
++ dest->state = p->state;
++
++ for (i = 0; i < kNumStates; i++)
++ {
++ memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
++ memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
++ }
++ for (i = 0; i < kNumLenToPosStates; i++)
++ memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
++ memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
++ memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
++ memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
++ memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
++ memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
++ memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
++ memcpy(dest->reps, p->reps, sizeof(p->reps));
++ memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
++}
++
++static void LzmaEnc_RestoreState(CLzmaEncHandle pp)
++{
++ CLzmaEnc *dest = (CLzmaEnc *)pp;
++ const CSaveState *p = &dest->saveState;
++ int i;
++ dest->lenEnc = p->lenEnc;
++ dest->repLenEnc = p->repLenEnc;
++ dest->state = p->state;
++
++ for (i = 0; i < kNumStates; i++)
++ {
++ memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
++ memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
++ }
++ for (i = 0; i < kNumLenToPosStates; i++)
++ memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
++ memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
++ memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
++ memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
++ memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
++ memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
++ memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
++ memcpy(dest->reps, p->reps, sizeof(p->reps));
++ memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
++}
++
++SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ CLzmaEncProps props = *props2;
++ LzmaEncProps_Normalize(&props);
++
++ if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
++ props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30))
++ return SZ_ERROR_PARAM;
++ p->dictSize = props.dictSize;
++ p->matchFinderCycles = props.mc;
++ {
++ unsigned fb = props.fb;
++ if (fb < 5)
++ fb = 5;
++ if (fb > LZMA_MATCH_LEN_MAX)
++ fb = LZMA_MATCH_LEN_MAX;
++ p->numFastBytes = fb;
++ }
++ p->lc = props.lc;
++ p->lp = props.lp;
++ p->pb = props.pb;
++ p->fastMode = (props.algo == 0);
++ p->matchFinderBase.btMode = props.btMode;
++ {
++ UInt32 numHashBytes = 4;
++ if (props.btMode)
++ {
++ if (props.numHashBytes < 2)
++ numHashBytes = 2;
++ else if (props.numHashBytes < 4)
++ numHashBytes = props.numHashBytes;
++ }
++ p->matchFinderBase.numHashBytes = numHashBytes;
++ }
++
++ p->matchFinderBase.cutValue = props.mc;
++
++ p->writeEndMark = props.writeEndMark;
++
++ #ifdef COMPRESS_MF_MT
++ /*
++ if (newMultiThread != _multiThread)
++ {
++ ReleaseMatchFinder();
++ _multiThread = newMultiThread;
++ }
++ */
++ p->multiThread = (props.numThreads > 1);
++ #endif
++
++ return SZ_OK;
++}
++
++static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
++static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
++static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
++static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
++
++/*
++ void UpdateChar() { Index = kLiteralNextStates[Index]; }
++ void UpdateMatch() { Index = kMatchNextStates[Index]; }
++ void UpdateRep() { Index = kRepNextStates[Index]; }
++ void UpdateShortRep() { Index = kShortRepNextStates[Index]; }
++*/
++
++#define IsCharState(s) ((s) < 7)
++
++
++#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
++
++#define kInfinityPrice (1 << 30)
++
++static void RangeEnc_Construct(CRangeEnc *p)
++{
++ p->outStream = 0;
++ p->bufBase = 0;
++}
++
++#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
++
++#define RC_BUF_SIZE (1 << 16)
++static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
++{
++ if (p->bufBase == 0)
++ {
++ p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
++ if (p->bufBase == 0)
++ return 0;
++ p->bufLim = p->bufBase + RC_BUF_SIZE;
++ }
++ return 1;
++}
++
++static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
++{
++ alloc->Free(alloc, p->bufBase);
++ p->bufBase = 0;
++}
++
++static void RangeEnc_Init(CRangeEnc *p)
++{
++ /* Stream.Init(); */
++ p->low = 0;
++ p->range = 0xFFFFFFFF;
++ p->cacheSize = 1;
++ p->cache = 0;
++
++ p->buf = p->bufBase;
++
++ p->processed = 0;
++ p->res = SZ_OK;
++}
++
++static void RangeEnc_FlushStream(CRangeEnc *p)
++{
++ size_t num;
++ if (p->res != SZ_OK)
++ return;
++ num = p->buf - p->bufBase;
++ if (num != p->outStream->Write(p->outStream, p->bufBase, num))
++ p->res = SZ_ERROR_WRITE;
++ p->processed += num;
++ p->buf = p->bufBase;
++}
++
++static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
++{
++ if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
++ {
++ Byte temp = p->cache;
++ do
++ {
++ Byte *buf = p->buf;
++ *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
++ p->buf = buf;
++ if (buf == p->bufLim)
++ RangeEnc_FlushStream(p);
++ temp = 0xFF;
++ }
++ while (--p->cacheSize != 0);
++ p->cache = (Byte)((UInt32)p->low >> 24);
++ }
++ p->cacheSize++;
++ p->low = (UInt32)p->low << 8;
++}
++
++static void RangeEnc_FlushData(CRangeEnc *p)
++{
++ int i;
++ for (i = 0; i < 5; i++)
++ RangeEnc_ShiftLow(p);
++}
++
++static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits)
++{
++ do
++ {
++ p->range >>= 1;
++ p->low += p->range & (0 - ((value >> --numBits) & 1));
++ if (p->range < kTopValue)
++ {
++ p->range <<= 8;
++ RangeEnc_ShiftLow(p);
++ }
++ }
++ while (numBits != 0);
++}
++
++static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol)
++{
++ UInt32 ttt = *prob;
++ UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
++ if (symbol == 0)
++ {
++ p->range = newBound;
++ ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
++ }
++ else
++ {
++ p->low += newBound;
++ p->range -= newBound;
++ ttt -= ttt >> kNumMoveBits;
++ }
++ *prob = (CLzmaProb)ttt;
++ if (p->range < kTopValue)
++ {
++ p->range <<= 8;
++ RangeEnc_ShiftLow(p);
++ }
++}
++
++static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol)
++{
++ symbol |= 0x100;
++ do
++ {
++ RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
++ symbol <<= 1;
++ }
++ while (symbol < 0x10000);
++}
++
++static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte)
++{
++ UInt32 offs = 0x100;
++ symbol |= 0x100;
++ do
++ {
++ matchByte <<= 1;
++ RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
++ symbol <<= 1;
++ offs &= ~(matchByte ^ symbol);
++ }
++ while (symbol < 0x10000);
++}
++
++static void LzmaEnc_InitPriceTables(UInt32 *ProbPrices)
++{
++ UInt32 i;
++ for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
++ {
++ const int kCyclesBits = kNumBitPriceShiftBits;
++ UInt32 w = i;
++ UInt32 bitCount = 0;
++ int j;
++ for (j = 0; j < kCyclesBits; j++)
++ {
++ w = w * w;
++ bitCount <<= 1;
++ while (w >= ((UInt32)1 << 16))
++ {
++ w >>= 1;
++ bitCount++;
++ }
++ }
++ ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
++ }
++}
++
++
++#define GET_PRICE(prob, symbol) \
++ p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
++
++#define GET_PRICEa(prob, symbol) \
++ ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
++
++#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
++#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
++
++#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
++#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
++
++static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices)
++{
++ UInt32 price = 0;
++ symbol |= 0x100;
++ do
++ {
++ price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
++ symbol <<= 1;
++ }
++ while (symbol < 0x10000);
++ return price;
++};
++
++static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices)
++{
++ UInt32 price = 0;
++ UInt32 offs = 0x100;
++ symbol |= 0x100;
++ do
++ {
++ matchByte <<= 1;
++ price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
++ symbol <<= 1;
++ offs &= ~(matchByte ^ symbol);
++ }
++ while (symbol < 0x10000);
++ return price;
++};
++
++
++static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
++{
++ UInt32 m = 1;
++ int i;
++ for (i = numBitLevels; i != 0 ;)
++ {
++ UInt32 bit;
++ i--;
++ bit = (symbol >> i) & 1;
++ RangeEnc_EncodeBit(rc, probs + m, bit);
++ m = (m << 1) | bit;
++ }
++};
++
++static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol)
++{
++ UInt32 m = 1;
++ int i;
++ for (i = 0; i < numBitLevels; i++)
++ {
++ UInt32 bit = symbol & 1;
++ RangeEnc_EncodeBit(rc, probs + m, bit);
++ m = (m << 1) | bit;
++ symbol >>= 1;
++ }
++}
++
++static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
++{
++ UInt32 price = 0;
++ symbol |= (1 << numBitLevels);
++ while (symbol != 1)
++ {
++ price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
++ symbol >>= 1;
++ }
++ return price;
++}
++
++static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices)
++{
++ UInt32 price = 0;
++ UInt32 m = 1;
++ int i;
++ for (i = numBitLevels; i != 0; i--)
++ {
++ UInt32 bit = symbol & 1;
++ symbol >>= 1;
++ price += GET_PRICEa(probs[m], bit);
++ m = (m << 1) | bit;
++ }
++ return price;
++}
++
++
++static void LenEnc_Init(CLenEnc *p)
++{
++ unsigned i;
++ p->choice = p->choice2 = kProbInitValue;
++ for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
++ p->low[i] = kProbInitValue;
++ for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
++ p->mid[i] = kProbInitValue;
++ for (i = 0; i < kLenNumHighSymbols; i++)
++ p->high[i] = kProbInitValue;
++}
++
++static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState)
++{
++ if (symbol < kLenNumLowSymbols)
++ {
++ RangeEnc_EncodeBit(rc, &p->choice, 0);
++ RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
++ }
++ else
++ {
++ RangeEnc_EncodeBit(rc, &p->choice, 1);
++ if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
++ {
++ RangeEnc_EncodeBit(rc, &p->choice2, 0);
++ RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
++ }
++ else
++ {
++ RangeEnc_EncodeBit(rc, &p->choice2, 1);
++ RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
++ }
++ }
++}
++
++static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices)
++{
++ UInt32 a0 = GET_PRICE_0a(p->choice);
++ UInt32 a1 = GET_PRICE_1a(p->choice);
++ UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
++ UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
++ UInt32 i = 0;
++ for (i = 0; i < kLenNumLowSymbols; i++)
++ {
++ if (i >= numSymbols)
++ return;
++ prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
++ }
++ for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
++ {
++ if (i >= numSymbols)
++ return;
++ prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
++ }
++ for (; i < numSymbols; i++)
++ prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
++}
++
++static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices)
++{
++ LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
++ p->counters[posState] = p->tableSize;
++}
++
++static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices)
++{
++ UInt32 posState;
++ for (posState = 0; posState < numPosStates; posState++)
++ LenPriceEnc_UpdateTable(p, posState, ProbPrices);
++}
++
++static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices)
++{
++ LenEnc_Encode(&p->p, rc, symbol, posState);
++ if (updatePrice)
++ if (--p->counters[posState] == 0)
++ LenPriceEnc_UpdateTable(p, posState, ProbPrices);
++}
++
++
++
++
++static void MovePos(CLzmaEnc *p, UInt32 num)
++{
++ #ifdef SHOW_STAT
++ ttt += num;
++ printf("\n MovePos %d", num);
++ #endif
++ if (num != 0)
++ {
++ p->additionalOffset += num;
++ p->matchFinder.Skip(p->matchFinderObj, num);
++ }
++}
++
++static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes)
++{
++ UInt32 lenRes = 0, numDistancePairs;
++ numDistancePairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matchDistances);
++ #ifdef SHOW_STAT
++ printf("\n i = %d numPairs = %d ", ttt, numDistancePairs / 2);
++ if (ttt >= 61994)
++ ttt = ttt;
++
++ ttt++;
++ {
++ UInt32 i;
++ for (i = 0; i < numDistancePairs; i += 2)
++ printf("%2d %6d | ", p->matchDistances[i], p->matchDistances[i + 1]);
++ }
++ #endif
++ if (numDistancePairs > 0)
++ {
++ lenRes = p->matchDistances[numDistancePairs - 2];
++ if (lenRes == p->numFastBytes)
++ {
++ UInt32 numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) + 1;
++ const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
++ UInt32 distance = p->matchDistances[numDistancePairs - 1] + 1;
++ if (numAvail > LZMA_MATCH_LEN_MAX)
++ numAvail = LZMA_MATCH_LEN_MAX;
++
++ {
++ const Byte *pby2 = pby - distance;
++ for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
++ }
++ }
++ }
++ p->additionalOffset++;
++ *numDistancePairsRes = numDistancePairs;
++ return lenRes;
++}
++
++
++#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False;
++#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
++#define IsShortRep(p) ((p)->backPrev == 0)
++
++static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState)
++{
++ return
++ GET_PRICE_0(p->isRepG0[state]) +
++ GET_PRICE_0(p->isRep0Long[state][posState]);
++}
++
++static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState)
++{
++ UInt32 price;
++ if (repIndex == 0)
++ {
++ price = GET_PRICE_0(p->isRepG0[state]);
++ price += GET_PRICE_1(p->isRep0Long[state][posState]);
++ }
++ else
++ {
++ price = GET_PRICE_1(p->isRepG0[state]);
++ if (repIndex == 1)
++ price += GET_PRICE_0(p->isRepG1[state]);
++ else
++ {
++ price += GET_PRICE_1(p->isRepG1[state]);
++ price += GET_PRICE(p->isRepG2[state], repIndex - 2);
++ }
++ }
++ return price;
++}
++
++static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState)
++{
++ return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
++ GetPureRepPrice(p, repIndex, state, posState);
++}
++
++static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur)
++{
++ UInt32 posMem = p->opt[cur].posPrev;
++ UInt32 backMem = p->opt[cur].backPrev;
++ p->optimumEndIndex = cur;
++ do
++ {
++ if (p->opt[cur].prev1IsChar)
++ {
++ MakeAsChar(&p->opt[posMem])
++ p->opt[posMem].posPrev = posMem - 1;
++ if (p->opt[cur].prev2)
++ {
++ p->opt[posMem - 1].prev1IsChar = False;
++ p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
++ p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
++ }
++ }
++ {
++ UInt32 posPrev = posMem;
++ UInt32 backCur = backMem;
++
++ backMem = p->opt[posPrev].backPrev;
++ posMem = p->opt[posPrev].posPrev;
++
++ p->opt[posPrev].backPrev = backCur;
++ p->opt[posPrev].posPrev = cur;
++ cur = posPrev;
++ }
++ }
++ while (cur != 0);
++ *backRes = p->opt[0].backPrev;
++ p->optimumCurrentIndex = p->opt[0].posPrev;
++ return p->optimumCurrentIndex;
++}
++
++#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
++
++static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes)
++{
++ UInt32 numAvailableBytes, lenMain, numDistancePairs;
++ const Byte *data;
++ UInt32 reps[LZMA_NUM_REPS];
++ UInt32 repLens[LZMA_NUM_REPS];
++ UInt32 repMaxIndex, i;
++ UInt32 *matchDistances;
++ Byte currentByte, matchByte;
++ UInt32 posState;
++ UInt32 matchPrice, repMatchPrice;
++ UInt32 lenEnd;
++ UInt32 len;
++ UInt32 normalMatchPrice;
++ UInt32 cur;
++ if (p->optimumEndIndex != p->optimumCurrentIndex)
++ {
++ const COptimal *opt = &p->opt[p->optimumCurrentIndex];
++ UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
++ *backRes = opt->backPrev;
++ p->optimumCurrentIndex = opt->posPrev;
++ return lenRes;
++ }
++ p->optimumCurrentIndex = p->optimumEndIndex = 0;
++
++ numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
++
++ if (!p->longestMatchWasFound)
++ {
++ lenMain = ReadMatchDistances(p, &numDistancePairs);
++ }
++ else
++ {
++ lenMain = p->longestMatchLength;
++ numDistancePairs = p->numDistancePairs;
++ p->longestMatchWasFound = False;
++ }
++
++ data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
++ if (numAvailableBytes < 2)
++ {
++ *backRes = (UInt32)(-1);
++ return 1;
++ }
++ if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
++ numAvailableBytes = LZMA_MATCH_LEN_MAX;
++
++ repMaxIndex = 0;
++ for (i = 0; i < LZMA_NUM_REPS; i++)
++ {
++ UInt32 lenTest;
++ const Byte *data2;
++ reps[i] = p->reps[i];
++ data2 = data - (reps[i] + 1);
++ if (data[0] != data2[0] || data[1] != data2[1])
++ {
++ repLens[i] = 0;
++ continue;
++ }
++ for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
++ repLens[i] = lenTest;
++ if (lenTest > repLens[repMaxIndex])
++ repMaxIndex = i;
++ }
++ if (repLens[repMaxIndex] >= p->numFastBytes)
++ {
++ UInt32 lenRes;
++ *backRes = repMaxIndex;
++ lenRes = repLens[repMaxIndex];
++ MovePos(p, lenRes - 1);
++ return lenRes;
++ }
++
++ matchDistances = p->matchDistances;
++ if (lenMain >= p->numFastBytes)
++ {
++ *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
++ MovePos(p, lenMain - 1);
++ return lenMain;
++ }
++ currentByte = *data;
++ matchByte = *(data - (reps[0] + 1));
++
++ if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
++ {
++ *backRes = (UInt32)-1;
++ return 1;
++ }
++
++ p->opt[0].state = (CState)p->state;
++
++ posState = (position & p->pbMask);
++
++ {
++ const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
++ p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
++ (!IsCharState(p->state) ?
++ LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
++ LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
++ }
++
++ MakeAsChar(&p->opt[1]);
++
++ matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
++ repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
++
++ if (matchByte == currentByte)
++ {
++ UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
++ if (shortRepPrice < p->opt[1].price)
++ {
++ p->opt[1].price = shortRepPrice;
++ MakeAsShortRep(&p->opt[1]);
++ }
++ }
++ lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
++
++ if (lenEnd < 2)
++ {
++ *backRes = p->opt[1].backPrev;
++ return 1;
++ }
++
++ p->opt[1].posPrev = 0;
++ for (i = 0; i < LZMA_NUM_REPS; i++)
++ p->opt[0].backs[i] = reps[i];
++
++ len = lenEnd;
++ do
++ p->opt[len--].price = kInfinityPrice;
++ while (len >= 2);
++
++ for (i = 0; i < LZMA_NUM_REPS; i++)
++ {
++ UInt32 repLen = repLens[i];
++ UInt32 price;
++ if (repLen < 2)
++ continue;
++ price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
++ do
++ {
++ UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
++ COptimal *opt = &p->opt[repLen];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = 0;
++ opt->backPrev = i;
++ opt->prev1IsChar = False;
++ }
++ }
++ while (--repLen >= 2);
++ }
++
++ normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
++
++ len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
++ if (len <= lenMain)
++ {
++ UInt32 offs = 0;
++ while (len > matchDistances[offs])
++ offs += 2;
++ for (; ; len++)
++ {
++ COptimal *opt;
++ UInt32 distance = matchDistances[offs + 1];
++
++ UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
++ UInt32 lenToPosState = GetLenToPosState(len);
++ if (distance < kNumFullDistances)
++ curAndLenPrice += p->distancesPrices[lenToPosState][distance];
++ else
++ {
++ UInt32 slot;
++ GetPosSlot2(distance, slot);
++ curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
++ }
++ opt = &p->opt[len];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = 0;
++ opt->backPrev = distance + LZMA_NUM_REPS;
++ opt->prev1IsChar = False;
++ }
++ if (len == matchDistances[offs])
++ {
++ offs += 2;
++ if (offs == numDistancePairs)
++ break;
++ }
++ }
++ }
++
++ cur = 0;
++
++ #ifdef SHOW_STAT2
++ if (position >= 0)
++ {
++ unsigned i;
++ printf("\n pos = %4X", position);
++ for (i = cur; i <= lenEnd; i++)
++ printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
++ }
++ #endif
++
++ for (;;)
++ {
++ UInt32 numAvailableBytesFull, newLen, numDistancePairs;
++ COptimal *curOpt;
++ UInt32 posPrev;
++ UInt32 state;
++ UInt32 curPrice;
++ Bool nextIsChar;
++ const Byte *data;
++ Byte currentByte, matchByte;
++ UInt32 posState;
++ UInt32 curAnd1Price;
++ COptimal *nextOpt;
++ UInt32 matchPrice, repMatchPrice;
++ UInt32 numAvailableBytes;
++ UInt32 startLen;
++
++ cur++;
++ if (cur == lenEnd)
++ return Backward(p, backRes, cur);
++
++ numAvailableBytesFull = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
++ newLen = ReadMatchDistances(p, &numDistancePairs);
++ if (newLen >= p->numFastBytes)
++ {
++ p->numDistancePairs = numDistancePairs;
++ p->longestMatchLength = newLen;
++ p->longestMatchWasFound = True;
++ return Backward(p, backRes, cur);
++ }
++ position++;
++ curOpt = &p->opt[cur];
++ posPrev = curOpt->posPrev;
++ if (curOpt->prev1IsChar)
++ {
++ posPrev--;
++ if (curOpt->prev2)
++ {
++ state = p->opt[curOpt->posPrev2].state;
++ if (curOpt->backPrev2 < LZMA_NUM_REPS)
++ state = kRepNextStates[state];
++ else
++ state = kMatchNextStates[state];
++ }
++ else
++ state = p->opt[posPrev].state;
++ state = kLiteralNextStates[state];
++ }
++ else
++ state = p->opt[posPrev].state;
++ if (posPrev == cur - 1)
++ {
++ if (IsShortRep(curOpt))
++ state = kShortRepNextStates[state];
++ else
++ state = kLiteralNextStates[state];
++ }
++ else
++ {
++ UInt32 pos;
++ const COptimal *prevOpt;
++ if (curOpt->prev1IsChar && curOpt->prev2)
++ {
++ posPrev = curOpt->posPrev2;
++ pos = curOpt->backPrev2;
++ state = kRepNextStates[state];
++ }
++ else
++ {
++ pos = curOpt->backPrev;
++ if (pos < LZMA_NUM_REPS)
++ state = kRepNextStates[state];
++ else
++ state = kMatchNextStates[state];
++ }
++ prevOpt = &p->opt[posPrev];
++ if (pos < LZMA_NUM_REPS)
++ {
++ UInt32 i;
++ reps[0] = prevOpt->backs[pos];
++ for (i = 1; i <= pos; i++)
++ reps[i] = prevOpt->backs[i - 1];
++ for (; i < LZMA_NUM_REPS; i++)
++ reps[i] = prevOpt->backs[i];
++ }
++ else
++ {
++ UInt32 i;
++ reps[0] = (pos - LZMA_NUM_REPS);
++ for (i = 1; i < LZMA_NUM_REPS; i++)
++ reps[i] = prevOpt->backs[i - 1];
++ }
++ }
++ curOpt->state = (CState)state;
++
++ curOpt->backs[0] = reps[0];
++ curOpt->backs[1] = reps[1];
++ curOpt->backs[2] = reps[2];
++ curOpt->backs[3] = reps[3];
++
++ curPrice = curOpt->price;
++ nextIsChar = False;
++ data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
++ currentByte = *data;
++ matchByte = *(data - (reps[0] + 1));
++
++ posState = (position & p->pbMask);
++
++ curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
++ {
++ const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
++ curAnd1Price +=
++ (!IsCharState(state) ?
++ LitEnc_GetPriceMatched(probs, currentByte, matchByte, p->ProbPrices) :
++ LitEnc_GetPrice(probs, currentByte, p->ProbPrices));
++ }
++
++ nextOpt = &p->opt[cur + 1];
++
++ if (curAnd1Price < nextOpt->price)
++ {
++ nextOpt->price = curAnd1Price;
++ nextOpt->posPrev = cur;
++ MakeAsChar(nextOpt);
++ nextIsChar = True;
++ }
++
++ matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
++ repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
++
++ if (matchByte == currentByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
++ {
++ UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
++ if (shortRepPrice <= nextOpt->price)
++ {
++ nextOpt->price = shortRepPrice;
++ nextOpt->posPrev = cur;
++ MakeAsShortRep(nextOpt);
++ nextIsChar = True;
++ }
++ }
++
++ {
++ UInt32 temp = kNumOpts - 1 - cur;
++ if (temp < numAvailableBytesFull)
++ numAvailableBytesFull = temp;
++ }
++ numAvailableBytes = numAvailableBytesFull;
++
++ if (numAvailableBytes < 2)
++ continue;
++ if (numAvailableBytes > p->numFastBytes)
++ numAvailableBytes = p->numFastBytes;
++ if (!nextIsChar && matchByte != currentByte) /* speed optimization */
++ {
++ /* try Literal + rep0 */
++ UInt32 temp;
++ UInt32 lenTest2;
++ const Byte *data2 = data - (reps[0] + 1);
++ UInt32 limit = p->numFastBytes + 1;
++ if (limit > numAvailableBytesFull)
++ limit = numAvailableBytesFull;
++
++ for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
++ lenTest2 = temp - 1;
++ if (lenTest2 >= 2)
++ {
++ UInt32 state2 = kLiteralNextStates[state];
++ UInt32 posStateNext = (position + 1) & p->pbMask;
++ UInt32 nextRepMatchPrice = curAnd1Price +
++ GET_PRICE_1(p->isMatch[state2][posStateNext]) +
++ GET_PRICE_1(p->isRep[state2]);
++ /* for (; lenTest2 >= 2; lenTest2--) */
++ {
++ UInt32 curAndLenPrice;
++ COptimal *opt;
++ UInt32 offset = cur + 1 + lenTest2;
++ while (lenEnd < offset)
++ p->opt[++lenEnd].price = kInfinityPrice;
++ curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
++ opt = &p->opt[offset];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = cur + 1;
++ opt->backPrev = 0;
++ opt->prev1IsChar = True;
++ opt->prev2 = False;
++ }
++ }
++ }
++ }
++
++ startLen = 2; /* speed optimization */
++ {
++ UInt32 repIndex;
++ for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
++ {
++ UInt32 lenTest;
++ UInt32 lenTestTemp;
++ UInt32 price;
++ const Byte *data2 = data - (reps[repIndex] + 1);
++ if (data[0] != data2[0] || data[1] != data2[1])
++ continue;
++ for (lenTest = 2; lenTest < numAvailableBytes && data[lenTest] == data2[lenTest]; lenTest++);
++ while (lenEnd < cur + lenTest)
++ p->opt[++lenEnd].price = kInfinityPrice;
++ lenTestTemp = lenTest;
++ price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
++ do
++ {
++ UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
++ COptimal *opt = &p->opt[cur + lenTest];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = cur;
++ opt->backPrev = repIndex;
++ opt->prev1IsChar = False;
++ }
++ }
++ while (--lenTest >= 2);
++ lenTest = lenTestTemp;
++
++ if (repIndex == 0)
++ startLen = lenTest + 1;
++
++ /* if (_maxMode) */
++ {
++ UInt32 lenTest2 = lenTest + 1;
++ UInt32 limit = lenTest2 + p->numFastBytes;
++ UInt32 nextRepMatchPrice;
++ if (limit > numAvailableBytesFull)
++ limit = numAvailableBytesFull;
++ for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
++ lenTest2 -= lenTest + 1;
++ if (lenTest2 >= 2)
++ {
++ UInt32 state2 = kRepNextStates[state];
++ UInt32 posStateNext = (position + lenTest) & p->pbMask;
++ UInt32 curAndLenCharPrice =
++ price + p->repLenEnc.prices[posState][lenTest - 2] +
++ GET_PRICE_0(p->isMatch[state2][posStateNext]) +
++ LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
++ data[lenTest], data2[lenTest], p->ProbPrices);
++ state2 = kLiteralNextStates[state2];
++ posStateNext = (position + lenTest + 1) & p->pbMask;
++ nextRepMatchPrice = curAndLenCharPrice +
++ GET_PRICE_1(p->isMatch[state2][posStateNext]) +
++ GET_PRICE_1(p->isRep[state2]);
++
++ /* for (; lenTest2 >= 2; lenTest2--) */
++ {
++ UInt32 curAndLenPrice;
++ COptimal *opt;
++ UInt32 offset = cur + lenTest + 1 + lenTest2;
++ while (lenEnd < offset)
++ p->opt[++lenEnd].price = kInfinityPrice;
++ curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
++ opt = &p->opt[offset];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = cur + lenTest + 1;
++ opt->backPrev = 0;
++ opt->prev1IsChar = True;
++ opt->prev2 = True;
++ opt->posPrev2 = cur;
++ opt->backPrev2 = repIndex;
++ }
++ }
++ }
++ }
++ }
++ }
++ /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
++ if (newLen > numAvailableBytes)
++ {
++ newLen = numAvailableBytes;
++ for (numDistancePairs = 0; newLen > matchDistances[numDistancePairs]; numDistancePairs += 2);
++ matchDistances[numDistancePairs] = newLen;
++ numDistancePairs += 2;
++ }
++ if (newLen >= startLen)
++ {
++ UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
++ UInt32 offs, curBack, posSlot;
++ UInt32 lenTest;
++ while (lenEnd < cur + newLen)
++ p->opt[++lenEnd].price = kInfinityPrice;
++
++ offs = 0;
++ while (startLen > matchDistances[offs])
++ offs += 2;
++ curBack = matchDistances[offs + 1];
++ GetPosSlot2(curBack, posSlot);
++ for (lenTest = /*2*/ startLen; ; lenTest++)
++ {
++ UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
++ UInt32 lenToPosState = GetLenToPosState(lenTest);
++ COptimal *opt;
++ if (curBack < kNumFullDistances)
++ curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
++ else
++ curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
++
++ opt = &p->opt[cur + lenTest];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = cur;
++ opt->backPrev = curBack + LZMA_NUM_REPS;
++ opt->prev1IsChar = False;
++ }
++
++ if (/*_maxMode && */lenTest == matchDistances[offs])
++ {
++ /* Try Match + Literal + Rep0 */
++ const Byte *data2 = data - (curBack + 1);
++ UInt32 lenTest2 = lenTest + 1;
++ UInt32 limit = lenTest2 + p->numFastBytes;
++ UInt32 nextRepMatchPrice;
++ if (limit > numAvailableBytesFull)
++ limit = numAvailableBytesFull;
++ for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
++ lenTest2 -= lenTest + 1;
++ if (lenTest2 >= 2)
++ {
++ UInt32 state2 = kMatchNextStates[state];
++ UInt32 posStateNext = (position + lenTest) & p->pbMask;
++ UInt32 curAndLenCharPrice = curAndLenPrice +
++ GET_PRICE_0(p->isMatch[state2][posStateNext]) +
++ LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
++ data[lenTest], data2[lenTest], p->ProbPrices);
++ state2 = kLiteralNextStates[state2];
++ posStateNext = (posStateNext + 1) & p->pbMask;
++ nextRepMatchPrice = curAndLenCharPrice +
++ GET_PRICE_1(p->isMatch[state2][posStateNext]) +
++ GET_PRICE_1(p->isRep[state2]);
++
++ /* for (; lenTest2 >= 2; lenTest2--) */
++ {
++ UInt32 offset = cur + lenTest + 1 + lenTest2;
++ UInt32 curAndLenPrice;
++ COptimal *opt;
++ while (lenEnd < offset)
++ p->opt[++lenEnd].price = kInfinityPrice;
++ curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
++ opt = &p->opt[offset];
++ if (curAndLenPrice < opt->price)
++ {
++ opt->price = curAndLenPrice;
++ opt->posPrev = cur + lenTest + 1;
++ opt->backPrev = 0;
++ opt->prev1IsChar = True;
++ opt->prev2 = True;
++ opt->posPrev2 = cur;
++ opt->backPrev2 = curBack + LZMA_NUM_REPS;
++ }
++ }
++ }
++ offs += 2;
++ if (offs == numDistancePairs)
++ break;
++ curBack = matchDistances[offs + 1];
++ if (curBack >= kNumFullDistances)
++ GetPosSlot2(curBack, posSlot);
++ }
++ }
++ }
++ }
++}
++
++#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
++
++static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes)
++{
++ UInt32 numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
++ UInt32 lenMain, numDistancePairs;
++ const Byte *data;
++ UInt32 repLens[LZMA_NUM_REPS];
++ UInt32 repMaxIndex, i;
++ UInt32 *matchDistances;
++ UInt32 backMain;
++
++ if (!p->longestMatchWasFound)
++ {
++ lenMain = ReadMatchDistances(p, &numDistancePairs);
++ }
++ else
++ {
++ lenMain = p->longestMatchLength;
++ numDistancePairs = p->numDistancePairs;
++ p->longestMatchWasFound = False;
++ }
++
++ data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
++ if (numAvailableBytes > LZMA_MATCH_LEN_MAX)
++ numAvailableBytes = LZMA_MATCH_LEN_MAX;
++ if (numAvailableBytes < 2)
++ {
++ *backRes = (UInt32)(-1);
++ return 1;
++ }
++
++ repMaxIndex = 0;
++
++ for (i = 0; i < LZMA_NUM_REPS; i++)
++ {
++ const Byte *data2 = data - (p->reps[i] + 1);
++ UInt32 len;
++ if (data[0] != data2[0] || data[1] != data2[1])
++ {
++ repLens[i] = 0;
++ continue;
++ }
++ for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
++ if (len >= p->numFastBytes)
++ {
++ *backRes = i;
++ MovePos(p, len - 1);
++ return len;
++ }
++ repLens[i] = len;
++ if (len > repLens[repMaxIndex])
++ repMaxIndex = i;
++ }
++ matchDistances = p->matchDistances;
++ if (lenMain >= p->numFastBytes)
++ {
++ *backRes = matchDistances[numDistancePairs - 1] + LZMA_NUM_REPS;
++ MovePos(p, lenMain - 1);
++ return lenMain;
++ }
++
++ backMain = 0; /* for GCC */
++ if (lenMain >= 2)
++ {
++ backMain = matchDistances[numDistancePairs - 1];
++ while (numDistancePairs > 2 && lenMain == matchDistances[numDistancePairs - 4] + 1)
++ {
++ if (!ChangePair(matchDistances[numDistancePairs - 3], backMain))
++ break;
++ numDistancePairs -= 2;
++ lenMain = matchDistances[numDistancePairs - 2];
++ backMain = matchDistances[numDistancePairs - 1];
++ }
++ if (lenMain == 2 && backMain >= 0x80)
++ lenMain = 1;
++ }
++
++ if (repLens[repMaxIndex] >= 2)
++ {
++ if (repLens[repMaxIndex] + 1 >= lenMain ||
++ (repLens[repMaxIndex] + 2 >= lenMain && (backMain > (1 << 9))) ||
++ (repLens[repMaxIndex] + 3 >= lenMain && (backMain > (1 << 15))))
++ {
++ UInt32 lenRes;
++ *backRes = repMaxIndex;
++ lenRes = repLens[repMaxIndex];
++ MovePos(p, lenRes - 1);
++ return lenRes;
++ }
++ }
++
++ if (lenMain >= 2 && numAvailableBytes > 2)
++ {
++ UInt32 i;
++ numAvailableBytes = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
++ p->longestMatchLength = ReadMatchDistances(p, &p->numDistancePairs);
++ if (p->longestMatchLength >= 2)
++ {
++ UInt32 newDistance = matchDistances[p->numDistancePairs - 1];
++ if ((p->longestMatchLength >= lenMain && newDistance < backMain) ||
++ (p->longestMatchLength == lenMain + 1 && !ChangePair(backMain, newDistance)) ||
++ (p->longestMatchLength > lenMain + 1) ||
++ (p->longestMatchLength + 1 >= lenMain && lenMain >= 3 && ChangePair(newDistance, backMain)))
++ {
++ p->longestMatchWasFound = True;
++ *backRes = (UInt32)(-1);
++ return 1;
++ }
++ }
++ data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
++ for (i = 0; i < LZMA_NUM_REPS; i++)
++ {
++ UInt32 len;
++ const Byte *data2 = data - (p->reps[i] + 1);
++ if (data[1] != data2[1] || data[2] != data2[2])
++ {
++ repLens[i] = 0;
++ continue;
++ }
++ for (len = 2; len < numAvailableBytes && data[len] == data2[len]; len++);
++ if (len + 1 >= lenMain)
++ {
++ p->longestMatchWasFound = True;
++ *backRes = (UInt32)(-1);
++ return 1;
++ }
++ }
++ *backRes = backMain + LZMA_NUM_REPS;
++ MovePos(p, lenMain - 2);
++ return lenMain;
++ }
++ *backRes = (UInt32)(-1);
++ return 1;
++}
++
++static void WriteEndMarker(CLzmaEnc *p, UInt32 posState)
++{
++ UInt32 len;
++ RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
++ RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
++ p->state = kMatchNextStates[p->state];
++ len = LZMA_MATCH_LEN_MIN;
++ LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
++ RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
++ RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
++ RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
++}
++
++static SRes CheckErrors(CLzmaEnc *p)
++{
++ if (p->result != SZ_OK)
++ return p->result;
++ if (p->rc.res != SZ_OK)
++ p->result = SZ_ERROR_WRITE;
++ if (p->matchFinderBase.result != SZ_OK)
++ p->result = SZ_ERROR_READ;
++ if (p->result != SZ_OK)
++ p->finished = True;
++ return p->result;
++}
++
++static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
++{
++ /* ReleaseMFStream(); */
++ p->finished = True;
++ if (p->writeEndMark)
++ WriteEndMarker(p, nowPos & p->pbMask);
++ RangeEnc_FlushData(&p->rc);
++ RangeEnc_FlushStream(&p->rc);
++ return CheckErrors(p);
++}
++
++static void FillAlignPrices(CLzmaEnc *p)
++{
++ UInt32 i;
++ for (i = 0; i < kAlignTableSize; i++)
++ p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
++ p->alignPriceCount = 0;
++}
++
++static void FillDistancesPrices(CLzmaEnc *p)
++{
++ UInt32 tempPrices[kNumFullDistances];
++ UInt32 i, lenToPosState;
++ for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
++ {
++ UInt32 posSlot = GetPosSlot1(i);
++ UInt32 footerBits = ((posSlot >> 1) - 1);
++ UInt32 base = ((2 | (posSlot & 1)) << footerBits);
++ tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
++ }
++
++ for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
++ {
++ UInt32 posSlot;
++ const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
++ UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
++ for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
++ posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
++ for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
++ posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
++
++ {
++ UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
++ UInt32 i;
++ for (i = 0; i < kStartPosModelIndex; i++)
++ distancesPrices[i] = posSlotPrices[i];
++ for (; i < kNumFullDistances; i++)
++ distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
++ }
++ }
++ p->matchPriceCount = 0;
++}
++
++static void LzmaEnc_Construct(CLzmaEnc *p)
++{
++ RangeEnc_Construct(&p->rc);
++ MatchFinder_Construct(&p->matchFinderBase);
++ #ifdef COMPRESS_MF_MT
++ MatchFinderMt_Construct(&p->matchFinderMt);
++ p->matchFinderMt.MatchFinder = &p->matchFinderBase;
++ #endif
++
++ {
++ CLzmaEncProps props;
++ LzmaEncProps_Init(&props);
++ LzmaEnc_SetProps(p, &props);
++ }
++
++ #ifndef LZMA_LOG_BSR
++ LzmaEnc_FastPosInit(p->g_FastPos);
++ #endif
++
++ LzmaEnc_InitPriceTables(p->ProbPrices);
++ p->litProbs = 0;
++ p->saveState.litProbs = 0;
++}
++
++CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
++{
++ void *p;
++ p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
++ if (p != 0)
++ LzmaEnc_Construct((CLzmaEnc *)p);
++ return p;
++}
++
++static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
++{
++ alloc->Free(alloc, p->litProbs);
++ alloc->Free(alloc, p->saveState.litProbs);
++ p->litProbs = 0;
++ p->saveState.litProbs = 0;
++}
++
++static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ #ifdef COMPRESS_MF_MT
++ MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
++ #endif
++ MatchFinder_Free(&p->matchFinderBase, allocBig);
++ LzmaEnc_FreeLits(p, alloc);
++ RangeEnc_Free(&p->rc, alloc);
++}
++
++void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
++ alloc->Free(alloc, p);
++}
++
++static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize)
++{
++ UInt32 nowPos32, startPos32;
++ if (p->inStream != 0)
++ {
++ p->matchFinderBase.stream = p->inStream;
++ p->matchFinder.Init(p->matchFinderObj);
++ p->inStream = 0;
++ }
++
++ if (p->finished)
++ return p->result;
++ RINOK(CheckErrors(p));
++
++ nowPos32 = (UInt32)p->nowPos64;
++ startPos32 = nowPos32;
++
++ if (p->nowPos64 == 0)
++ {
++ UInt32 numDistancePairs;
++ Byte curByte;
++ if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
++ return Flush(p, nowPos32);
++ ReadMatchDistances(p, &numDistancePairs);
++ RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
++ p->state = kLiteralNextStates[p->state];
++ curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
++ LitEnc_Encode(&p->rc, p->litProbs, curByte);
++ p->additionalOffset--;
++ nowPos32++;
++ }
++
++ if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
++ for (;;)
++ {
++ UInt32 pos, len, posState;
++
++ if (p->fastMode)
++ len = GetOptimumFast(p, &pos);
++ else
++ len = GetOptimum(p, nowPos32, &pos);
++
++ #ifdef SHOW_STAT2
++ printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos);
++ #endif
++
++ posState = nowPos32 & p->pbMask;
++ if (len == 1 && pos == 0xFFFFFFFF)
++ {
++ Byte curByte;
++ CLzmaProb *probs;
++ const Byte *data;
++
++ RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
++ data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
++ curByte = *data;
++ probs = LIT_PROBS(nowPos32, *(data - 1));
++ if (IsCharState(p->state))
++ LitEnc_Encode(&p->rc, probs, curByte);
++ else
++ LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
++ p->state = kLiteralNextStates[p->state];
++ }
++ else
++ {
++ RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
++ if (pos < LZMA_NUM_REPS)
++ {
++ RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
++ if (pos == 0)
++ {
++ RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
++ RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
++ }
++ else
++ {
++ UInt32 distance = p->reps[pos];
++ RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
++ if (pos == 1)
++ RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
++ else
++ {
++ RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
++ RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
++ if (pos == 3)
++ p->reps[3] = p->reps[2];
++ p->reps[2] = p->reps[1];
++ }
++ p->reps[1] = p->reps[0];
++ p->reps[0] = distance;
++ }
++ if (len == 1)
++ p->state = kShortRepNextStates[p->state];
++ else
++ {
++ LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
++ p->state = kRepNextStates[p->state];
++ }
++ }
++ else
++ {
++ UInt32 posSlot;
++ RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
++ p->state = kMatchNextStates[p->state];
++ LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
++ pos -= LZMA_NUM_REPS;
++ GetPosSlot(pos, posSlot);
++ RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
++
++ if (posSlot >= kStartPosModelIndex)
++ {
++ UInt32 footerBits = ((posSlot >> 1) - 1);
++ UInt32 base = ((2 | (posSlot & 1)) << footerBits);
++ UInt32 posReduced = pos - base;
++
++ if (posSlot < kEndPosModelIndex)
++ RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
++ else
++ {
++ RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
++ RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
++ p->alignPriceCount++;
++ }
++ }
++ p->reps[3] = p->reps[2];
++ p->reps[2] = p->reps[1];
++ p->reps[1] = p->reps[0];
++ p->reps[0] = pos;
++ p->matchPriceCount++;
++ }
++ }
++ p->additionalOffset -= len;
++ nowPos32 += len;
++ if (p->additionalOffset == 0)
++ {
++ UInt32 processed;
++ if (!p->fastMode)
++ {
++ if (p->matchPriceCount >= (1 << 7))
++ FillDistancesPrices(p);
++ if (p->alignPriceCount >= kAlignTableSize)
++ FillAlignPrices(p);
++ }
++ if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
++ break;
++ processed = nowPos32 - startPos32;
++ if (useLimits)
++ {
++ if (processed + kNumOpts + 300 >= maxUnpackSize ||
++ RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
++ break;
++ }
++ else if (processed >= (1 << 15))
++ {
++ p->nowPos64 += nowPos32 - startPos32;
++ return CheckErrors(p);
++ }
++ }
++ }
++ p->nowPos64 += nowPos32 - startPos32;
++ return Flush(p, nowPos32);
++}
++
++#define kBigHashDicLimit ((UInt32)1 << 24)
++
++static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ UInt32 beforeSize = kNumOpts;
++ Bool btMode;
++ if (!RangeEnc_Alloc(&p->rc, alloc))
++ return SZ_ERROR_MEM;
++ btMode = (p->matchFinderBase.btMode != 0);
++ #ifdef COMPRESS_MF_MT
++ p->mtMode = (p->multiThread && !p->fastMode && btMode);
++ #endif
++
++ {
++ unsigned lclp = p->lc + p->lp;
++ if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
++ {
++ LzmaEnc_FreeLits(p, alloc);
++ p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
++ p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
++ if (p->litProbs == 0 || p->saveState.litProbs == 0)
++ {
++ LzmaEnc_FreeLits(p, alloc);
++ return SZ_ERROR_MEM;
++ }
++ p->lclp = lclp;
++ }
++ }
++
++ p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
++
++ if (beforeSize + p->dictSize < keepWindowSize)
++ beforeSize = keepWindowSize - p->dictSize;
++
++ #ifdef COMPRESS_MF_MT
++ if (p->mtMode)
++ {
++ RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
++ p->matchFinderObj = &p->matchFinderMt;
++ MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
++ }
++ else
++ #endif
++ {
++ if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
++ return SZ_ERROR_MEM;
++ p->matchFinderObj = &p->matchFinderBase;
++ MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
++ }
++ return SZ_OK;
++}
++
++static void LzmaEnc_Init(CLzmaEnc *p)
++{
++ UInt32 i;
++ p->state = 0;
++ for(i = 0 ; i < LZMA_NUM_REPS; i++)
++ p->reps[i] = 0;
++
++ RangeEnc_Init(&p->rc);
++
++
++ for (i = 0; i < kNumStates; i++)
++ {
++ UInt32 j;
++ for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
++ {
++ p->isMatch[i][j] = kProbInitValue;
++ p->isRep0Long[i][j] = kProbInitValue;
++ }
++ p->isRep[i] = kProbInitValue;
++ p->isRepG0[i] = kProbInitValue;
++ p->isRepG1[i] = kProbInitValue;
++ p->isRepG2[i] = kProbInitValue;
++ }
++
++ {
++ UInt32 num = 0x300 << (p->lp + p->lc);
++ for (i = 0; i < num; i++)
++ p->litProbs[i] = kProbInitValue;
++ }
++
++ {
++ for (i = 0; i < kNumLenToPosStates; i++)
++ {
++ CLzmaProb *probs = p->posSlotEncoder[i];
++ UInt32 j;
++ for (j = 0; j < (1 << kNumPosSlotBits); j++)
++ probs[j] = kProbInitValue;
++ }
++ }
++ {
++ for(i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
++ p->posEncoders[i] = kProbInitValue;
++ }
++
++ LenEnc_Init(&p->lenEnc.p);
++ LenEnc_Init(&p->repLenEnc.p);
++
++ for (i = 0; i < (1 << kNumAlignBits); i++)
++ p->posAlignEncoder[i] = kProbInitValue;
++
++ p->longestMatchWasFound = False;
++ p->optimumEndIndex = 0;
++ p->optimumCurrentIndex = 0;
++ p->additionalOffset = 0;
++
++ p->pbMask = (1 << p->pb) - 1;
++ p->lpMask = (1 << p->lp) - 1;
++}
++
++static void LzmaEnc_InitPrices(CLzmaEnc *p)
++{
++ if (!p->fastMode)
++ {
++ FillDistancesPrices(p);
++ FillAlignPrices(p);
++ }
++
++ p->lenEnc.tableSize =
++ p->repLenEnc.tableSize =
++ p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
++ LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
++ LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
++}
++
++static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ UInt32 i;
++ for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++)
++ if (p->dictSize <= ((UInt32)1 << i))
++ break;
++ p->distTableSize = i * 2;
++
++ p->finished = False;
++ p->result = SZ_OK;
++ RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
++ LzmaEnc_Init(p);
++ LzmaEnc_InitPrices(p);
++ p->nowPos64 = 0;
++ return SZ_OK;
++}
++
++static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream,
++ ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ p->inStream = inStream;
++ p->rc.outStream = outStream;
++ return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
++}
++
++static SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
++ ISeqInStream *inStream, UInt32 keepWindowSize,
++ ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ p->inStream = inStream;
++ return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
++}
++
++static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
++{
++ p->seqBufInStream.funcTable.Read = MyRead;
++ p->seqBufInStream.data = src;
++ p->seqBufInStream.rem = srcLen;
++}
++
++static SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
++ UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ LzmaEnc_SetInputBuf(p, src, srcLen);
++ p->inStream = &p->seqBufInStream.funcTable;
++ return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
++}
++
++static void LzmaEnc_Finish(CLzmaEncHandle pp)
++{
++ #ifdef COMPRESS_MF_MT
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ if (p->mtMode)
++ MatchFinderMt_ReleaseStream(&p->matchFinderMt);
++ #endif
++}
++
++typedef struct _CSeqOutStreamBuf
++{
++ ISeqOutStream funcTable;
++ Byte *data;
++ SizeT rem;
++ Bool overflow;
++} CSeqOutStreamBuf;
++
++static size_t MyWrite(void *pp, const void *data, size_t size)
++{
++ CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
++ if (p->rem < size)
++ {
++ size = p->rem;
++ p->overflow = True;
++ }
++ memcpy(p->data, data, size);
++ p->rem -= size;
++ p->data += size;
++ return size;
++}
++
++
++static UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
++{
++ const CLzmaEnc *p = (CLzmaEnc *)pp;
++ return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
++}
++
++static const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
++{
++ const CLzmaEnc *p = (CLzmaEnc *)pp;
++ return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
++}
++
++static SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
++ Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ UInt64 nowPos64;
++ SRes res;
++ CSeqOutStreamBuf outStream;
++
++ outStream.funcTable.Write = MyWrite;
++ outStream.data = dest;
++ outStream.rem = *destLen;
++ outStream.overflow = False;
++
++ p->writeEndMark = False;
++ p->finished = False;
++ p->result = SZ_OK;
++
++ if (reInit)
++ LzmaEnc_Init(p);
++ LzmaEnc_InitPrices(p);
++ nowPos64 = p->nowPos64;
++ RangeEnc_Init(&p->rc);
++ p->rc.outStream = &outStream.funcTable;
++
++ res = LzmaEnc_CodeOneBlock(pp, True, desiredPackSize, *unpackSize);
++
++ *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
++ *destLen -= outStream.rem;
++ if (outStream.overflow)
++ return SZ_ERROR_OUTPUT_EOF;
++
++ return res;
++}
++
++SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
++ ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ SRes res = SZ_OK;
++
++ #ifdef COMPRESS_MF_MT
++ Byte allocaDummy[0x300];
++ int i = 0;
++ for (i = 0; i < 16; i++)
++ allocaDummy[i] = (Byte)i;
++ #endif
++
++ RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig));
++
++ for (;;)
++ {
++ res = LzmaEnc_CodeOneBlock(pp, False, 0, 0);
++ if (res != SZ_OK || p->finished != 0)
++ break;
++ if (progress != 0)
++ {
++ res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
++ if (res != SZ_OK)
++ {
++ res = SZ_ERROR_PROGRESS;
++ break;
++ }
++ }
++ }
++ LzmaEnc_Finish(pp);
++ return res;
++}
++
++SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
++{
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++ int i;
++ UInt32 dictSize = p->dictSize;
++ if (*size < LZMA_PROPS_SIZE)
++ return SZ_ERROR_PARAM;
++ *size = LZMA_PROPS_SIZE;
++ props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
++
++ for (i = 11; i <= 30; i++)
++ {
++ if (dictSize <= ((UInt32)2 << i))
++ {
++ dictSize = (2 << i);
++ break;
++ }
++ if (dictSize <= ((UInt32)3 << i))
++ {
++ dictSize = (3 << i);
++ break;
++ }
++ }
++
++ for (i = 0; i < 4; i++)
++ props[1 + i] = (Byte)(dictSize >> (8 * i));
++ return SZ_OK;
++}
++
++SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
++ int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ SRes res;
++ CLzmaEnc *p = (CLzmaEnc *)pp;
++
++ CSeqOutStreamBuf outStream;
++
++ LzmaEnc_SetInputBuf(p, src, srcLen);
++
++ outStream.funcTable.Write = MyWrite;
++ outStream.data = dest;
++ outStream.rem = *destLen;
++ outStream.overflow = False;
++
++ p->writeEndMark = writeEndMark;
++ res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable,
++ progress, alloc, allocBig);
++
++ *destLen -= outStream.rem;
++ if (outStream.overflow)
++ return SZ_ERROR_OUTPUT_EOF;
++ return res;
++}
++
++SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
++ const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
++ ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
++{
++ CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
++ SRes res;
++ if (p == 0)
++ return SZ_ERROR_MEM;
++
++ res = LzmaEnc_SetProps(p, props);
++ if (res == SZ_OK)
++ {
++ res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
++ if (res == SZ_OK)
++ res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
++ writeEndMark, progress, alloc, allocBig);
++ }
++
++ LzmaEnc_Destroy(p, alloc, allocBig);
++ return res;
++}
+--- a/jffsX-utils/mkfs.jffs2.c
++++ b/jffsX-utils/mkfs.jffs2.c
+@@ -1668,11 +1668,11 @@ int main(int argc, char **argv)
+ }
+ erase_block_size *= units;
+
+- /* If it's less than 8KiB, they're not allowed */
+- if (erase_block_size < 0x2000) {
+- fprintf(stderr, "Erase size 0x%x too small. Increasing to 8KiB minimum\n",
++ /* If it's less than 4KiB, they're not allowed */
++ if (erase_block_size < 0x1000) {
++ fprintf(stderr, "Erase size 0x%x too small. Increasing to 4KiB minimum\n",
+ erase_block_size);
+- erase_block_size = 0x2000;
++ erase_block_size = 0x1000;
+ }
+ break;
+ }
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -19,6 +19,10 @@ if WITH_ZSTD
+ AM_CPPFLAGS += -DWITH_ZSTD
+ endif
+
++if WITH_LZMA
++AM_CPPFLAGS += -DWITH_LZMA
++endif
++
+ if WITH_SELINUX
+ AM_CPPFLAGS += -DWITH_SELINUX
+ endif
+--- a/configure.ac
++++ b/configure.ac
+@@ -96,6 +96,10 @@ AC_ARG_WITH([zstd],
+ [AS_HELP_STRING([--with-zstd], [Support for ZSTD compression])],
+ [], [with_zstd="check"])
+
++AC_ARG_WITH([lzma],
++ [AS_HELP_STRING([--with-lzma], [Support for LZMA compression])],
++ [], [with_lzma="check"])
++
+ AC_ARG_WITH([selinux],
+ [AS_HELP_STRING([--with-selinux],
+ [Support for selinux extended attributes])],
+@@ -269,6 +273,7 @@ fi
+ AM_CONDITIONAL([WITH_LZO], [test "x$with_lzo" = "xyes"])
+ AM_CONDITIONAL([WITH_ZLIB], [test "x$with_zlib" = "xyes"])
+ AM_CONDITIONAL([WITH_ZSTD], [test "x$with_zstd" = "xyes"])
++AM_CONDITIONAL([WITH_LZMA], [test "x$with_lzma" = "xyes"])
+ AM_CONDITIONAL([WITH_XATTR], [test "x$with_xattr" = "xyes"])
+ AM_CONDITIONAL([WITH_SELINUX], [test "x$with_selinux" = "xyes"])
+ AM_CONDITIONAL([WITH_CRYPTO], [test "x$with_crypto" = "xyes"])
+@@ -313,6 +318,7 @@ AC_MSG_RESULT([
+ lzo support: ${with_lzo}
+ zlib support: ${with_zlib}
+ zstd support: ${with_zstd}
++ lzma support: ${with_lzma}
+ xattr/acl support: ${with_xattr}
+ SELinux support: ${with_selinux}
+ fscrypt support: ${with_crypto}
diff --git a/tools/mtd-utils/patches/134-freebsd_loff_t.patch b/tools/mtd-utils/patches/134-freebsd_loff_t.patch
new file mode 100644
index 0000000..2d141bd
--- /dev/null
+++ b/tools/mtd-utils/patches/134-freebsd_loff_t.patch
@@ -0,0 +1,14 @@
+--- a/include/mtd/mtd-abi.h
++++ b/include/mtd/mtd-abi.h
+@@ -171,9 +171,9 @@ struct otp_info {
+ /* Get info about OOB modes (e.g., RAW, PLACE, AUTO) - legacy interface */
+ #define MEMGETOOBSEL _IOR('M', 10, struct nand_oobinfo)
+ /* Check if an eraseblock is bad */
+-#define MEMGETBADBLOCK _IOW('M', 11, __kernel_loff_t)
++#define MEMGETBADBLOCK _IOW('M', 11, loff_t)
+ /* Mark an eraseblock as bad */
+-#define MEMSETBADBLOCK _IOW('M', 12, __kernel_loff_t)
++#define MEMSETBADBLOCK _IOW('M', 12, loff_t)
+ /* Set OTP (One-Time Programmable) mode (factory vs. user) */
+ #define OTPSELECT _IOR('M', 13, int)
+ /* Get number of OTP (One-Time Programmable) regions */
diff --git a/tools/mtd-utils/patches/200-libubigen-add-ubigen_write_terminator-function.patch b/tools/mtd-utils/patches/200-libubigen-add-ubigen_write_terminator-function.patch
new file mode 100644
index 0000000..90c9515
--- /dev/null
+++ b/tools/mtd-utils/patches/200-libubigen-add-ubigen_write_terminator-function.patch
@@ -0,0 +1,89 @@
+--- a/lib/libubigen.c
++++ b/lib/libubigen.c
+@@ -122,8 +122,9 @@ int ubigen_add_volume(const struct ubige
+ return 0;
+ }
+
+-void ubigen_init_ec_hdr(const struct ubigen_info *ui,
+- struct ubi_ec_hdr *hdr, long long ec)
++static void __ubigen_init_ec_hdr(const struct ubigen_info *ui,
++ struct ubi_ec_hdr *hdr, long long ec,
++ int eof)
+ {
+ uint32_t crc;
+
+@@ -136,10 +137,22 @@ void ubigen_init_ec_hdr(const struct ubi
+ hdr->data_offset = cpu_to_be32(ui->data_offs);
+ hdr->image_seq = cpu_to_be32(ui->image_seq);
+
++ if (eof) {
++ hdr->padding1[0] = 'E';
++ hdr->padding1[1] = 'O';
++ hdr->padding1[2] = 'F';
++ }
++
+ crc = mtd_crc32(UBI_CRC32_INIT, hdr, UBI_EC_HDR_SIZE_CRC);
+ hdr->hdr_crc = cpu_to_be32(crc);
+ }
+
++void ubigen_init_ec_hdr(const struct ubigen_info *ui,
++ struct ubi_ec_hdr *hdr, long long ec)
++{
++ __ubigen_init_ec_hdr(ui, hdr, ec, 0);
++}
++
+ void ubigen_init_vid_hdr(const struct ubigen_info *ui,
+ const struct ubigen_vol_info *vi,
+ struct ubi_vid_hdr *hdr, int lnum,
+@@ -307,6 +320,39 @@ int ubigen_write_layout_vol(const struct
+ }
+
+ free(outbuf);
++ return 0;
++
++out_free:
++ free(outbuf);
++ return -1;
++}
++
++int ubigen_write_eof_markers(const struct ubigen_info *ui, long long ec,
++ int count, int out_fd)
++{
++ char *outbuf;
++ int peb_size = ui->peb_size;
++
++ outbuf = malloc(peb_size);
++ if (!outbuf) {
++ sys_errmsg("cannot allocate %d bytes of memory", peb_size);
++ return -1;
++ }
++
++ memset(outbuf, 0xFF, peb_size);
++ __ubigen_init_ec_hdr(ui, (struct ubi_ec_hdr *)outbuf, ec, 1);
++
++ while (count) {
++ if (write(out_fd, outbuf, peb_size) != peb_size) {
++ sys_errmsg("cannot write %d bytes to the output file",
++ peb_size);
++ goto out_free;
++ }
++
++ count--;
++ }
++
++ free(outbuf);
+ return 0;
+
+ out_free:
+--- a/include/libubigen.h
++++ b/include/libubigen.h
+@@ -187,6 +187,9 @@ int ubigen_write_layout_vol(const struct
+ long long ec1, long long ec2,
+ struct ubi_vtbl_record *vtbl, int fd);
+
++int ubigen_write_eof_markers(const struct ubigen_info *ui, long long ec,
++ int count, int out_fd);
++
+ #ifdef __cplusplus
+ }
+ #endif
diff --git a/tools/mtd-utils/patches/201-ubinize-add-terminator-support.patch b/tools/mtd-utils/patches/201-ubinize-add-terminator-support.patch
new file mode 100644
index 0000000..d765cdc
--- /dev/null
+++ b/tools/mtd-utils/patches/201-ubinize-add-terminator-support.patch
@@ -0,0 +1,68 @@
+--- a/ubi-utils/ubinize.c
++++ b/ubi-utils/ubinize.c
+@@ -60,6 +60,8 @@ static const char optionsstr[] =
+ " (default is 1)\n"
+ "-Q, --image-seq=<num> 32-bit UBI image sequence number to use\n"
+ " (by default a random number is picked)\n"
++"-E, --eof-markers=<num> number of eof-markers to put at the end of the\n"
++" output image\n"
+ "-v, --verbose be verbose\n"
+ "-h, --help print help message\n"
+ "-V, --version print program version\n\n";
+@@ -79,6 +81,7 @@ static const struct option long_options[
+ { .name = "erase-counter", .has_arg = 1, .flag = NULL, .val = 'e' },
+ { .name = "ubi-ver", .has_arg = 1, .flag = NULL, .val = 'x' },
+ { .name = "image-seq", .has_arg = 1, .flag = NULL, .val = 'Q' },
++ { .name = "eof-markers", .has_arg = 1, .flag = NULL, .val = 'E' },
+ { .name = "verbose", .has_arg = 0, .flag = NULL, .val = 'v' },
+ { .name = "help", .has_arg = 0, .flag = NULL, .val = 'h' },
+ { .name = "version", .has_arg = 0, .flag = NULL, .val = 'V' },
+@@ -98,6 +101,7 @@ struct args {
+ uint32_t image_seq;
+ int verbose;
+ dictionary *dict;
++ int eof_markers;
+ };
+
+ static struct args args = {
+@@ -116,7 +120,7 @@ static int parse_opt(int argc, char * co
+ int key, error = 0;
+ unsigned long int image_seq;
+
+- key = getopt_long(argc, argv, "o:p:m:s:O:e:x:Q:vhV", long_options, NULL);
++ key = getopt_long(argc, argv, "o:p:m:s:O:e:x:Q:E:vhV", long_options, NULL);
+ if (key == -1)
+ break;
+
+@@ -176,6 +180,12 @@ static int parse_opt(int argc, char * co
+ args.image_seq = image_seq;
+ break;
+
++ case 'E':
++ args.eof_markers = simple_strtoul(optarg, &error);
++ if (error)
++ return errmsg("bad number of eof-markers: \"%s\"", optarg);
++ break;
++
+ case 'v':
+ args.verbose = 1;
+ break;
+@@ -582,6 +592,18 @@ int main(int argc, char * const argv[])
+ printf("\n");
+ }
+
++ if (args.eof_markers) {
++ verbose(args.verbose, "writing %d eof-marker blocks",
++ args.eof_markers);
++
++ err = ubigen_write_eof_markers(&ui, args.ec, args.eof_markers,
++ args.out_fd);
++ if (err) {
++ errmsg("cannot write eof-marker blocks");
++ goto out_free;
++ }
++ }
++
+ verbose(args.verbose, "writing layout volume");
+
+ err = ubigen_write_layout_vol(&ui, 0, 1, args.ec, args.ec, vtbl, args.out_fd);
diff --git a/tools/mtd-utils/patches/320-mkfs.jffs2-SOURCE_DATE_EPOCH.patch b/tools/mtd-utils/patches/320-mkfs.jffs2-SOURCE_DATE_EPOCH.patch
new file mode 100644
index 0000000..a1703eb
--- /dev/null
+++ b/tools/mtd-utils/patches/320-mkfs.jffs2-SOURCE_DATE_EPOCH.patch
@@ -0,0 +1,60 @@
+--- a/jffsX-utils/mkfs.jffs2.c
++++ b/jffsX-utils/mkfs.jffs2.c
+@@ -109,7 +109,7 @@ static char *rootdir = default_rootdir;
+ static int verbose = 0;
+ static int squash_uids = 0;
+ static int squash_perms = 0;
+-static int fake_times = 0;
++static time_t fixed_timestamp = -1;
+ int target_endian = __BYTE_ORDER;
+
+ static uint32_t find_hardlink(struct filesystem_entry *e)
+@@ -251,8 +251,8 @@ static struct filesystem_entry *add_host
+ mode &= ~(S_ISUID | S_ISGID);
+ }
+ }
+- if (fake_times) {
+- timestamp = 0;
++ if (fixed_timestamp != -1) {
++ timestamp = fixed_timestamp;
+ }
+
+ entry = xcalloc(1, sizeof(struct filesystem_entry));
+@@ -1559,6 +1559,20 @@ static void parse_image(void){
+ close(in_fd);
+ }
+
++static void set_source_date_epoch() {
++ char *env = getenv("SOURCE_DATE_EPOCH");
++ char *endptr = env;
++ errno = 0;
++ if (env && *env) {
++ fixed_timestamp = strtoull(env, &endptr, 10);
++ if (errno || (endptr && *endptr != '\0')) {
++ fprintf(stderr, "Invalid SOURCE_DATE_EPOCH");
++ exit(1);
++ }
++ }
++}
++
++
+ int main(int argc, char **argv)
+ {
+ int c, opt;
+@@ -1577,6 +1591,7 @@ int main(int argc, char **argv)
+ warn_page_size = 1; /* warn user if page size not 4096 */
+
+ jffs2_compressors_init();
++ set_source_date_epoch();
+
+ while ((opt = getopt_long(argc, argv,
+ "D:d:r:s:o:qUPfh?vVe:lbp::nc:m:x:X:Lty:i:", long_options, &c)) >= 0)
+@@ -1627,7 +1642,7 @@ int main(int argc, char **argv)
+ break;
+
+ case 'f':
+- fake_times = 1;
++ fixed_timestamp = 0;
+ break;
+
+ case 'h':
diff --git a/tools/mtools/Makefile b/tools/mtools/Makefile
new file mode 100644
index 0000000..b810918
--- /dev/null
+++ b/tools/mtools/Makefile
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2012-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=mtools
+PKG_VERSION:=4.0.43
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=541e179665dc4e272b9602f2074243591a157da89cc47064da8c5829dbd2b339
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += --without-x
+
+HOST_CONFIGURE_VARS += \
+ ac_cv_header_iconv_h=no
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR) mcopy mmd
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/mcopy $(STAGING_DIR_HOST)/bin/
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/mmd $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/mcopy
+ rm -f $(STAGING_DIR_HOST)/bin/mmd
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/ninja/Makefile b/tools/ninja/Makefile
new file mode 100644
index 0000000..d79f3c5
--- /dev/null
+++ b/tools/ninja/Makefile
@@ -0,0 +1,36 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=ninja
+PKG_VERSION:=1.12.1
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://codeload.github.com/ninja-build/ninja/tar.gz/v$(PKG_VERSION)?
+PKG_HASH:=821bdff48a3f683bc4bb3b6f0b5fe7b2d647cf65d52aeb63328c91a6c6df285a
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+ cd $(HOST_BUILD_DIR) && \
+ $(HOST_MAKE_VARS) \
+ CXX="$(HOSTCXX_NOCACHE)" \
+ $(STAGING_DIR_HOST)/bin/$(PYTHON) configure.py \
+ $(if $(shell $(STAGING_DIR_HOST)/bin/ninja --version),,--bootstrap) \
+ --no-rebuild \
+ --verbose
+ -$(Host/Install)
+endef
+
+define Host/Compile
+ +$(NINJA) -C $(HOST_BUILD_DIR)
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/ninja $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/ninja
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/ninja/patches/001-backport-gtest.patch b/tools/ninja/patches/001-backport-gtest.patch
new file mode 100644
index 0000000..1440f29
--- /dev/null
+++ b/tools/ninja/patches/001-backport-gtest.patch
@@ -0,0 +1,153 @@
+From afcd4a146fb82843f6ff695f89504ce4ca65ddfd Mon Sep 17 00:00:00 2001
+From: David 'Digit' Turner <digit+github@google.com>
+Date: Sun, 12 May 2024 23:45:28 +0200
+Subject: [PATCH] configure.py: Support --gtest-source-dir to build tests.
+
+Allow the Ninja build plan generated by configure.py to
+build `ninja_test` by compiling GoogleTest from source if
+the path to the library if passed through the new option
+`--gtest-source-dir` or the GTEST_SOURCE_DIR environment
+variable.
+
+For simplicity, probing for an installed version of the
+library, and linking to it, is not supported (use the
+CMake build for this).
+
+This also removes the obsolete `--gtest-dir` option.
+
++ Update README.md
+
+Fixes #2447
+---
+ README.md | 13 ++++++++
+ configure.py | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++-
+ 2 files changed, 95 insertions(+), 1 deletion(-)
+
+--- a/README.md
++++ b/README.md
+@@ -34,6 +34,19 @@ via CMake. For more details see
+ This will generate the `ninja` binary and a `build.ninja` file you can now use
+ to build Ninja with itself.
+
++If you have a GoogleTest source directory, you can build the tests
++by passing its path with `--gtest-source-dir=PATH` option, or the
++`GTEST_SOURCE_DIR` environment variable, e.g.:
++
++```
++./configure.py --bootstrap --gtest-source-dir=/path/to/googletest
++./ninja all # build ninja_test and other auxiliary binaries
++./ninja_test` # run the unit-test suite.
++```
++
++Use the CMake build below if you want to use a preinstalled binary
++version of the library.
++
+ ### CMake
+
+ ```
+--- a/configure.py
++++ b/configure.py
+@@ -213,7 +213,10 @@ parser.add_option('--debug', action='sto
+ parser.add_option('--profile', metavar='TYPE',
+ choices=profilers,
+ help='enable profiling (' + '/'.join(profilers) + ')',)
+-parser.add_option('--with-gtest', metavar='PATH', help='ignored')
++parser.add_option('--gtest-source-dir', metavar='PATH',
++ help='Path to GoogleTest source directory. If not provided ' +
++ 'GTEST_SOURCE_DIR will be probed in the environment. ' +
++ 'Tests will not be built without a value.')
+ parser.add_option('--with-python', metavar='EXE',
+ help='use EXE as the Python interpreter',
+ default=os.path.basename(sys.executable))
+@@ -425,6 +428,7 @@ n.variable('cflags', ' '.join(shell_esca
+ if 'LDFLAGS' in configure_env:
+ ldflags.append(configure_env['LDFLAGS'])
+ n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
++
+ n.newline()
+
+ if platform.is_msvc():
+@@ -582,6 +586,83 @@ if options.bootstrap:
+ # build.ninja file.
+ n = ninja_writer
+
++# Build the ninja_test executable only if the GTest source directory
++# is provided explicitly. Either from the environment with GTEST_SOURCE_DIR
++# or with the --gtest-source-dir command-line option.
++#
++# Do not try to look for an installed binary version, and link against it
++# because doing so properly is platform-specific (use the CMake build for
++# this).
++if options.gtest_source_dir:
++ gtest_src_dir = options.gtest_source_dir
++else:
++ gtest_src_dir = os.environ.get('GTEST_SOURCE_DIR')
++
++if gtest_src_dir:
++ # Verify GoogleTest source directory, and add its include directory
++ # to the global include search path (even for non-test sources) to
++ # keep the build plan generation simple.
++ gtest_all_cc = os.path.join(gtest_src_dir, 'googletest', 'src', 'gtest-all.cc')
++ if not os.path.exists(gtest_all_cc):
++ print('ERROR: Missing GoogleTest source file: %s' % gtest_all_cc)
++ sys.exit(1)
++
++ n.comment('Tests all build into ninja_test executable.')
++
++ # Test-specific version of cflags, must include the GoogleTest
++ # include directory. Also GoogleTest can only build with a C++14 compiler.
++ test_cflags = [f.replace('std=c++11', 'std=c++14') for f in cflags]
++ test_cflags.append('-I' + os.path.join(gtest_src_dir, 'googletest', 'include'))
++
++ test_variables = [('cflags', test_cflags)]
++ if platform.is_msvc():
++ test_variables += [('pdb', 'ninja_test.pdb')]
++
++ test_names = [
++ 'build_log_test',
++ 'build_test',
++ 'clean_test',
++ 'clparser_test',
++ 'depfile_parser_test',
++ 'deps_log_test',
++ 'disk_interface_test',
++ 'dyndep_parser_test',
++ 'edit_distance_test',
++ 'graph_test',
++ 'json_test',
++ 'lexer_test',
++ 'manifest_parser_test',
++ 'ninja_test',
++ 'state_test',
++ 'string_piece_util_test',
++ 'subprocess_test',
++ 'test',
++ 'util_test',
++ ]
++ if platform.is_windows():
++ test_names += [
++ 'includes_normalize_test',
++ 'msvc_helper_test',
++ ]
++
++ objs = []
++ for name in test_names:
++ objs += cxx(name, variables=test_variables)
++
++ # Build GTest as a monolithic source file.
++ # This requires one extra include search path, so replace the
++ # value of 'cflags' in our list.
++ gtest_all_variables = test_variables[1:] + [
++ ('cflags', test_cflags + ['-I' + os.path.join(gtest_src_dir, 'googletest') ]),
++ ]
++ # Do not use cxx() directly to ensure the object file is under $builddir.
++ objs += n.build(built('gtest_all' + objext), 'cxx', gtest_all_cc, variables=gtest_all_variables)
++
++ ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
++ variables=[('libs', libs)])
++ n.newline()
++ all_targets += ninja_test
++
+ n.comment('Ancillary executables.')
+
+ if platform.is_aix() and '-maix64' not in ldflags:
diff --git a/tools/ninja/patches/010-bootstrap-configure-only.patch b/tools/ninja/patches/010-bootstrap-configure-only.patch
new file mode 100644
index 0000000..4785ac6
--- /dev/null
+++ b/tools/ninja/patches/010-bootstrap-configure-only.patch
@@ -0,0 +1,24 @@
+--- a/configure.py
++++ b/configure.py
+@@ -198,6 +198,8 @@ parser = OptionParser()
+ profilers = ['gmon', 'pprof']
+ parser.add_option('--bootstrap', action='store_true',
+ help='bootstrap a ninja binary from nothing')
++parser.add_option('--no-rebuild', action='store_true',
++ help='let user execute ninja after build.ninja generation')
+ parser.add_option('--verbose', action='store_true',
+ help='enable verbose build')
+ parser.add_option('--platform',
+@@ -756,7 +758,11 @@ n.build('all', 'phony', all_targets)
+ n.close()
+ print('wrote %s.' % BUILD_FILENAME)
+
+-if options.bootstrap:
++if options.bootstrap and options.no_rebuild:
++ print('bootstrap complete. execute ninja in this directory...')
++ print(os.getcwd())
++
++elif options.bootstrap:
+ print('bootstrap complete. rebuilding...')
+
+ rebuild_args = []
diff --git a/tools/ninja/patches/100-make_jobserver_support.patch b/tools/ninja/patches/100-make_jobserver_support.patch
new file mode 100644
index 0000000..82ecf02
--- /dev/null
+++ b/tools/ninja/patches/100-make_jobserver_support.patch
@@ -0,0 +1,2143 @@
+From afec30f5caf4b051827ffdd822ebd27c58219fee Mon Sep 17 00:00:00 2001
+From: Stefan Becker <stefanb@gpartner-nvidia.com>
+Date: Tue, 22 Mar 2016 13:48:07 +0200
+Subject: [PATCH 01/11] Add GNU make jobserver client support
+
+- add new TokenPool interface
+- GNU make implementation for TokenPool parses and verifies the magic
+ information from the MAKEFLAGS environment variable
+- RealCommandRunner tries to acquire TokenPool
+ * if no token pool is available then there is no change in behaviour
+- When a token pool is available then RealCommandRunner behaviour
+ changes as follows
+ * CanRunMore() only returns true if TokenPool::Acquire() returns true
+ * StartCommand() calls TokenPool::Reserve()
+ * WaitForCommand() calls TokenPool::Release()
+
+Documentation for GNU make jobserver
+
+ http://make.mad-scientist.net/papers/jobserver-implementation/
+
+--- a/configure.py
++++ b/configure.py
+@@ -543,11 +543,13 @@ for name in ['build',
+ 'state',
+ 'status',
+ 'string_piece_util',
++ 'tokenpool-gnu-make',
+ 'util',
+ 'version']:
+ objs += cxx(name, variables=cxxvariables)
+ if platform.is_windows():
+ for name in ['subprocess-win32',
++ 'tokenpool-gnu-make-win32',
+ 'includes_normalize-win32',
+ 'msvc_helper-win32',
+ 'msvc_helper_main-win32']:
+@@ -556,7 +558,9 @@ if platform.is_windows():
+ objs += cxx('minidump-win32', variables=cxxvariables)
+ objs += cc('getopt')
+ else:
+- objs += cxx('subprocess-posix')
++ for name in ['subprocess-posix',
++ 'tokenpool-gnu-make-posix']:
++ objs += cxx(name)
+ if platform.is_aix():
+ objs += cc('getopt')
+ if platform.is_msvc():
+@@ -639,6 +643,7 @@ if gtest_src_dir:
+ 'string_piece_util_test',
+ 'subprocess_test',
+ 'test',
++ 'tokenpool_test',
+ 'util_test',
+ ]
+ if platform.is_windows():
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -39,6 +39,7 @@
+ #include "state.h"
+ #include "status.h"
+ #include "subprocess.h"
++#include "tokenpool.h"
+ #include "util.h"
+
+ using namespace std;
+@@ -50,24 +51,29 @@ struct DryRunCommandRunner : public Comm
+ virtual ~DryRunCommandRunner() {}
+
+ // Overridden from CommandRunner:
+- virtual size_t CanRunMore() const;
++ virtual size_t CanRunMore();
++ virtual bool AcquireToken();
+ virtual bool StartCommand(Edge* edge);
+- virtual bool WaitForCommand(Result* result);
++ virtual bool WaitForCommand(Result* result, bool more_ready);
+
+ private:
+ queue<Edge*> finished_;
+ };
+
+-size_t DryRunCommandRunner::CanRunMore() const {
++size_t DryRunCommandRunner::CanRunMore() {
+ return SIZE_MAX;
+ }
+
++bool DryRunCommandRunner::AcquireToken() {
++ return true;
++}
++
+ bool DryRunCommandRunner::StartCommand(Edge* edge) {
+ finished_.push(edge);
+ return true;
+ }
+
+-bool DryRunCommandRunner::WaitForCommand(Result* result) {
++bool DryRunCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+ if (finished_.empty())
+ return false;
+
+@@ -160,7 +166,7 @@ void Plan::EdgeWanted(const Edge* edge)
+ }
+
+ Edge* Plan::FindWork() {
+- if (ready_.empty())
++ if (!more_ready())
+ return NULL;
+
+ Edge* work = ready_.top();
+@@ -595,19 +601,39 @@ void Plan::Dump() const {
+ }
+
+ struct RealCommandRunner : public CommandRunner {
+- explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
+- virtual ~RealCommandRunner() {}
+- virtual size_t CanRunMore() const;
++ explicit RealCommandRunner(const BuildConfig& config);
++ virtual ~RealCommandRunner();
++ virtual size_t CanRunMore();
++ virtual bool AcquireToken();
+ virtual bool StartCommand(Edge* edge);
+- virtual bool WaitForCommand(Result* result);
++ virtual bool WaitForCommand(Result* result, bool more_ready);
+ virtual vector<Edge*> GetActiveEdges();
+ virtual void Abort();
+
+ const BuildConfig& config_;
++ // copy of config_.max_load_average; can be modified by TokenPool setup
++ double max_load_average_;
+ SubprocessSet subprocs_;
++ TokenPool* tokens_;
+ map<const Subprocess*, Edge*> subproc_to_edge_;
+ };
+
++RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
++ max_load_average_ = config.max_load_average;
++ if ((tokens_ = TokenPool::Get()) != NULL) {
++ if (!tokens_->Setup(config_.parallelism_from_cmdline,
++ config_.verbosity == BuildConfig::VERBOSE,
++ max_load_average_)) {
++ delete tokens_;
++ tokens_ = NULL;
++ }
++ }
++}
++
++RealCommandRunner::~RealCommandRunner() {
++ delete tokens_;
++}
++
+ vector<Edge*> RealCommandRunner::GetActiveEdges() {
+ vector<Edge*> edges;
+ for (map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.begin();
+@@ -618,9 +644,11 @@ vector<Edge*> RealCommandRunner::GetActi
+
+ void RealCommandRunner::Abort() {
+ subprocs_.Clear();
++ if (tokens_)
++ tokens_->Clear();
+ }
+
+-size_t RealCommandRunner::CanRunMore() const {
++size_t RealCommandRunner::CanRunMore() {
+ size_t subproc_number =
+ subprocs_.running_.size() + subprocs_.finished_.size();
+
+@@ -635,6 +663,13 @@ size_t RealCommandRunner::CanRunMore() c
+ if (capacity < 0)
+ capacity = 0;
+
++ if (tokens_) {
++ if (AcquireToken())
++ return SIZE_MAX;
++ else
++ capacity = 0;
++ }
++
+ if (capacity == 0 && subprocs_.running_.empty())
+ // Ensure that we make progress.
+ capacity = 1;
+@@ -642,24 +677,42 @@ size_t RealCommandRunner::CanRunMore() c
+ return capacity;
+ }
+
++bool RealCommandRunner::AcquireToken() {
++ return (!tokens_ || tokens_->Acquire());
++}
++
+ bool RealCommandRunner::StartCommand(Edge* edge) {
+ string command = edge->EvaluateCommand();
+ Subprocess* subproc = subprocs_.Add(command, edge->use_console());
+ if (!subproc)
+ return false;
++ if (tokens_)
++ tokens_->Reserve();
+ subproc_to_edge_.insert(make_pair(subproc, edge));
+
+ return true;
+ }
+
+-bool RealCommandRunner::WaitForCommand(Result* result) {
++bool RealCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+ Subprocess* subproc;
+- while ((subproc = subprocs_.NextFinished()) == NULL) {
+- bool interrupted = subprocs_.DoWork();
++ subprocs_.ResetTokenAvailable();
++ while (((subproc = subprocs_.NextFinished()) == NULL) &&
++ !subprocs_.IsTokenAvailable()) {
++ bool interrupted = subprocs_.DoWork(more_ready ? tokens_ : NULL);
+ if (interrupted)
+ return false;
+ }
+
++ // token became available
++ if (subproc == NULL) {
++ result->status = ExitTokenAvailable;
++ return true;
++ }
++
++ // command completed
++ if (tokens_)
++ tokens_->Release();
++
+ result->status = subproc->Finish();
+ result->output = subproc->GetOutput();
+
+@@ -790,7 +843,8 @@ bool Builder::Build(string* err) {
+ // Second, we attempt to wait for / reap the next finished command.
+ while (plan_.more_to_do()) {
+ // See if we can start any more commands.
+- if (failures_allowed) {
++ bool can_run_more = failures_allowed && plan_.more_ready();
++ if (can_run_more) {
+ size_t capacity = command_runner_->CanRunMore();
+ while (capacity > 0) {
+ Edge* edge = plan_.FindWork();
+@@ -833,7 +887,7 @@ bool Builder::Build(string* err) {
+ // See if we can reap any finished commands.
+ if (pending_commands) {
+ CommandRunner::Result result;
+- if (!command_runner_->WaitForCommand(&result) ||
++ if (!command_runner_->WaitForCommand(&result, can_run_more) ||
+ result.status == ExitInterrupted) {
+ Cleanup();
+ status_->BuildFinished();
+@@ -841,6 +895,10 @@ bool Builder::Build(string* err) {
+ return false;
+ }
+
++ // We might be able to start another command; start the main loop over.
++ if (result.status == ExitTokenAvailable)
++ continue;
++
+ --pending_commands;
+ if (!FinishCommand(&result, err)) {
+ Cleanup();
+--- a/src/build.h
++++ b/src/build.h
+@@ -51,6 +51,9 @@ struct Plan {
+ /// Returns true if there's more work to be done.
+ bool more_to_do() const { return wanted_edges_ > 0 && command_edges_ > 0; }
+
++ /// Returns true if there's more edges ready to start
++ bool more_ready() const { return !ready_.empty(); }
++
+ /// Dumps the current state of the plan.
+ void Dump() const;
+
+@@ -145,7 +148,8 @@ private:
+ /// RealCommandRunner is an implementation that actually runs commands.
+ struct CommandRunner {
+ virtual ~CommandRunner() {}
+- virtual size_t CanRunMore() const = 0;
++ virtual size_t CanRunMore() = 0;
++ virtual bool AcquireToken() = 0;
+ virtual bool StartCommand(Edge* edge) = 0;
+
+ /// The result of waiting for a command.
+@@ -157,7 +161,9 @@ struct CommandRunner {
+ bool success() const { return status == ExitSuccess; }
+ };
+ /// Wait for a command to complete, or return false if interrupted.
+- virtual bool WaitForCommand(Result* result) = 0;
++ /// If more_ready is true then the optional TokenPool is monitored too
++ /// and we return when a token becomes available.
++ virtual bool WaitForCommand(Result* result, bool more_ready) = 0;
+
+ virtual std::vector<Edge*> GetActiveEdges() { return std::vector<Edge*>(); }
+ virtual void Abort() {}
+@@ -165,7 +171,8 @@ struct CommandRunner {
+
+ /// Options (e.g. verbosity, parallelism) passed to a build.
+ struct BuildConfig {
+- BuildConfig() : verbosity(NORMAL), dry_run(false), parallelism(1),
++ BuildConfig() : verbosity(NORMAL), dry_run(false),
++ parallelism(1), parallelism_from_cmdline(false),
+ failures_allowed(1), max_load_average(-0.0f) {}
+
+ enum Verbosity {
+@@ -177,6 +184,7 @@ struct BuildConfig {
+ Verbosity verbosity;
+ bool dry_run;
+ int parallelism;
++ bool parallelism_from_cmdline;
+ int failures_allowed;
+ /// The maximum load average we must not exceed. A negative value
+ /// means that we do not have any limit.
+--- /dev/null
++++ b/src/tokenpool-gnu-make.cc
+@@ -0,0 +1,108 @@
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#include "tokenpool-gnu-make.h"
++
++#include <stdlib.h>
++#include <stdio.h>
++#include <string.h>
++
++#include "line_printer.h"
++
++// TokenPool implementation for GNU make jobserver - common bits
++// every instance owns an implicit token -> available_ == 1
++GNUmakeTokenPool::GNUmakeTokenPool() : available_(1), used_(0) {
++}
++
++GNUmakeTokenPool::~GNUmakeTokenPool() {
++}
++
++bool GNUmakeTokenPool::Setup(bool ignore,
++ bool verbose,
++ double& max_load_average) {
++ const char* value = GetEnv("MAKEFLAGS");
++ if (!value)
++ return false;
++
++ // GNU make <= 4.1
++ const char* jobserver = strstr(value, "--jobserver-fds=");
++ if (!jobserver)
++ // GNU make => 4.2
++ jobserver = strstr(value, "--jobserver-auth=");
++ if (jobserver) {
++ LinePrinter printer;
++
++ if (ignore) {
++ printer.PrintOnNewLine("ninja: warning: -jN forced on command line; ignoring GNU make jobserver.\n");
++ } else {
++ if (ParseAuth(jobserver)) {
++ const char* l_arg = strstr(value, " -l");
++ int load_limit = -1;
++
++ if (verbose) {
++ printer.PrintOnNewLine("ninja: using GNU make jobserver.\n");
++ }
++
++ // translate GNU make -lN to ninja -lN
++ if (l_arg &&
++ (sscanf(l_arg + 3, "%d ", &load_limit) == 1) &&
++ (load_limit > 0)) {
++ max_load_average = load_limit;
++ }
++
++ return true;
++ }
++ }
++ }
++
++ return false;
++}
++
++bool GNUmakeTokenPool::Acquire() {
++ if (available_ > 0)
++ return true;
++
++ if (AcquireToken()) {
++ // token acquired
++ available_++;
++ return true;
++ }
++
++ // no token available
++ return false;
++}
++
++void GNUmakeTokenPool::Reserve() {
++ available_--;
++ used_++;
++}
++
++void GNUmakeTokenPool::Return() {
++ if (ReturnToken())
++ available_--;
++}
++
++void GNUmakeTokenPool::Release() {
++ available_++;
++ used_--;
++ if (available_ > 1)
++ Return();
++}
++
++void GNUmakeTokenPool::Clear() {
++ while (used_ > 0)
++ Release();
++ while (available_ > 1)
++ Return();
++}
+--- /dev/null
++++ b/src/tokenpool.h
+@@ -0,0 +1,42 @@
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#ifdef _WIN32
++#include <windows.h>
++#endif
++
++// interface to token pool
++struct TokenPool {
++ virtual ~TokenPool() {}
++
++ virtual bool Acquire() = 0;
++ virtual void Reserve() = 0;
++ virtual void Release() = 0;
++ virtual void Clear() = 0;
++
++ // returns false if token pool setup failed
++ virtual bool Setup(bool ignore, bool verbose, double& max_load_average) = 0;
++
++#ifdef _WIN32
++ virtual void WaitForTokenAvailability(HANDLE ioport) = 0;
++ // returns true if a token has become available
++ // key is result from GetQueuedCompletionStatus()
++ virtual bool TokenIsAvailable(ULONG_PTR key) = 0;
++#else
++ virtual int GetMonitorFd() = 0;
++#endif
++
++ // returns NULL if token pool is not available
++ static TokenPool* Get();
++};
+--- a/src/build_test.cc
++++ b/src/build_test.cc
+@@ -15,6 +15,7 @@
+ #include "build.h"
+
+ #include <assert.h>
++#include <stdarg.h>
+ #include <climits>
+ #include <stdint.h>
+
+@@ -521,9 +522,10 @@ struct FakeCommandRunner : public Comman
+ max_active_edges_(1), fs_(fs) {}
+
+ // CommandRunner impl
+- virtual size_t CanRunMore() const;
++ virtual size_t CanRunMore();
++ virtual bool AcquireToken();
+ virtual bool StartCommand(Edge* edge);
+- virtual bool WaitForCommand(Result* result);
++ virtual bool WaitForCommand(Result* result, bool more_ready);
+ virtual vector<Edge*> GetActiveEdges();
+ virtual void Abort();
+
+@@ -622,13 +624,17 @@ void BuildTest::RebuildTarget(const stri
+ builder.command_runner_.release();
+ }
+
+-size_t FakeCommandRunner::CanRunMore() const {
++size_t FakeCommandRunner::CanRunMore() {
+ if (active_edges_.size() < max_active_edges_)
+ return SIZE_MAX;
+
+ return 0;
+ }
+
++bool FakeCommandRunner::AcquireToken() {
++ return true;
++}
++
+ bool FakeCommandRunner::StartCommand(Edge* edge) {
+ assert(active_edges_.size() < max_active_edges_);
+ assert(find(active_edges_.begin(), active_edges_.end(), edge)
+@@ -720,7 +726,7 @@ bool FakeCommandRunner::StartCommand(Edg
+ return true;
+ }
+
+-bool FakeCommandRunner::WaitForCommand(Result* result) {
++bool FakeCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+ if (active_edges_.empty())
+ return false;
+
+@@ -4380,3 +4386,355 @@ TEST_F(BuildTest, ValidationWithCircular
+ EXPECT_FALSE(builder_.AddTarget("out", &err));
+ EXPECT_EQ("dependency cycle: validate -> validate_in -> validate", err);
+ }
++
++/// The token tests are concerned with the main loop functionality when
++// the CommandRunner has an active TokenPool. It is therefore intentional
++// that the plan doesn't complete and that builder_.Build() returns false!
++
++/// Fake implementation of CommandRunner that simulates a TokenPool
++struct FakeTokenCommandRunner : public CommandRunner {
++ explicit FakeTokenCommandRunner() {}
++
++ // CommandRunner impl
++ virtual bool CanRunMore();
++ virtual bool AcquireToken();
++ virtual bool StartCommand(Edge* edge);
++ virtual bool WaitForCommand(Result* result, bool more_ready);
++ virtual vector<Edge*> GetActiveEdges();
++ virtual void Abort();
++
++ vector<string> commands_ran_;
++ vector<Edge *> edges_;
++
++ vector<bool> acquire_token_;
++ vector<bool> can_run_more_;
++ vector<bool> wait_for_command_;
++};
++
++bool FakeTokenCommandRunner::CanRunMore() {
++ if (can_run_more_.size() == 0) {
++ EXPECT_FALSE("unexpected call to CommandRunner::CanRunMore()");
++ return false;
++ }
++
++ bool result = can_run_more_[0];
++
++ can_run_more_.erase(
++ can_run_more_.begin()
++ );
++
++ return result;
++}
++
++bool FakeTokenCommandRunner::AcquireToken() {
++ if (acquire_token_.size() == 0) {
++ EXPECT_FALSE("unexpected call to CommandRunner::AcquireToken()");
++ return false;
++ }
++
++ bool result = acquire_token_[0];
++ acquire_token_.erase(acquire_token_.begin());
++ return result;
++}
++
++bool FakeTokenCommandRunner::StartCommand(Edge* edge) {
++ commands_ran_.push_back(edge->EvaluateCommand());
++ edges_.push_back(edge);
++ return true;
++}
++
++bool FakeTokenCommandRunner::WaitForCommand(Result* result, bool more_ready) {
++ if (wait_for_command_.size() == 0) {
++ EXPECT_FALSE("unexpected call to CommandRunner::WaitForCommand()");
++ return false;
++ }
++
++ bool expected = wait_for_command_[0];
++ if (expected != more_ready) {
++ EXPECT_EQ(expected, more_ready);
++ return false;
++ }
++ wait_for_command_.erase(wait_for_command_.begin());
++
++ if (edges_.size() == 0)
++ return false;
++
++ Edge* edge = edges_[0];
++ result->edge = edge;
++
++ if (more_ready &&
++ (edge->rule().name() == "token-available")) {
++ result->status = ExitTokenAvailable;
++ } else {
++ edges_.erase(edges_.begin());
++ result->status = ExitSuccess;
++ }
++
++ return true;
++}
++
++vector<Edge*> FakeTokenCommandRunner::GetActiveEdges() {
++ return edges_;
++}
++
++void FakeTokenCommandRunner::Abort() {
++ edges_.clear();
++}
++
++struct BuildTokenTest : public BuildTest {
++ virtual void SetUp();
++ virtual void TearDown();
++
++ FakeTokenCommandRunner token_command_runner_;
++
++ void ExpectAcquireToken(int count, ...);
++ void ExpectCanRunMore(int count, ...);
++ void ExpectWaitForCommand(int count, ...);
++
++private:
++ void EnqueueBooleans(vector<bool>& booleans, int count, va_list ap);
++};
++
++void BuildTokenTest::SetUp() {
++ BuildTest::SetUp();
++
++ // replace FakeCommandRunner with FakeTokenCommandRunner
++ builder_.command_runner_.release();
++ builder_.command_runner_.reset(&token_command_runner_);
++}
++void BuildTokenTest::TearDown() {
++ EXPECT_EQ(0u, token_command_runner_.acquire_token_.size());
++ EXPECT_EQ(0u, token_command_runner_.can_run_more_.size());
++ EXPECT_EQ(0u, token_command_runner_.wait_for_command_.size());
++
++ BuildTest::TearDown();
++}
++
++void BuildTokenTest::ExpectAcquireToken(int count, ...) {
++ va_list ap;
++ va_start(ap, count);
++ EnqueueBooleans(token_command_runner_.acquire_token_, count, ap);
++ va_end(ap);
++}
++
++void BuildTokenTest::ExpectCanRunMore(int count, ...) {
++ va_list ap;
++ va_start(ap, count);
++ EnqueueBooleans(token_command_runner_.can_run_more_, count, ap);
++ va_end(ap);
++}
++
++void BuildTokenTest::ExpectWaitForCommand(int count, ...) {
++ va_list ap;
++ va_start(ap, count);
++ EnqueueBooleans(token_command_runner_.wait_for_command_, count, ap);
++ va_end(ap);
++}
++
++void BuildTokenTest::EnqueueBooleans(vector<bool>& booleans, int count, va_list ap) {
++ while (count--) {
++ int value = va_arg(ap, int);
++ booleans.push_back(!!value); // force bool
++ }
++}
++
++TEST_F(BuildTokenTest, DoNotAquireToken) {
++ // plan should execute one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++ ASSERT_EQ("", err);
++
++ // pretend we can't run anything
++ ExpectCanRunMore(1, false);
++
++ EXPECT_FALSE(builder_.Build(&err));
++ EXPECT_EQ("stuck [this is a bug]", err);
++
++ EXPECT_EQ(0u, token_command_runner_.commands_ran_.size());
++}
++
++TEST_F(BuildTokenTest, DoNotStartWithoutToken) {
++ // plan should execute one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++ ASSERT_EQ("", err);
++
++ // we could run a command but do not have a token for it
++ ExpectCanRunMore(1, true);
++ ExpectAcquireToken(1, false);
++
++ EXPECT_FALSE(builder_.Build(&err));
++ EXPECT_EQ("stuck [this is a bug]", err);
++
++ EXPECT_EQ(0u, token_command_runner_.commands_ran_.size());
++}
++
++TEST_F(BuildTokenTest, CompleteOneStep) {
++ // plan should execute one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of one command
++ ExpectCanRunMore(1, true);
++ ExpectAcquireToken(1, true);
++ // block and wait for command to finalize
++ ExpectWaitForCommand(1, false);
++
++ EXPECT_TRUE(builder_.Build(&err));
++ EXPECT_EQ("", err);
++
++ EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++ EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1");
++}
++
++TEST_F(BuildTokenTest, AcquireOneToken) {
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of one command
++ ExpectCanRunMore(3, true, false, false);
++ ExpectAcquireToken(1, true);
++ // block and wait for command to finalize
++ ExpectWaitForCommand(1, false);
++
++ EXPECT_FALSE(builder_.Build(&err));
++ EXPECT_EQ("stuck [this is a bug]", err);
++
++ EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++ // any of the two dependencies could have been executed
++ EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1" ||
++ token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2");
++}
++
++TEST_F(BuildTokenTest, WantTwoTokens) {
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of one command
++ ExpectCanRunMore(3, true, true, false);
++ ExpectAcquireToken(2, true, false);
++ // wait for command to finalize or token to become available
++ ExpectWaitForCommand(1, true);
++
++ EXPECT_FALSE(builder_.Build(&err));
++ EXPECT_EQ("stuck [this is a bug]", err);
++
++ EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++ // any of the two dependencies could have been executed
++ EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1" ||
++ token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2");
++}
++
++TEST_F(BuildTokenTest, CompleteTwoSteps) {
++ ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"build out1: cat in1\n"
++"build out2: cat out1\n"));
++
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("out2", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of two commands
++ ExpectCanRunMore(2, true, true);
++ ExpectAcquireToken(2, true, true);
++ // wait for commands to finalize
++ ExpectWaitForCommand(2, false, false);
++
++ EXPECT_TRUE(builder_.Build(&err));
++ EXPECT_EQ("", err);
++
++ EXPECT_EQ(2u, token_command_runner_.commands_ran_.size());
++ EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > out1");
++ EXPECT_TRUE(token_command_runner_.commands_ran_[1] == "cat out1 > out2");
++}
++
++TEST_F(BuildTokenTest, TwoCommandsInParallel) {
++ ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"rule token-available\n"
++" command = cat $in > $out\n"
++"build out1: token-available in1\n"
++"build out2: token-available in2\n"
++"build out12: cat out1 out2\n"));
++
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("out12", &err));
++ ASSERT_EQ("", err);
++
++ // 1st command: token available -> allow running
++ // 2nd command: no token available but becomes available later
++ ExpectCanRunMore(4, true, true, true, false);
++ ExpectAcquireToken(3, true, false, true);
++ // 1st call waits for command to finalize or token to become available
++ // 2nd call waits for command to finalize
++ // 3rd call waits for command to finalize
++ ExpectWaitForCommand(3, true, false, false);
++
++ EXPECT_FALSE(builder_.Build(&err));
++ EXPECT_EQ("stuck [this is a bug]", err);
++
++ EXPECT_EQ(2u, token_command_runner_.commands_ran_.size());
++ EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > out1" &&
++ token_command_runner_.commands_ran_[1] == "cat in2 > out2") ||
++ (token_command_runner_.commands_ran_[0] == "cat in2 > out2" &&
++ token_command_runner_.commands_ran_[1] == "cat in1 > out1"));
++}
++
++TEST_F(BuildTokenTest, CompleteThreeStepsSerial) {
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of all commands
++ ExpectCanRunMore(4, true, true, true, true);
++ ExpectAcquireToken(4, true, false, true, true);
++ // wait for commands to finalize
++ ExpectWaitForCommand(3, true, false, false);
++
++ EXPECT_TRUE(builder_.Build(&err));
++ EXPECT_EQ("", err);
++
++ EXPECT_EQ(3u, token_command_runner_.commands_ran_.size());
++ EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > cat1" &&
++ token_command_runner_.commands_ran_[1] == "cat in1 in2 > cat2") ||
++ (token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2" &&
++ token_command_runner_.commands_ran_[1] == "cat in1 > cat1" ));
++ EXPECT_TRUE(token_command_runner_.commands_ran_[2] == "cat cat1 cat2 > cat12");
++}
++
++TEST_F(BuildTokenTest, CompleteThreeStepsParallel) {
++ ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"rule token-available\n"
++" command = cat $in > $out\n"
++"build out1: token-available in1\n"
++"build out2: token-available in2\n"
++"build out12: cat out1 out2\n"));
++
++ // plan should execute more than one command
++ string err;
++ EXPECT_TRUE(builder_.AddTarget("out12", &err));
++ ASSERT_EQ("", err);
++
++ // allow running of all commands
++ ExpectCanRunMore(4, true, true, true, true);
++ ExpectAcquireToken(4, true, false, true, true);
++ // wait for commands to finalize
++ ExpectWaitForCommand(4, true, false, false, false);
++
++ EXPECT_TRUE(builder_.Build(&err));
++ EXPECT_EQ("", err);
++
++ EXPECT_EQ(3u, token_command_runner_.commands_ran_.size());
++ EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > out1" &&
++ token_command_runner_.commands_ran_[1] == "cat in2 > out2") ||
++ (token_command_runner_.commands_ran_[0] == "cat in2 > out2" &&
++ token_command_runner_.commands_ran_[1] == "cat in1 > out1"));
++ EXPECT_TRUE(token_command_runner_.commands_ran_[2] == "cat out1 out2 > out12");
++}
+--- a/src/exit_status.h
++++ b/src/exit_status.h
+@@ -18,7 +18,8 @@
+ enum ExitStatus {
+ ExitSuccess,
+ ExitFailure,
+- ExitInterrupted
++ ExitTokenAvailable,
++ ExitInterrupted,
+ };
+
+ #endif // NINJA_EXIT_STATUS_H_
+--- a/src/subprocess-posix.cc
++++ b/src/subprocess-posix.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include <sys/select.h>
+ #include <assert.h>
+@@ -249,7 +250,7 @@ Subprocess *SubprocessSet::Add(const str
+ }
+
+ #ifdef USE_PPOLL
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(TokenPool* tokens) {
+ vector<pollfd> fds;
+ nfds_t nfds = 0;
+
+@@ -263,6 +264,12 @@ bool SubprocessSet::DoWork() {
+ ++nfds;
+ }
+
++ if (tokens) {
++ pollfd pfd = { tokens->GetMonitorFd(), POLLIN | POLLPRI, 0 };
++ fds.push_back(pfd);
++ ++nfds;
++ }
++
+ interrupted_ = 0;
+ int ret = ppoll(&fds.front(), nfds, NULL, &old_mask_);
+ if (ret == -1) {
+@@ -295,11 +302,20 @@ bool SubprocessSet::DoWork() {
+ ++i;
+ }
+
++ if (tokens) {
++ pollfd *pfd = &fds[nfds - 1];
++ if (pfd->fd >= 0) {
++ assert(pfd->fd == tokens->GetMonitorFd());
++ if (pfd->revents != 0)
++ token_available_ = true;
++ }
++ }
++
+ return IsInterrupted();
+ }
+
+ #else // !defined(USE_PPOLL)
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(TokenPool* tokens) {
+ fd_set set;
+ int nfds = 0;
+ FD_ZERO(&set);
+@@ -314,6 +330,13 @@ bool SubprocessSet::DoWork() {
+ }
+ }
+
++ if (tokens) {
++ int fd = tokens->GetMonitorFd();
++ FD_SET(fd, &set);
++ if (nfds < fd+1)
++ nfds = fd+1;
++ }
++
+ interrupted_ = 0;
+ int ret = pselect(nfds, &set, 0, 0, 0, &old_mask_);
+ if (ret == -1) {
+@@ -342,6 +365,12 @@ bool SubprocessSet::DoWork() {
+ ++i;
+ }
+
++ if (tokens) {
++ int fd = tokens->GetMonitorFd();
++ if ((fd >= 0) && FD_ISSET(fd, &set))
++ token_available_ = true;
++ }
++
+ return IsInterrupted();
+ }
+ #endif // !defined(USE_PPOLL)
+--- a/src/subprocess-win32.cc
++++ b/src/subprocess-win32.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include <assert.h>
+ #include <stdio.h>
+@@ -251,11 +252,14 @@ Subprocess *SubprocessSet::Add(const str
+ return subprocess;
+ }
+
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(TokenPool* tokens) {
+ DWORD bytes_read;
+ Subprocess* subproc;
+ OVERLAPPED* overlapped;
+
++ if (tokens)
++ tokens->WaitForTokenAvailability(ioport_);
++
+ if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
+ &overlapped, INFINITE)) {
+ if (GetLastError() != ERROR_BROKEN_PIPE)
+@@ -266,6 +270,11 @@ bool SubprocessSet::DoWork() {
+ // delivered by NotifyInterrupted above.
+ return true;
+
++ if (tokens && tokens->TokenIsAvailable((ULONG_PTR)subproc)) {
++ token_available_ = true;
++ return false;
++ }
++
+ subproc->OnPipeReady();
+
+ if (subproc->Done()) {
+--- a/src/subprocess.h
++++ b/src/subprocess.h
+@@ -76,6 +76,8 @@ struct Subprocess {
+ friend struct SubprocessSet;
+ };
+
++struct TokenPool;
++
+ /// SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
+ /// DoWork() waits for any state change in subprocesses; finished_
+ /// is a queue of subprocesses as they finish.
+@@ -84,13 +86,17 @@ struct SubprocessSet {
+ ~SubprocessSet();
+
+ Subprocess* Add(const std::string& command, bool use_console = false);
+- bool DoWork();
++ bool DoWork(TokenPool* tokens);
+ Subprocess* NextFinished();
+ void Clear();
+
+ std::vector<Subprocess*> running_;
+ std::queue<Subprocess*> finished_;
+
++ bool token_available_;
++ bool IsTokenAvailable() { return token_available_; }
++ void ResetTokenAvailable() { token_available_ = false; }
++
+ #ifdef _WIN32
+ static BOOL WINAPI NotifyInterrupted(DWORD dwCtrlType);
+ static HANDLE ioport_;
+--- a/src/subprocess_test.cc
++++ b/src/subprocess_test.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include "test.h"
+
+@@ -34,8 +35,30 @@ const char* kSimpleCommand = "cmd /c dir
+ const char* kSimpleCommand = "ls /";
+ #endif
+
++struct TestTokenPool : public TokenPool {
++ bool Acquire() { return false; }
++ void Reserve() {}
++ void Release() {}
++ void Clear() {}
++ bool Setup(bool ignore_unused, bool verbose, double& max_load_average) { return false; }
++
++#ifdef _WIN32
++ bool _token_available;
++ void WaitForTokenAvailability(HANDLE ioport) {
++ if (_token_available)
++ // unblock GetQueuedCompletionStatus()
++ PostQueuedCompletionStatus(ioport, 0, (ULONG_PTR) this, NULL);
++ }
++ bool TokenIsAvailable(ULONG_PTR key) { return key == (ULONG_PTR) this; }
++#else
++ int _fd;
++ int GetMonitorFd() { return _fd; }
++#endif
++};
++
+ struct SubprocessTest : public testing::Test {
+ SubprocessSet subprocs_;
++ TestTokenPool tokens_;
+ };
+
+ } // anonymous namespace
+@@ -45,10 +68,12 @@ TEST_F(SubprocessTest, BadCommandStderr)
+ Subprocess* subproc = subprocs_.Add("cmd /c ninja_no_such_command");
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+ // Pretend we discovered that stderr was ready for writing.
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitFailure, subproc->Finish());
+ EXPECT_NE("", subproc->GetOutput());
+@@ -59,10 +84,12 @@ TEST_F(SubprocessTest, NoSuchCommand) {
+ Subprocess* subproc = subprocs_.Add("ninja_no_such_command");
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+ // Pretend we discovered that stderr was ready for writing.
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitFailure, subproc->Finish());
+ EXPECT_NE("", subproc->GetOutput());
+@@ -78,9 +105,11 @@ TEST_F(SubprocessTest, InterruptChild) {
+ Subprocess* subproc = subprocs_.Add("kill -INT $$");
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -90,7 +119,7 @@ TEST_F(SubprocessTest, InterruptParent)
+ ASSERT_NE((Subprocess *) 0, subproc);
+
+ while (!subproc->Done()) {
+- bool interrupted = subprocs_.DoWork();
++ bool interrupted = subprocs_.DoWork(NULL);
+ if (interrupted)
+ return;
+ }
+@@ -102,9 +131,11 @@ TEST_F(SubprocessTest, InterruptChildWit
+ Subprocess* subproc = subprocs_.Add("kill -TERM $$");
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -114,7 +145,7 @@ TEST_F(SubprocessTest, InterruptParentWi
+ ASSERT_NE((Subprocess *) 0, subproc);
+
+ while (!subproc->Done()) {
+- bool interrupted = subprocs_.DoWork();
++ bool interrupted = subprocs_.DoWork(NULL);
+ if (interrupted)
+ return;
+ }
+@@ -126,9 +157,11 @@ TEST_F(SubprocessTest, InterruptChildWit
+ Subprocess* subproc = subprocs_.Add("kill -HUP $$");
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -138,7 +171,7 @@ TEST_F(SubprocessTest, InterruptParentWi
+ ASSERT_NE((Subprocess *) 0, subproc);
+
+ while (!subproc->Done()) {
+- bool interrupted = subprocs_.DoWork();
++ bool interrupted = subprocs_.DoWork(NULL);
+ if (interrupted)
+ return;
+ }
+@@ -153,9 +186,11 @@ TEST_F(SubprocessTest, Console) {
+ subprocs_.Add("test -t 0 -a -t 1 -a -t 2", /*use_console=*/true);
+ ASSERT_NE((Subprocess*)0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+
+ EXPECT_EQ(ExitSuccess, subproc->Finish());
+ }
+@@ -167,9 +202,11 @@ TEST_F(SubprocessTest, SetWithSingle) {
+ Subprocess* subproc = subprocs_.Add(kSimpleCommand);
+ ASSERT_NE((Subprocess *) 0, subproc);
+
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+ ASSERT_EQ(ExitSuccess, subproc->Finish());
+ ASSERT_NE("", subproc->GetOutput());
+
+@@ -200,12 +237,13 @@ TEST_F(SubprocessTest, SetWithMulti) {
+ ASSERT_EQ("", processes[i]->GetOutput());
+ }
+
++ subprocs_.ResetTokenAvailable();
+ while (!processes[0]->Done() || !processes[1]->Done() ||
+ !processes[2]->Done()) {
+ ASSERT_GT(subprocs_.running_.size(), 0u);
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
+-
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+ ASSERT_EQ(0u, subprocs_.running_.size());
+ ASSERT_EQ(3u, subprocs_.finished_.size());
+
+@@ -237,8 +275,10 @@ TEST_F(SubprocessTest, SetWithLots) {
+ ASSERT_NE((Subprocess *) 0, subproc);
+ procs.push_back(subproc);
+ }
++ subprocs_.ResetTokenAvailable();
+ while (!subprocs_.running_.empty())
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+ for (size_t i = 0; i < procs.size(); ++i) {
+ ASSERT_EQ(ExitSuccess, procs[i]->Finish());
+ ASSERT_NE("", procs[i]->GetOutput());
+@@ -254,10 +294,91 @@ TEST_F(SubprocessTest, SetWithLots) {
+ // that stdin is closed.
+ TEST_F(SubprocessTest, ReadStdin) {
+ Subprocess* subproc = subprocs_.Add("cat -");
++ subprocs_.ResetTokenAvailable();
+ while (!subproc->Done()) {
+- subprocs_.DoWork();
++ subprocs_.DoWork(NULL);
+ }
++ ASSERT_FALSE(subprocs_.IsTokenAvailable());
+ ASSERT_EQ(ExitSuccess, subproc->Finish());
+ ASSERT_EQ(1u, subprocs_.finished_.size());
+ }
+ #endif // _WIN32
++
++TEST_F(SubprocessTest, TokenAvailable) {
++ Subprocess* subproc = subprocs_.Add(kSimpleCommand);
++ ASSERT_NE((Subprocess *) 0, subproc);
++
++ // simulate GNUmake jobserver pipe with 1 token
++#ifdef _WIN32
++ tokens_._token_available = true;
++#else
++ int fds[2];
++ ASSERT_EQ(0u, pipe(fds));
++ tokens_._fd = fds[0];
++ ASSERT_EQ(1u, write(fds[1], "T", 1));
++#endif
++
++ subprocs_.ResetTokenAvailable();
++ subprocs_.DoWork(&tokens_);
++#ifdef _WIN32
++ tokens_._token_available = false;
++ // we need to loop here as we have no control where the token
++ // I/O completion post ends up in the queue
++ while (!subproc->Done() && !subprocs_.IsTokenAvailable()) {
++ subprocs_.DoWork(&tokens_);
++ }
++#endif
++
++ EXPECT_TRUE(subprocs_.IsTokenAvailable());
++ EXPECT_EQ(0u, subprocs_.finished_.size());
++
++ // remove token to let DoWork() wait for command again
++#ifndef _WIN32
++ char token;
++ ASSERT_EQ(1u, read(fds[0], &token, 1));
++#endif
++
++ while (!subproc->Done()) {
++ subprocs_.DoWork(&tokens_);
++ }
++
++#ifndef _WIN32
++ close(fds[1]);
++ close(fds[0]);
++#endif
++
++ EXPECT_EQ(ExitSuccess, subproc->Finish());
++ EXPECT_NE("", subproc->GetOutput());
++
++ EXPECT_EQ(1u, subprocs_.finished_.size());
++}
++
++TEST_F(SubprocessTest, TokenNotAvailable) {
++ Subprocess* subproc = subprocs_.Add(kSimpleCommand);
++ ASSERT_NE((Subprocess *) 0, subproc);
++
++ // simulate GNUmake jobserver pipe with 0 tokens
++#ifdef _WIN32
++ tokens_._token_available = false;
++#else
++ int fds[2];
++ ASSERT_EQ(0u, pipe(fds));
++ tokens_._fd = fds[0];
++#endif
++
++ subprocs_.ResetTokenAvailable();
++ while (!subproc->Done()) {
++ subprocs_.DoWork(&tokens_);
++ }
++
++#ifndef _WIN32
++ close(fds[1]);
++ close(fds[0]);
++#endif
++
++ EXPECT_FALSE(subprocs_.IsTokenAvailable());
++ EXPECT_EQ(ExitSuccess, subproc->Finish());
++ EXPECT_NE("", subproc->GetOutput());
++
++ EXPECT_EQ(1u, subprocs_.finished_.size());
++}
+--- a/src/ninja.cc
++++ b/src/ninja.cc
+@@ -1466,6 +1466,7 @@ int ReadFlags(int* argc, char*** argv,
+ // We want to run N jobs in parallel. For N = 0, INT_MAX
+ // is close enough to infinite for most sane builds.
+ config->parallelism = value > 0 ? value : INT_MAX;
++ config->parallelism_from_cmdline = true;
+ deferGuessParallelism.needGuess = false;
+ break;
+ }
+--- /dev/null
++++ b/src/tokenpool_test.cc
+@@ -0,0 +1,279 @@
++// Copyright 2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#include "tokenpool.h"
++
++#include "test.h"
++
++#ifdef _WIN32
++#include <windows.h>
++#else
++#include <unistd.h>
++#endif
++
++#include <stdio.h>
++#include <stdlib.h>
++
++#ifdef _WIN32
++// should contain all valid characters
++#define SEMAPHORE_NAME "abcdefghijklmnopqrstwxyz01234567890_"
++#define AUTH_FORMAT(tmpl) "foo " tmpl "=%s bar"
++#define ENVIRONMENT_CLEAR() SetEnvironmentVariable("MAKEFLAGS", NULL)
++#define ENVIRONMENT_INIT(v) SetEnvironmentVariable("MAKEFLAGS", v)
++#else
++#define AUTH_FORMAT(tmpl) "foo " tmpl "=%d,%d bar"
++#define ENVIRONMENT_CLEAR() unsetenv("MAKEFLAGS")
++#define ENVIRONMENT_INIT(v) setenv("MAKEFLAGS", v, true)
++#endif
++
++namespace {
++
++const double kLoadAverageDefault = -1.23456789;
++
++struct TokenPoolTest : public testing::Test {
++ double load_avg_;
++ TokenPool* tokens_;
++ char buf_[1024];
++#ifdef _WIN32
++ const char* semaphore_name_;
++ HANDLE semaphore_;
++#else
++ int fds_[2];
++
++ char random() {
++ return int((rand() / double(RAND_MAX)) * 256);
++ }
++#endif
++
++ virtual void SetUp() {
++ load_avg_ = kLoadAverageDefault;
++ tokens_ = NULL;
++ ENVIRONMENT_CLEAR();
++#ifdef _WIN32
++ semaphore_name_ = SEMAPHORE_NAME;
++ if ((semaphore_ = CreateSemaphore(0, 0, 2, SEMAPHORE_NAME)) == NULL)
++#else
++ if (pipe(fds_) < 0)
++#endif
++ ASSERT_TRUE(false);
++ }
++
++ void CreatePool(const char* format, bool ignore_jobserver = false) {
++ if (format) {
++ sprintf(buf_, format,
++#ifdef _WIN32
++ semaphore_name_
++#else
++ fds_[0], fds_[1]
++#endif
++ );
++ ENVIRONMENT_INIT(buf_);
++ }
++ if ((tokens_ = TokenPool::Get()) != NULL) {
++ if (!tokens_->Setup(ignore_jobserver, false, load_avg_)) {
++ delete tokens_;
++ tokens_ = NULL;
++ }
++ }
++ }
++
++ void CreateDefaultPool() {
++ CreatePool(AUTH_FORMAT("--jobserver-auth"));
++ }
++
++ virtual void TearDown() {
++ if (tokens_)
++ delete tokens_;
++#ifdef _WIN32
++ CloseHandle(semaphore_);
++#else
++ close(fds_[0]);
++ close(fds_[1]);
++#endif
++ ENVIRONMENT_CLEAR();
++ }
++};
++
++} // anonymous namespace
++
++// verifies none implementation
++TEST_F(TokenPoolTest, NoTokenPool) {
++ CreatePool(NULL, false);
++
++ EXPECT_EQ(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, SuccessfulOldSetup) {
++ // GNUmake <= 4.1
++ CreatePool(AUTH_FORMAT("--jobserver-fds"));
++
++ EXPECT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, SuccessfulNewSetup) {
++ // GNUmake => 4.2
++ CreateDefaultPool();
++
++ EXPECT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, IgnoreWithJN) {
++ CreatePool(AUTH_FORMAT("--jobserver-auth"), true);
++
++ EXPECT_EQ(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, HonorLN) {
++ CreatePool(AUTH_FORMAT("-l9 --jobserver-auth"));
++
++ EXPECT_NE(NULL, tokens_);
++ EXPECT_EQ(9.0, load_avg_);
++}
++
++#ifdef _WIN32
++TEST_F(TokenPoolTest, SemaphoreNotFound) {
++ semaphore_name_ = SEMAPHORE_NAME "_foobar";
++ CreateDefaultPool();
++
++ EXPECT_EQ(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, TokenIsAvailable) {
++ CreateDefaultPool();
++
++ ASSERT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++ EXPECT_TRUE(tokens_->TokenIsAvailable((ULONG_PTR)tokens_));
++}
++#else
++TEST_F(TokenPoolTest, MonitorFD) {
++ CreateDefaultPool();
++
++ ASSERT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++ EXPECT_EQ(fds_[0], tokens_->GetMonitorFd());
++}
++#endif
++
++TEST_F(TokenPoolTest, ImplicitToken) {
++ CreateDefaultPool();
++
++ ASSERT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_FALSE(tokens_->Acquire());
++ tokens_->Release();
++ EXPECT_TRUE(tokens_->Acquire());
++}
++
++TEST_F(TokenPoolTest, TwoTokens) {
++ CreateDefaultPool();
++
++ ASSERT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++ // implicit token
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_FALSE(tokens_->Acquire());
++
++ // jobserver offers 2nd token
++#ifdef _WIN32
++ LONG previous;
++ ASSERT_TRUE(ReleaseSemaphore(semaphore_, 1, &previous));
++ ASSERT_EQ(0, previous);
++#else
++ char test_tokens[1] = { random() };
++ ASSERT_EQ(1u, write(fds_[1], test_tokens, sizeof(test_tokens)));
++#endif
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_FALSE(tokens_->Acquire());
++
++ // release 2nd token
++ tokens_->Release();
++ EXPECT_TRUE(tokens_->Acquire());
++
++ // release implicit token - must return 2nd token back to jobserver
++ tokens_->Release();
++ EXPECT_TRUE(tokens_->Acquire());
++
++ // there must be one token available
++#ifdef _WIN32
++ EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(semaphore_, 0));
++ EXPECT_TRUE(ReleaseSemaphore(semaphore_, 1, &previous));
++ EXPECT_EQ(0, previous);
++#else
++ EXPECT_EQ(1u, read(fds_[0], buf_, sizeof(buf_)));
++ EXPECT_EQ(test_tokens[0], buf_[0]);
++#endif
++
++ // implicit token
++ EXPECT_TRUE(tokens_->Acquire());
++}
++
++TEST_F(TokenPoolTest, Clear) {
++ CreateDefaultPool();
++
++ ASSERT_NE(NULL, tokens_);
++ EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++ // implicit token
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_FALSE(tokens_->Acquire());
++
++ // jobserver offers 2nd & 3rd token
++#ifdef _WIN32
++ LONG previous;
++ ASSERT_TRUE(ReleaseSemaphore(semaphore_, 2, &previous));
++ ASSERT_EQ(0, previous);
++#else
++ char test_tokens[2] = { random(), random() };
++ ASSERT_EQ(2u, write(fds_[1], test_tokens, sizeof(test_tokens)));
++#endif
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_TRUE(tokens_->Acquire());
++ tokens_->Reserve();
++ EXPECT_FALSE(tokens_->Acquire());
++
++ tokens_->Clear();
++ EXPECT_TRUE(tokens_->Acquire());
++
++ // there must be two tokens available
++#ifdef _WIN32
++ EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(semaphore_, 0));
++ EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(semaphore_, 0));
++ EXPECT_TRUE(ReleaseSemaphore(semaphore_, 2, &previous));
++ EXPECT_EQ(0, previous);
++#else
++ EXPECT_EQ(2u, read(fds_[0], buf_, sizeof(buf_)));
++ // tokens are pushed onto a stack, hence returned in reverse order
++ EXPECT_EQ(test_tokens[0], buf_[1]);
++ EXPECT_EQ(test_tokens[1], buf_[0]);
++#endif
++
++ // implicit token
++ EXPECT_TRUE(tokens_->Acquire());
++}
+--- /dev/null
++++ b/src/tokenpool-gnu-make-posix.cc
+@@ -0,0 +1,214 @@
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#include "tokenpool-gnu-make.h"
++
++#include <errno.h>
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <signal.h>
++#include <sys/time.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++#include <stack>
++
++// TokenPool implementation for GNU make jobserver - POSIX implementation
++// (http://make.mad-scientist.net/papers/jobserver-implementation/)
++struct GNUmakeTokenPoolPosix : public GNUmakeTokenPool {
++ GNUmakeTokenPoolPosix();
++ virtual ~GNUmakeTokenPoolPosix();
++
++ virtual int GetMonitorFd();
++
++ virtual const char* GetEnv(const char* name) { return getenv(name); };
++ virtual bool ParseAuth(const char* jobserver);
++ virtual bool AcquireToken();
++ virtual bool ReturnToken();
++
++ private:
++ int rfd_;
++ int wfd_;
++
++ struct sigaction old_act_;
++ bool restore_;
++
++ // See https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html
++ //
++ // It’s important that when you release the job slot, you write back
++ // the same character you read. Don’t assume that all tokens are the
++ // same character different characters may have different meanings to
++ // GNU make. The order is not important, since make has no idea in
++ // what order jobs will complete anyway.
++ //
++ std::stack<char> tokens_;
++
++ static int dup_rfd_;
++ static void CloseDupRfd(int signum);
++
++ bool CheckFd(int fd);
++ bool SetAlarmHandler();
++};
++
++GNUmakeTokenPoolPosix::GNUmakeTokenPoolPosix() : rfd_(-1), wfd_(-1), restore_(false) {
++}
++
++GNUmakeTokenPoolPosix::~GNUmakeTokenPoolPosix() {
++ Clear();
++ if (restore_)
++ sigaction(SIGALRM, &old_act_, NULL);
++}
++
++bool GNUmakeTokenPoolPosix::CheckFd(int fd) {
++ if (fd < 0)
++ return false;
++ int ret = fcntl(fd, F_GETFD);
++ return ret >= 0;
++}
++
++int GNUmakeTokenPoolPosix::dup_rfd_ = -1;
++
++void GNUmakeTokenPoolPosix::CloseDupRfd(int signum) {
++ close(dup_rfd_);
++ dup_rfd_ = -1;
++}
++
++bool GNUmakeTokenPoolPosix::SetAlarmHandler() {
++ struct sigaction act;
++ memset(&act, 0, sizeof(act));
++ act.sa_handler = CloseDupRfd;
++ if (sigaction(SIGALRM, &act, &old_act_) < 0) {
++ perror("sigaction:");
++ return false;
++ }
++ restore_ = true;
++ return true;
++}
++
++bool GNUmakeTokenPoolPosix::ParseAuth(const char* jobserver) {
++ int rfd = -1;
++ int wfd = -1;
++ if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
++ CheckFd(rfd) &&
++ CheckFd(wfd) &&
++ SetAlarmHandler()) {
++ rfd_ = rfd;
++ wfd_ = wfd;
++ return true;
++ }
++
++ return false;
++}
++
++bool GNUmakeTokenPoolPosix::AcquireToken() {
++ // Please read
++ //
++ // http://make.mad-scientist.net/papers/jobserver-implementation/
++ //
++ // for the reasoning behind the following code.
++ //
++ // Try to read one character from the pipe. Returns true on success.
++ //
++ // First check if read() would succeed without blocking.
++#ifdef USE_PPOLL
++ pollfd pollfds[] = {{rfd_, POLLIN, 0}};
++ int ret = poll(pollfds, 1, 0);
++#else
++ fd_set set;
++ struct timeval timeout = { 0, 0 };
++ FD_ZERO(&set);
++ FD_SET(rfd_, &set);
++ int ret = select(rfd_ + 1, &set, NULL, NULL, &timeout);
++#endif
++ if (ret > 0) {
++ // Handle potential race condition:
++ // - the above check succeeded, i.e. read() should not block
++ // - the character disappears before we call read()
++ //
++ // Create a duplicate of rfd_. The duplicate file descriptor dup_rfd_
++ // can safely be closed by signal handlers without affecting rfd_.
++ dup_rfd_ = dup(rfd_);
++
++ if (dup_rfd_ != -1) {
++ struct sigaction act, old_act;
++ int ret = 0;
++ char buf;
++
++ // Temporarily replace SIGCHLD handler with our own
++ memset(&act, 0, sizeof(act));
++ act.sa_handler = CloseDupRfd;
++ if (sigaction(SIGCHLD, &act, &old_act) == 0) {
++ struct itimerval timeout;
++
++ // install a 100ms timeout that generates SIGALARM on expiration
++ memset(&timeout, 0, sizeof(timeout));
++ timeout.it_value.tv_usec = 100 * 1000; // [ms] -> [usec]
++ if (setitimer(ITIMER_REAL, &timeout, NULL) == 0) {
++ // Now try to read() from dup_rfd_. Return values from read():
++ //
++ // 1. token read -> 1
++ // 2. pipe closed -> 0
++ // 3. alarm expires -> -1 (EINTR)
++ // 4. child exits -> -1 (EINTR)
++ // 5. alarm expired before entering read() -> -1 (EBADF)
++ // 6. child exited before entering read() -> -1 (EBADF)
++ // 7. child exited before handler is installed -> go to 1 - 3
++ ret = read(dup_rfd_, &buf, 1);
++
++ // disarm timer
++ memset(&timeout, 0, sizeof(timeout));
++ setitimer(ITIMER_REAL, &timeout, NULL);
++ }
++
++ sigaction(SIGCHLD, &old_act, NULL);
++ }
++
++ CloseDupRfd(0);
++
++ // Case 1 from above list
++ if (ret > 0) {
++ tokens_.push(buf);
++ return true;
++ }
++ }
++ }
++
++ // read() would block, i.e. no token available,
++ // cases 2-6 from above list or
++ // select() / poll() / dup() / sigaction() / setitimer() failed
++ return false;
++}
++
++bool GNUmakeTokenPoolPosix::ReturnToken() {
++ const char buf = tokens_.top();
++ while (1) {
++ int ret = write(wfd_, &buf, 1);
++ if (ret > 0) {
++ tokens_.pop();
++ return true;
++ }
++ if ((ret != -1) || (errno != EINTR))
++ return false;
++ // write got interrupted - retry
++ }
++}
++
++int GNUmakeTokenPoolPosix::GetMonitorFd() {
++ return rfd_;
++}
++
++TokenPool* TokenPool::Get() {
++ return new GNUmakeTokenPoolPosix;
++}
+--- /dev/null
++++ b/src/tokenpool-gnu-make-win32.cc
+@@ -0,0 +1,239 @@
++// Copyright 2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#include "tokenpool-gnu-make.h"
++
++// Always include this first.
++// Otherwise the other system headers don't work correctly under Win32
++#include <windows.h>
++
++#include <ctype.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include "util.h"
++
++// TokenPool implementation for GNU make jobserver - Win32 implementation
++// (https://www.gnu.org/software/make/manual/html_node/Windows-Jobserver.html)
++struct GNUmakeTokenPoolWin32 : public GNUmakeTokenPool {
++ GNUmakeTokenPoolWin32();
++ virtual ~GNUmakeTokenPoolWin32();
++
++ virtual void WaitForTokenAvailability(HANDLE ioport);
++ virtual bool TokenIsAvailable(ULONG_PTR key);
++
++ virtual const char* GetEnv(const char* name);
++ virtual bool ParseAuth(const char* jobserver);
++ virtual bool AcquireToken();
++ virtual bool ReturnToken();
++
++ private:
++ // Semaphore for GNU make jobserver protocol
++ HANDLE semaphore_jobserver_;
++ // Semaphore Child -> Parent
++ // - child releases it before entering wait on jobserver semaphore
++ // - parent blocks on it to know when child enters wait
++ HANDLE semaphore_enter_wait_;
++ // Semaphore Parent -> Child
++ // - parent releases it to allow child to restart loop
++ // - child blocks on it to know when to restart loop
++ HANDLE semaphore_restart_;
++ // set to false if child should exit loop and terminate thread
++ bool running_;
++ // child thread
++ HANDLE child_;
++ // I/O completion port from SubprocessSet
++ HANDLE ioport_;
++
++
++ DWORD SemaphoreThread();
++ void ReleaseSemaphore(HANDLE semaphore);
++ void WaitForObject(HANDLE object);
++ static DWORD WINAPI SemaphoreThreadWrapper(LPVOID param);
++ static void NoopAPCFunc(ULONG_PTR param);
++};
++
++GNUmakeTokenPoolWin32::GNUmakeTokenPoolWin32() : semaphore_jobserver_(NULL),
++ semaphore_enter_wait_(NULL),
++ semaphore_restart_(NULL),
++ running_(false),
++ child_(NULL),
++ ioport_(NULL) {
++}
++
++GNUmakeTokenPoolWin32::~GNUmakeTokenPoolWin32() {
++ Clear();
++ CloseHandle(semaphore_jobserver_);
++ semaphore_jobserver_ = NULL;
++
++ if (child_) {
++ // tell child thread to exit
++ running_ = false;
++ ReleaseSemaphore(semaphore_restart_);
++
++ // wait for child thread to exit
++ WaitForObject(child_);
++ CloseHandle(child_);
++ child_ = NULL;
++ }
++
++ if (semaphore_restart_) {
++ CloseHandle(semaphore_restart_);
++ semaphore_restart_ = NULL;
++ }
++
++ if (semaphore_enter_wait_) {
++ CloseHandle(semaphore_enter_wait_);
++ semaphore_enter_wait_ = NULL;
++ }
++}
++
++const char* GNUmakeTokenPoolWin32::GetEnv(const char* name) {
++ // getenv() does not work correctly together with tokenpool_tests.cc
++ static char buffer[MAX_PATH + 1];
++ if (GetEnvironmentVariable(name, buffer, sizeof(buffer)) == 0)
++ return NULL;
++ return buffer;
++}
++
++bool GNUmakeTokenPoolWin32::ParseAuth(const char* jobserver) {
++ // match "--jobserver-auth=gmake_semaphore_<INTEGER>..."
++ const char* start = strchr(jobserver, '=');
++ if (start) {
++ const char* end = start;
++ unsigned int len;
++ char c, *auth;
++
++ while ((c = *++end) != '\0')
++ if (!(isalnum(c) || (c == '_')))
++ break;
++ len = end - start; // includes string terminator in count
++
++ if ((len > 1) && ((auth = (char*)malloc(len)) != NULL)) {
++ strncpy(auth, start + 1, len - 1);
++ auth[len - 1] = '\0';
++
++ if ((semaphore_jobserver_ =
++ OpenSemaphore(SEMAPHORE_ALL_ACCESS, /* Semaphore access setting */
++ FALSE, /* Child processes DON'T inherit */
++ auth /* Semaphore name */
++ )) != NULL) {
++ free(auth);
++ return true;
++ }
++
++ free(auth);
++ }
++ }
++
++ return false;
++}
++
++bool GNUmakeTokenPoolWin32::AcquireToken() {
++ return WaitForSingleObject(semaphore_jobserver_, 0) == WAIT_OBJECT_0;
++}
++
++bool GNUmakeTokenPoolWin32::ReturnToken() {
++ ReleaseSemaphore(semaphore_jobserver_);
++ return true;
++}
++
++DWORD GNUmakeTokenPoolWin32::SemaphoreThread() {
++ while (running_) {
++ // indicate to parent that we are entering wait
++ ReleaseSemaphore(semaphore_enter_wait_);
++
++ // alertable wait forever on token semaphore
++ if (WaitForSingleObjectEx(semaphore_jobserver_, INFINITE, TRUE) == WAIT_OBJECT_0) {
++ // release token again for AcquireToken()
++ ReleaseSemaphore(semaphore_jobserver_);
++
++ // indicate to parent on ioport that a token might be available
++ if (!PostQueuedCompletionStatus(ioport_, 0, (ULONG_PTR) this, NULL))
++ Win32Fatal("PostQueuedCompletionStatus");
++ }
++
++ // wait for parent to allow loop restart
++ WaitForObject(semaphore_restart_);
++ // semaphore is now in nonsignaled state again for next run...
++ }
++
++ return 0;
++}
++
++DWORD WINAPI GNUmakeTokenPoolWin32::SemaphoreThreadWrapper(LPVOID param) {
++ GNUmakeTokenPoolWin32* This = (GNUmakeTokenPoolWin32*) param;
++ return This->SemaphoreThread();
++}
++
++void GNUmakeTokenPoolWin32::NoopAPCFunc(ULONG_PTR param) {
++}
++
++void GNUmakeTokenPoolWin32::WaitForTokenAvailability(HANDLE ioport) {
++ if (child_ == NULL) {
++ // first invocation
++ //
++ // subprocess-win32.cc uses I/O completion port (IOCP) which can't be
++ // used as a waitable object. Therefore we can't use WaitMultipleObjects()
++ // to wait on the IOCP and the token semaphore at the same time. Create
++ // a child thread that waits on the semaphore and posts an I/O completion
++ ioport_ = ioport;
++
++ // create both semaphores in nonsignaled state
++ if ((semaphore_enter_wait_ = CreateSemaphore(NULL, 0, 1, NULL))
++ == NULL)
++ Win32Fatal("CreateSemaphore/enter_wait");
++ if ((semaphore_restart_ = CreateSemaphore(NULL, 0, 1, NULL))
++ == NULL)
++ Win32Fatal("CreateSemaphore/restart");
++
++ // start child thread
++ running_ = true;
++ if ((child_ = CreateThread(NULL, 0, &SemaphoreThreadWrapper, this, 0, NULL))
++ == NULL)
++ Win32Fatal("CreateThread");
++
++ } else {
++ // all further invocations - allow child thread to loop
++ ReleaseSemaphore(semaphore_restart_);
++ }
++
++ // wait for child thread to enter wait
++ WaitForObject(semaphore_enter_wait_);
++ // semaphore is now in nonsignaled state again for next run...
++
++ // now SubprocessSet::DoWork() can enter GetQueuedCompletionStatus()...
++}
++
++bool GNUmakeTokenPoolWin32::TokenIsAvailable(ULONG_PTR key) {
++ // alert child thread to break wait on token semaphore
++ QueueUserAPC((PAPCFUNC)&NoopAPCFunc, child_, (ULONG_PTR)NULL);
++
++ // return true when GetQueuedCompletionStatus() returned our key
++ return key == (ULONG_PTR) this;
++}
++
++void GNUmakeTokenPoolWin32::ReleaseSemaphore(HANDLE semaphore) {
++ if (!::ReleaseSemaphore(semaphore, 1, NULL))
++ Win32Fatal("ReleaseSemaphore");
++}
++
++void GNUmakeTokenPoolWin32::WaitForObject(HANDLE object) {
++ if (WaitForSingleObject(object, INFINITE) != WAIT_OBJECT_0)
++ Win32Fatal("WaitForSingleObject");
++}
++
++TokenPool* TokenPool::Get() {
++ return new GNUmakeTokenPoolWin32;
++}
+--- /dev/null
++++ b/src/tokenpool-gnu-make.h
+@@ -0,0 +1,40 @@
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
++//
++// Licensed under the Apache License, Version 2.0 (the "License");
++// you may not use this file except in compliance with the License.
++// You may obtain a copy of the License at
++//
++// http://www.apache.org/licenses/LICENSE-2.0
++//
++// Unless required by applicable law or agreed to in writing, software
++// distributed under the License is distributed on an "AS IS" BASIS,
++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++// See the License for the specific language governing permissions and
++// limitations under the License.
++
++#include "tokenpool.h"
++
++// interface to GNU make token pool
++struct GNUmakeTokenPool : public TokenPool {
++ GNUmakeTokenPool();
++ ~GNUmakeTokenPool();
++
++ // token pool implementation
++ virtual bool Acquire();
++ virtual void Reserve();
++ virtual void Release();
++ virtual void Clear();
++ virtual bool Setup(bool ignore, bool verbose, double& max_load_average);
++
++ // platform specific implementation
++ virtual const char* GetEnv(const char* name) = 0;
++ virtual bool ParseAuth(const char* jobserver) = 0;
++ virtual bool AcquireToken() = 0;
++ virtual bool ReturnToken() = 0;
++
++ private:
++ int available_;
++ int used_;
++
++ void Return();
++};
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -142,6 +142,7 @@ add_library(libninja OBJECT
+ src/state.cc
+ src/status.cc
+ src/string_piece_util.cc
++ src/tokenpool-gnu-make.cc
+ src/util.cc
+ src/version.cc
+ )
+@@ -153,13 +154,17 @@ if(WIN32)
+ src/msvc_helper_main-win32.cc
+ src/getopt.c
+ src/minidump-win32.cc
++ src/tokenpool-gnu-make-win32.cc
+ )
+ # Build getopt.c, which can be compiled as either C or C++, as C++
+ # so that build environments which lack a C compiler, but have a C++
+ # compiler may build ninja.
+ set_source_files_properties(src/getopt.c PROPERTIES LANGUAGE CXX)
+ else()
+- target_sources(libninja PRIVATE src/subprocess-posix.cc)
++ target_sources(libninja PRIVATE
++ src/subprocess-posix.cc
++ src/tokenpool-gnu-make-posix.cc
++ )
+ if(CMAKE_SYSTEM_NAME STREQUAL "OS400" OR CMAKE_SYSTEM_NAME STREQUAL "AIX")
+ target_sources(libninja PRIVATE src/getopt.c)
+ # Build getopt.c, which can be compiled as either C or C++, as C++
+@@ -286,6 +291,7 @@ if(BUILD_TESTING)
+ src/string_piece_util_test.cc
+ src/subprocess_test.cc
+ src/test.cc
++ src/tokenpool_test.cc
+ src/util_test.cc
+ )
+ if(WIN32)
diff --git a/tools/padjffs2/Makefile b/tools/padjffs2/Makefile
new file mode 100644
index 0000000..b893fad
--- /dev/null
+++ b/tools/padjffs2/Makefile
@@ -0,0 +1,35 @@
+#
+# Copyright (C) 2011-2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=padjffs2
+PKG_RELEASE:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Prepare
+ $(call Host/Prepare/Default)
+ find $(HOST_BUILD_DIR) -name .svn | $(XARGS) rm -rf
+endef
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR)
+endef
+
+define Host/Configure
+endef
+
+define Host/Install
+ $(CP) $(HOST_BUILD_DIR)/padjffs2 $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/padjffs2
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/padjffs2/src/Makefile b/tools/padjffs2/src/Makefile
new file mode 100644
index 0000000..45da8e5
--- /dev/null
+++ b/tools/padjffs2/src/Makefile
@@ -0,0 +1,15 @@
+CC = gcc
+CFLAGS =
+WFLAGS = -Wall -Werror
+padjffs2-objs = padjffs2.o
+
+all: padjffs2
+
+%.o: %.c
+ $(CC) $(CFLAGS) $(WFLAGS) -c -o $@ $<
+
+padjffs2: $(padjffs2-objs)
+ $(CC) $(LDFLAGS) -o $@ $(padjffs2-objs)
+
+clean:
+ rm -f padjffs2 *.o
diff --git a/tools/padjffs2/src/padjffs2.c b/tools/padjffs2/src/padjffs2.c
new file mode 100644
index 0000000..6308292
--- /dev/null
+++ b/tools/padjffs2/src/padjffs2.c
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2011 Gabor Juhos <juhosg@openwrt.org>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 as published
+ * by the Free Software Foundation.
+ *
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+static char *progname;
+static unsigned int xtra_offset;
+static unsigned char eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
+static unsigned char jffs2_pad_be[] = "\x19\x85\x20\x04\x04\x00\x00\x00\xc4\x94\xdb\xf4";
+static unsigned char jffs2_pad_le[] = "\x85\x19\x04\x20\x00\x00\x00\x04\xa8\xfb\xa0\xb4";
+static unsigned char *pad = eof_mark;
+static int pad_len = sizeof(eof_mark);
+static bool pad_to_stdout = false;
+
+#define ERR(fmt, ...) do { \
+ fflush(0); \
+ fprintf(stderr, "[%s] *** error: " fmt "\n", \
+ progname, ## __VA_ARGS__ ); \
+} while (0)
+
+#define ERRS(fmt, ...) do { \
+ int save = errno; \
+ fflush(0); \
+ fprintf(stderr, "[%s] *** error: " fmt ", %s\n", \
+ progname, ## __VA_ARGS__, strerror(save)); \
+} while (0)
+
+#define BUF_SIZE (64 * 1024)
+#define ALIGN(_x,_y) (((_x) + ((_y) - 1)) & ~((_y) - 1))
+
+static int pad_image(char *name, uint32_t pad_mask)
+{
+ char *buf;
+ int fd;
+ int outfd;
+ ssize_t in_len;
+ ssize_t out_len;
+ int ret = -1;
+
+ buf = malloc(BUF_SIZE);
+ if (!buf) {
+ ERR("No memory for buffer");
+ goto out;
+ }
+
+ fd = open(name, O_RDWR);
+ if (fd < 0) {
+ ERRS("Unable to open %s", name);
+ goto free_buf;
+ }
+
+ in_len = lseek(fd, 0, SEEK_END);
+ if (in_len < 0)
+ goto close;
+
+ if (!pad_to_stdout)
+ outfd = fd;
+ else
+ outfd = STDOUT_FILENO;
+
+ memset(buf, '\xff', BUF_SIZE);
+
+ in_len += xtra_offset;
+
+ out_len = in_len;
+ while (pad_mask) {
+ uint32_t mask;
+ ssize_t t;
+ int i;
+
+ for (i = 10; i < 32; i++) {
+ mask = 1UL << i;
+ if (pad_mask & mask)
+ break;
+ }
+
+ in_len = ALIGN(in_len, mask);
+
+ for (i = 10; i < 32; i++) {
+ mask = 1UL << i;
+ if ((in_len & (mask - 1)) == 0)
+ pad_mask &= ~mask;
+ }
+
+ fprintf(stderr, "padding image to %08x\n", (unsigned int) in_len - xtra_offset);
+
+ while (out_len < in_len) {
+ ssize_t len;
+
+ len = in_len - out_len;
+ if (len > BUF_SIZE)
+ len = BUF_SIZE;
+
+ t = write(outfd, buf, len);
+ if (t != len) {
+ ERRS("Unable to write to %s", name);
+ goto close;
+ }
+
+ out_len += len;
+ }
+
+ /* write out the JFFS end-of-filesystem marker */
+ t = write(outfd, pad, pad_len);
+ if (t != pad_len) {
+ ERRS("Unable to write to %s", name);
+ goto close;
+ }
+ out_len += pad_len;
+ }
+
+ ret = 0;
+
+close:
+ close(fd);
+free_buf:
+ free(buf);
+out:
+ return ret;
+}
+
+static int usage(void)
+{
+ fprintf(stderr,
+ "Usage: %s file [<options>] [pad0] [pad1] [padN]\n"
+ "Options:\n"
+ " -x <offset>: Add an extra offset for padding data\n"
+ " -J: Use a fake big-endian jffs2 padding element instead of EOF\n"
+ " This is used to work around broken boot loaders that\n"
+ " try to parse the entire firmware area as one big jffs2\n"
+ " -j: (like -J, but little-endian instead of big-endian)\n"
+ " -c: write padding to stdout\n"
+ "\n",
+ progname);
+ return EXIT_FAILURE;
+}
+
+int main(int argc, char* argv[])
+{
+ char *image;
+ uint32_t pad_mask;
+ int ret = EXIT_FAILURE;
+ int err;
+ int ch, i;
+
+ progname = basename(argv[0]);
+
+ if (argc < 2)
+ return usage();
+
+ image = argv[1];
+ argv++;
+ argc--;
+
+ pad_mask = 0;
+ while ((ch = getopt(argc, argv, "x:Jjc")) != -1) {
+ switch (ch) {
+ case 'x':
+ xtra_offset = strtoul(optarg, NULL, 0);
+ fprintf(stderr, "assuming %u bytes offset\n",
+ xtra_offset);
+ break;
+ case 'J':
+ pad = jffs2_pad_be;
+ pad_len = sizeof(jffs2_pad_be) - 1;
+ break;
+ case 'j':
+ pad = jffs2_pad_le;
+ pad_len = sizeof(jffs2_pad_le) - 1;
+ break;
+ case 'c':
+ pad_to_stdout = true;
+ break;
+ default:
+ return usage();
+ }
+ }
+
+ for (i = optind; i < argc; i++)
+ pad_mask |= strtoul(argv[i], NULL, 0) * 1024;
+
+ if (pad_mask == 0)
+ pad_mask = (4 * 1024) | (8 * 1024) | (64 * 1024) |
+ (128 * 1024);
+
+ err = pad_image(image, pad_mask);
+ if (err)
+ goto out;
+
+ ret = EXIT_SUCCESS;
+
+out:
+ return ret;
+}
diff --git a/tools/patch-image/Makefile b/tools/patch-image/Makefile
new file mode 100644
index 0000000..89cd25e
--- /dev/null
+++ b/tools/patch-image/Makefile
@@ -0,0 +1,29 @@
+#
+# Copyright (C) 2007-2020 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=patch-image
+PKG_RELEASE:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ $(HOSTCC) $(HOST_CFLAGS) -include endian.h -o $(HOST_BUILD_DIR)/patch-cmdline src/patch-cmdline.c
+ $(HOSTCC) $(HOST_CFLAGS) -include endian.h -o $(HOST_BUILD_DIR)/patch-dtb src/patch-dtb.c
+endef
+
+define Host/Install
+ $(CP) $(HOST_BUILD_DIR)/patch-cmdline $(STAGING_DIR_HOST)/bin/
+ $(CP) $(HOST_BUILD_DIR)/patch-dtb $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/patch-cmdline
+ rm -f $(STAGING_DIR_HOST)/bin/patch-dtb
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/patch-image/src/patch-cmdline.c b/tools/patch-image/src/patch-cmdline.c
new file mode 100644
index 0000000..9eaa648
--- /dev/null
+++ b/tools/patch-image/src/patch-cmdline.c
@@ -0,0 +1,85 @@
+/*
+ * patch-cmdline.c - patch the kernel command line
+ *
+ * Copyright (C) 2006 Felix Fietkau <nbd@nbd.name>
+ *
+ * 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 2
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <string.h>
+
+#define SEARCH_SPACE (16 * 1024)
+#define CMDLINE_MAX 512
+
+int main(int argc, char **argv)
+{
+ int fd, found = 0, len, ret = -1;
+ char *ptr, *p;
+ unsigned int search_space;
+
+ if (argc <= 2 || argc > 4) {
+ fprintf(stderr, "Usage: %s <file> <cmdline> [size]\n", argv[0]);
+ goto err1;
+ } else if (argc == 3) {
+ fprintf(stdout, "search space used is default of 16KB\n");
+ search_space = SEARCH_SPACE;
+ } else {
+ search_space = atoi(argv[3]);
+ }
+ len = strlen(argv[2]);
+ if (len + 9 > CMDLINE_MAX) {
+ fprintf(stderr, "Command line string too long\n");
+ goto err1;
+ }
+
+ if (((fd = open(argv[1], O_RDWR)) < 0) ||
+ (ptr = (char *) mmap(0, search_space + CMDLINE_MAX, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == (void *) (-1)) {
+ fprintf(stderr, "Could not open kernel image");
+ goto err2;
+ }
+
+ for (p = ptr; p < (ptr + search_space); p += 4) {
+ if (memcmp(p, "CMDLINE:", 8) == 0) {
+ found = 1;
+ p += 8;
+ break;
+ }
+ }
+ if (!found) {
+ fprintf(stderr, "Command line marker not found!\n");
+ goto err3;
+ }
+
+ memset(p, 0, CMDLINE_MAX - 8);
+ strcpy(p, argv[2]);
+ msync(p, CMDLINE_MAX, MS_SYNC|MS_INVALIDATE);
+ ret = 0;
+
+err3:
+ munmap((void *) ptr, len);
+err2:
+ if (fd > 0)
+ close(fd);
+err1:
+ return ret;
+}
diff --git a/tools/patch-image/src/patch-dtb.c b/tools/patch-image/src/patch-dtb.c
new file mode 100644
index 0000000..a94da3f
--- /dev/null
+++ b/tools/patch-image/src/patch-dtb.c
@@ -0,0 +1,103 @@
+/*
+ * patch-dtb.c - patch a dtb into an image
+ *
+ * Copyright (C) 2006 Felix Fietkau <nbd@nbd.name>
+ * Copyright (C) 2012 John Crispin <blogic@openwrt.org>
+ *
+ * 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 2
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * based on patch-cmdline.c
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <string.h>
+
+#define DTB_MAX (16 * 1024)
+
+int main(int argc, char **argv)
+{
+ int fd, fddtb, found = 0, len, ret = -1;
+ char *ptr, *ptrdtb, *p;
+ struct stat s;
+ unsigned int search_space , dtb_max_size;
+
+ if (argc <= 2 || argc > 4) {
+ fprintf(stderr, "Usage: %s <file> <dtb> [size]\n", argv[0]);
+ goto err1;
+ } else if (argc == 3) {
+ fprintf(stdout, "DT size used is default of 16KB\n");
+ search_space = dtb_max_size = DTB_MAX;
+ } else {
+ search_space = dtb_max_size = atoi(argv[3]);
+ }
+
+ if (stat(argv[2], &s)) {
+ fprintf(stderr, "DTB not found\n");
+ goto err1;
+ }
+
+ len = s.st_size;
+ if (len + 8 > dtb_max_size) {
+ fprintf(stderr, "DTB too big\n");
+ goto err1;
+ }
+
+ if (((fddtb = open(argv[2], O_RDONLY)) < 0) ||
+ (ptrdtb = (char *) mmap(0, dtb_max_size, PROT_READ, MAP_SHARED, fddtb, 0)) == (void *) (-1)) {
+ fprintf(stderr, "Could not open DTB");
+ goto err2;
+ }
+
+ if (((fd = open(argv[1], O_RDWR)) < 0) ||
+ (ptr = (char *) mmap(0, search_space + dtb_max_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == (void *) (-1)) {
+ fprintf(stderr, "Could not open kernel image");
+ goto err3;
+ }
+
+ for (p = ptr; p < (ptr + search_space); p += 4) {
+ if (memcmp(p, "OWRTDTB:", 8) == 0) {
+ found = 1;
+ p += 8;
+ break;
+ }
+ }
+ if (!found) {
+ fprintf(stderr, "DTB marker not found!\n");
+ goto err4;
+ }
+
+ memset(p, 0, dtb_max_size - 8);
+ memcpy(p, ptrdtb, len);
+ msync(p, len, MS_SYNC|MS_INVALIDATE);
+ ret = 0;
+
+err4:
+ munmap((void *) ptr, len);
+err3:
+ if (fd > 0)
+ close(fd);
+ munmap((void *) ptrdtb, len);
+err2:
+ if (fddtb > 0)
+ close(fddtb);
+err1:
+ return ret;
+}
diff --git a/tools/patch/Makefile b/tools/patch/Makefile
new file mode 100644
index 0000000..f4cf588
--- /dev/null
+++ b/tools/patch/Makefile
@@ -0,0 +1,29 @@
+#
+# Copyright (C) 2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=patch
+PKG_VERSION:=2.7.6
+PKG_RELEASE:=7
+PKG_CPE_ID:=cpe:/a:gnu:patch
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/patch
+PKG_HASH:=8cf86e00ad3aaa6d26aca30640e86b0e3e1f395ed99f189b06d4c9f74bc58a4e
+
+HOST_BUILD_PARALLEL := 1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOSTCXX := $(HOSTCXX_NOCACHE)
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/patch/patches/010-CVE-2018-6951.patch b/tools/patch/patches/010-CVE-2018-6951.patch
new file mode 100644
index 0000000..10dc568
--- /dev/null
+++ b/tools/patch/patches/010-CVE-2018-6951.patch
@@ -0,0 +1,24 @@
+From 1f7853c05f9949d81da9be7a02b90cc64284d1f8 Mon Sep 17 00:00:00 2001
+From: Andreas Gruenbacher <agruen@gnu.org>
+Date: Mon, 12 Feb 2018 16:48:24 +0100
+Subject: [PATCH] Fix segfault with mangled rename patch
+
+http://savannah.gnu.org/bugs/?53132
+* src/pch.c (intuit_diff_type): Ensure that two filenames are specified
+for renames and copies (fix the existing check).
+---
+ src/pch.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+--- a/src/pch.c
++++ b/src/pch.c
+@@ -974,7 +974,8 @@ intuit_diff_type (bool need_header, mode
+ if ((pch_rename () || pch_copy ())
+ && ! inname
+ && ! ((i == OLD || i == NEW) &&
+- p_name[! reverse] &&
++ p_name[reverse] && p_name[! reverse] &&
++ name_is_valid (p_name[reverse]) &&
+ name_is_valid (p_name[! reverse])))
+ {
+ say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy");
diff --git a/tools/patch/patches/020-CVE-2018-1000156.patch b/tools/patch/patches/020-CVE-2018-1000156.patch
new file mode 100644
index 0000000..99dfe54
--- /dev/null
+++ b/tools/patch/patches/020-CVE-2018-1000156.patch
@@ -0,0 +1,142 @@
+From b3a0ca3deed00334f9feece43f76776b6a168e47 Mon Sep 17 00:00:00 2001
+From: Andreas Gruenbacher <agruen@gnu.org>
+Date: Fri, 6 Apr 2018 12:14:49 +0200
+Subject: [PATCH] Fix arbitrary command execution in ed-style patches
+ (CVE-2018-1000156)
+
+* src/pch.c (do_ed_script): Write ed script to a temporary file instead
+of piping it to ed: this will cause ed to abort on invalid commands
+instead of rejecting them and carrying on.
+* tests/ed-style: New test case.
+* tests/Makefile.am (TESTS): Add test case.
+---
+ src/pch.c | 89 +++++++++++++++++++++++++++++++++++++++++--------------
+ 1 file changed, 66 insertions(+), 23 deletions(-)
+
+--- a/src/pch.c
++++ b/src/pch.c
+@@ -33,6 +33,7 @@
+ # include <io.h>
+ #endif
+ #include <safe.h>
++#include <sys/wait.h>
+
+ #define INITHUNKMAX 125 /* initial dynamic allocation size */
+
+@@ -2389,22 +2390,28 @@ do_ed_script (char const *inname, char c
+ static char const editor_program[] = EDITOR_PROGRAM;
+
+ file_offset beginning_of_this_line;
+- FILE *pipefp = 0;
+ size_t chars_read;
++ FILE *tmpfp = 0;
++ char const *tmpname;
++ int tmpfd;
++ pid_t pid;
++
++ if (! dry_run && ! skip_rest_of_patch)
++ {
++ /* Write ed script to a temporary file. This causes ed to abort on
++ invalid commands such as when line numbers or ranges exceed the
++ number of available lines. When ed reads from a pipe, it rejects
++ invalid commands and treats the next line as a new command, which
++ can lead to arbitrary command execution. */
++
++ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0);
++ if (tmpfd == -1)
++ pfatal ("Can't create temporary file %s", quotearg (tmpname));
++ tmpfp = fdopen (tmpfd, "w+b");
++ if (! tmpfp)
++ pfatal ("Can't open stream for file %s", quotearg (tmpname));
++ }
+
+- if (! dry_run && ! skip_rest_of_patch) {
+- int exclusive = *outname_needs_removal ? 0 : O_EXCL;
+- assert (! inerrno);
+- *outname_needs_removal = true;
+- copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
+- sprintf (buf, "%s %s%s", editor_program,
+- verbosity == VERBOSE ? "" : "- ",
+- outname);
+- fflush (stdout);
+- pipefp = popen(buf, binary_transput ? "wb" : "w");
+- if (!pipefp)
+- pfatal ("Can't open pipe to %s", quotearg (buf));
+- }
+ for (;;) {
+ char ed_command_letter;
+ beginning_of_this_line = file_tell (pfp);
+@@ -2415,14 +2422,14 @@ do_ed_script (char const *inname, char c
+ }
+ ed_command_letter = get_ed_command_letter (buf);
+ if (ed_command_letter) {
+- if (pipefp)
+- if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
++ if (tmpfp)
++ if (! fwrite (buf, sizeof *buf, chars_read, tmpfp))
+ write_fatal ();
+ if (ed_command_letter != 'd' && ed_command_letter != 's') {
+ p_pass_comments_through = true;
+ while ((chars_read = get_line ()) != 0) {
+- if (pipefp)
+- if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
++ if (tmpfp)
++ if (! fwrite (buf, sizeof *buf, chars_read, tmpfp))
+ write_fatal ();
+ if (chars_read == 2 && strEQ (buf, ".\n"))
+ break;
+@@ -2435,13 +2442,49 @@ do_ed_script (char const *inname, char c
+ break;
+ }
+ }
+- if (!pipefp)
++ if (!tmpfp)
+ return;
+- if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0
+- || fflush (pipefp) != 0)
++ if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0
++ || fflush (tmpfp) != 0)
+ write_fatal ();
+- if (pclose (pipefp) != 0)
+- fatal ("%s FAILED", editor_program);
++
++ if (lseek (tmpfd, 0, SEEK_SET) == -1)
++ pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname));
++
++ if (! dry_run && ! skip_rest_of_patch) {
++ int exclusive = *outname_needs_removal ? 0 : O_EXCL;
++ *outname_needs_removal = true;
++ if (inerrno != ENOENT)
++ {
++ *outname_needs_removal = true;
++ copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
++ }
++ sprintf (buf, "%s %s%s", editor_program,
++ verbosity == VERBOSE ? "" : "- ",
++ outname);
++ fflush (stdout);
++
++ pid = fork();
++ if (pid == -1)
++ pfatal ("Can't fork");
++ else if (pid == 0)
++ {
++ dup2 (tmpfd, 0);
++ execl ("/bin/sh", "sh", "-c", buf, (char *) 0);
++ _exit (2);
++ }
++ else
++ {
++ int wstatus;
++ if (waitpid (pid, &wstatus, 0) == -1
++ || ! WIFEXITED (wstatus)
++ || WEXITSTATUS (wstatus) != 0)
++ fatal ("%s FAILED", editor_program);
++ }
++ }
++
++ fclose (tmpfp);
++ safe_unlink (tmpname);
+
+ if (ofp)
+ {
diff --git a/tools/patch/patches/030-CVE-2018-6952.patch b/tools/patch/patches/030-CVE-2018-6952.patch
new file mode 100644
index 0000000..36b58c7
--- /dev/null
+++ b/tools/patch/patches/030-CVE-2018-6952.patch
@@ -0,0 +1,25 @@
+From df40f2ea17254de269a3624319a12a93a4e395ff Mon Sep 17 00:00:00 2001
+From: Andreas Gruenbacher <agruen@gnu.org>
+Date: Fri, 17 Aug 2018 13:35:40 +0200
+Subject: [PATCH] Fix swapping fake lines in pch_swap
+
+* src/pch.c (pch_swap): Fix swapping p_bfake and p_efake when there is a
+blank line in the middle of a context-diff hunk: that empty line stays
+in the middle of the hunk and isn't swapped.
+
+Fixes: https://savannah.gnu.org/bugs/index.php?53133
+---
+ src/pch.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+--- a/src/pch.c
++++ b/src/pch.c
+@@ -2115,7 +2115,7 @@ pch_swap (void)
+ }
+ if (p_efake >= 0) { /* fix non-freeable ptr range */
+ if (p_efake <= i)
+- n = p_end - i + 1;
++ n = p_end - p_ptrn_lines;
+ else
+ n = -i;
+ p_efake += n;
diff --git a/tools/patch/patches/040-Fix-error-handling-with-git-style-patches.patch b/tools/patch/patches/040-Fix-error-handling-with-git-style-patches.patch
new file mode 100644
index 0000000..5cc958e
--- /dev/null
+++ b/tools/patch/patches/040-Fix-error-handling-with-git-style-patches.patch
@@ -0,0 +1,53 @@
+From 424da221cec76ea200cff1fa9b08a6f3d94c28a7 Mon Sep 17 00:00:00 2001
+From: Lubomir Rintel <lkundrak@v3.sk>
+Date: Wed, 31 Oct 2018 16:39:13 -0700
+Subject: [PATCH] Fix error handling with git-style patches
+
+When an error is encountered in output_files(), the subsequent call to
+cleanup() calls back into output_files() resulting in an infinte recursion.
+This is trivially reproduced with a git-style patch (which utilizes
+output_file_later()) that tries to patch a nonexistent or unreadable
+file (see attached test case).
+
+* src/patch.c: (output_files) clear the files_to_output list before
+iterating it, so that recursive calls won't iterate the same files.
+---
+ src/patch.c | 12 ++++++++----
+ 1 file changed, 8 insertions(+), 4 deletions(-)
+
+--- a/src/patch.c
++++ b/src/patch.c
+@@ -1938,8 +1938,12 @@ output_files (struct stat const *st)
+ {
+ gl_list_iterator_t iter;
+ const void *elt;
++ gl_list_t files;
+
+- iter = gl_list_iterator (files_to_output);
++ files = files_to_output;
++ init_files_to_output ();
++
++ iter = gl_list_iterator (files);
+ while (gl_list_iterator_next (&iter, &elt, NULL))
+ {
+ const struct file_to_output *file_to_output = elt;
+@@ -1957,8 +1961,8 @@ output_files (struct stat const *st)
+ /* Free the list up to here. */
+ for (;;)
+ {
+- const void *elt2 = gl_list_get_at (files_to_output, 0);
+- gl_list_remove_at (files_to_output, 0);
++ const void *elt2 = gl_list_get_at (files, 0);
++ gl_list_remove_at (files, 0);
+ if (elt == elt2)
+ break;
+ }
+@@ -1967,7 +1971,7 @@ output_files (struct stat const *st)
+ }
+ }
+ gl_list_iterator_free (&iter);
+- gl_list_clear (files_to_output);
++ gl_list_clear (files);
+ }
+
+ /* Fatal exit with cleanup. */
diff --git a/tools/patch/patches/050-CVE-2019-13636.patch b/tools/patch/patches/050-CVE-2019-13636.patch
new file mode 100644
index 0000000..d819838
--- /dev/null
+++ b/tools/patch/patches/050-CVE-2019-13636.patch
@@ -0,0 +1,101 @@
+From dce4683cbbe107a95f1f0d45fabc304acfb5d71a Mon Sep 17 00:00:00 2001
+From: Andreas Gruenbacher <agruen@gnu.org>
+Date: Mon, 15 Jul 2019 16:21:48 +0200
+Subject: Don't follow symlinks unless --follow-symlinks is given
+
+* src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file,
+append_to_file): Unless the --follow-symlinks option is given, open files with
+the O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing
+that consistently for input files.
+* src/util.c (create_backup): When creating empty backup files, (re)create them
+with O_CREAT | O_EXCL to avoid following symlinks in that case as well.
+---
+ src/inp.c | 12 ++++++++++--
+ src/util.c | 14 +++++++++++---
+ 2 files changed, 21 insertions(+), 5 deletions(-)
+
+--- a/src/inp.c
++++ b/src/inp.c
+@@ -238,8 +238,13 @@ plan_a (char const *filename)
+ {
+ if (S_ISREG (instat.st_mode))
+ {
+- int ifd = safe_open (filename, O_RDONLY|binary_transput, 0);
++ int flags = O_RDONLY | binary_transput;
+ size_t buffered = 0, n;
++ int ifd;
++
++ if (! follow_symlinks)
++ flags |= O_NOFOLLOW;
++ ifd = safe_open (filename, flags, 0);
+ if (ifd < 0)
+ pfatal ("can't open file %s", quotearg (filename));
+
+@@ -340,6 +345,7 @@ plan_a (char const *filename)
+ static void
+ plan_b (char const *filename)
+ {
++ int flags = O_RDONLY | binary_transput;
+ int ifd;
+ FILE *ifp;
+ int c;
+@@ -353,7 +359,9 @@ plan_b (char const *filename)
+
+ if (instat.st_size == 0)
+ filename = NULL_DEVICE;
+- if ((ifd = safe_open (filename, O_RDONLY | binary_transput, 0)) < 0
++ if (! follow_symlinks)
++ flags |= O_NOFOLLOW;
++ if ((ifd = safe_open (filename, flags, 0)) < 0
+ || ! (ifp = fdopen (ifd, binary_transput ? "rb" : "r")))
+ pfatal ("Can't open file %s", quotearg (filename));
+ if (TMPINNAME_needs_removal)
+--- a/src/util.c
++++ b/src/util.c
+@@ -388,7 +388,7 @@ create_backup (char const *to, const str
+
+ try_makedirs_errno = ENOENT;
+ safe_unlink (bakname);
+- while ((fd = safe_open (bakname, O_CREAT | O_WRONLY | O_TRUNC, 0666)) < 0)
++ while ((fd = safe_open (bakname, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, 0666)) < 0)
+ {
+ if (errno != try_makedirs_errno)
+ pfatal ("Can't create file %s", quotearg (bakname));
+@@ -579,10 +579,13 @@ create_file (char const *file, int open_
+ static void
+ copy_to_fd (const char *from, int tofd)
+ {
++ int from_flags = O_RDONLY | O_BINARY;
+ int fromfd;
+ ssize_t i;
+
+- if ((fromfd = safe_open (from, O_RDONLY | O_BINARY, 0)) < 0)
++ if (! follow_symlinks)
++ from_flags |= O_NOFOLLOW;
++ if ((fromfd = safe_open (from, from_flags, 0)) < 0)
+ pfatal ("Can't reopen file %s", quotearg (from));
+ while ((i = read (fromfd, buf, bufsize)) != 0)
+ {
+@@ -625,6 +628,8 @@ copy_file (char const *from, char const
+ else
+ {
+ assert (S_ISREG (mode));
++ if (! follow_symlinks)
++ to_flags |= O_NOFOLLOW;
+ tofd = create_file (to, O_WRONLY | O_BINARY | to_flags, mode,
+ to_dir_known_to_exist);
+ copy_to_fd (from, tofd);
+@@ -640,9 +645,12 @@ copy_file (char const *from, char const
+ void
+ append_to_file (char const *from, char const *to)
+ {
++ int to_flags = O_WRONLY | O_APPEND | O_BINARY;
+ int tofd;
+
+- if ((tofd = safe_open (to, O_WRONLY | O_BINARY | O_APPEND, 0)) < 0)
++ if (! follow_symlinks)
++ to_flags |= O_NOFOLLOW;
++ if ((tofd = safe_open (to, to_flags, 0)) < 0)
+ pfatal ("Can't reopen file %s", quotearg (to));
+ copy_to_fd (from, tofd);
+ if (close (tofd) != 0)
diff --git a/tools/patch/patches/060-CVE-2019-13638.patch b/tools/patch/patches/060-CVE-2019-13638.patch
new file mode 100644
index 0000000..590cf18
--- /dev/null
+++ b/tools/patch/patches/060-CVE-2019-13638.patch
@@ -0,0 +1,33 @@
+From 3fcd042d26d70856e826a42b5f93dc4854d80bf0 Mon Sep 17 00:00:00 2001
+From: Andreas Gruenbacher <agruen@gnu.org>
+Date: Fri, 6 Apr 2018 19:36:15 +0200
+Subject: Invoke ed directly instead of using the shell
+
+* src/pch.c (do_ed_script): Invoke ed directly instead of using a shell
+command to avoid quoting vulnerabilities.
+---
+ src/pch.c | 6 ++----
+ 1 file changed, 2 insertions(+), 4 deletions(-)
+
+--- a/src/pch.c
++++ b/src/pch.c
+@@ -2459,9 +2459,6 @@ do_ed_script (char const *inname, char c
+ *outname_needs_removal = true;
+ copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
+ }
+- sprintf (buf, "%s %s%s", editor_program,
+- verbosity == VERBOSE ? "" : "- ",
+- outname);
+ fflush (stdout);
+
+ pid = fork();
+@@ -2470,7 +2467,8 @@ do_ed_script (char const *inname, char c
+ else if (pid == 0)
+ {
+ dup2 (tmpfd, 0);
+- execl ("/bin/sh", "sh", "-c", buf, (char *) 0);
++ assert (outname[0] != '!' && outname[0] != '-');
++ execlp (editor_program, editor_program, "-", outname, (char *) NULL);
+ _exit (2);
+ }
+ else
diff --git a/tools/patch/patches/070-don-t-fail-hard-on-EACCES-when-copying-xattrs.patch b/tools/patch/patches/070-don-t-fail-hard-on-EACCES-when-copying-xattrs.patch
new file mode 100644
index 0000000..e19a9c0
--- /dev/null
+++ b/tools/patch/patches/070-don-t-fail-hard-on-EACCES-when-copying-xattrs.patch
@@ -0,0 +1,33 @@
+From f42cbe1a91a3a6f79d1eec594ce7c72aec79179b Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Thomas=20Wei=C3=9Fschuh?= <thomas@t-8ch.de>
+Date: Wed, 9 Nov 2022 05:08:22 +0100
+Subject: [PATCH] don't fail hard on EACCES when copying xattrs
+
+On btrfs the xattr "btrfs.compressed" requires privileges to set,
+otherwise EACCES is returned.
+When patch tries to do copy this attribute it receives the error and
+aborts.
+---
+ src/util.c | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+--- a/src/util.c
++++ b/src/util.c
+@@ -182,7 +182,7 @@ copy_attr_error (struct error_context *c
+ int err = errno;
+ va_list ap;
+
+- if (err != ENOSYS && err != ENOTSUP && err != EPERM)
++ if (err != ENOSYS && err != ENOTSUP && err != EPERM && err != EACCES)
+ {
+ /* use verror module to print error message */
+ va_start (ap, fmt);
+@@ -284,7 +284,7 @@ set_file_attributes (char const *to, enu
+ }
+ if (attr & FA_XATTRS)
+ if (copy_attr (from, to) != 0
+- && errno != ENOSYS && errno != ENOTSUP && errno != EPERM)
++ && errno != ENOSYS && errno != ENOTSUP && errno != EPERM && errno != EACCES)
+ fatal_exit (0);
+ if (attr & FA_MODE)
+ {
diff --git a/tools/patchelf/Makefile b/tools/patchelf/Makefile
new file mode 100644
index 0000000..bbda3a9
--- /dev/null
+++ b/tools/patchelf/Makefile
@@ -0,0 +1,30 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=patchelf
+PKG_VERSION:=0.18.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=https://github.com/NixOS/patchelf/releases/download/$(PKG_VERSION)
+PKG_HASH:=1952b2a782ba576279c211ee942e341748fdb44997f704dd53def46cd055470b
+
+HOST_BUILD_PARALLEL:=1
+HOST_FIXUP:=autoreconf
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/src/patchelf $(STAGING_DIR_HOST)/bin/patchelf
+endef
+
+define Host/Clean
+ rm -rf $(STAGING_DIR_HOST)/bin/patchelf
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/pkgconf/Makefile b/tools/pkgconf/Makefile
new file mode 100644
index 0000000..533af50
--- /dev/null
+++ b/tools/pkgconf/Makefile
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2006-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=pkgconf
+PKG_VERSION:=2.2.0
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://distfiles.dereferenced.org/pkgconf
+PKG_HASH:=28f8dfc279a10ef66148befa3f6eb266e5f3570316600208ed50e9781c7269d8
+
+PKG_CPE_ID:=cpe:/a:pkgconf:pkgconf
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/meson.mk
+
+unexport PKG_CONFIG
+
+HOSTCC := $(HOSTCC_NOCACHE)
+
+MESON_HOST_ARGS += \
+ -Ddefault_library=static \
+ -Dtests=disabled
+
+define Host/Install
+ $(call Host/Install/Meson)
+ mv $(STAGING_DIR_HOST)/bin/pkgconf $(STAGING_DIR_HOST)/bin/pkg-config.real
+ $(INSTALL_BIN) ./files/pkg-config $(STAGING_DIR_HOST)/bin/pkg-config
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/pkg-config.real $(STAGING_DIR_HOST)/bin/pkg-config
+ $(call Host/Clean/Meson)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/pkgconf/files/pkg-config b/tools/pkgconf/files/pkg-config
new file mode 100755
index 0000000..2e4dac9
--- /dev/null
+++ b/tools/pkgconf/files/pkg-config
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+${STAGING_DIR_HOST}/bin/pkg-config.real \
+--keep-system-cflags \
+--keep-system-libs \
+--define-variable=prefix="${STAGING_PREFIX}" \
+--define-variable=prefix_host="${STAGING_DIR_HOST}" \
+--define-variable=prefix_hostpkg="${STAGING_DIR_HOSTPKG}" \
+--define-variable=exec_prefix="${STAGING_PREFIX}" \
+--define-variable=bindir="${STAGING_PREFIX}/bin" \
+$PKG_CONFIG_EXTRAARGS "$@"
diff --git a/tools/quilt/Makefile b/tools/quilt/Makefile
new file mode 100644
index 0000000..73d1db9
--- /dev/null
+++ b/tools/quilt/Makefile
@@ -0,0 +1,36 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=quilt
+PKG_VERSION:=0.68
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@SAVANNAH/quilt
+PKG_HASH:=fe8c09de03c106e85b3737c8f03ade147c956b79ed7af485a1c8a3858db38426
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+ cd $(HOST_BUILD_DIR) && autoconf
+ $(call Host/Configure/Default)
+ [ -f $(HOST_BUILD_DIR)/Makefile ]
+endef
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR) SHELL="$(BASH)" all
+endef
+
+define Host/Install
+ $(MAKE) -C $(HOST_BUILD_DIR) SHELL="$(BASH)" install
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/quilt
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/quilt/patches/000-relocatable.patch b/tools/quilt/patches/000-relocatable.patch
new file mode 100644
index 0000000..caf5eb8
--- /dev/null
+++ b/tools/quilt/patches/000-relocatable.patch
@@ -0,0 +1,170 @@
+--- a/bin/quilt.in
++++ b/bin/quilt.in
+@@ -15,14 +15,22 @@ unset POSIXLY_CORRECT
+ unset GREP_OPTIONS
+
+ export TEXTDOMAIN=quilt
+-export TEXTDOMAINDIR=@LOCALEDIR@
+
+-: ${QUILT_DIR=@QUILT_DIR@}
++if test -n "$STAGING_DIR_HOST"; then
++ export TEXTDOMAINDIR="$STAGING_DIR_HOST/share/locale"
++ : ${QUILT_DIR=$STAGING_DIR_HOST/share/quilt} ${QUILT_LIB=$STAGING_DIR_HOST/lib/quilt}
++ : ${QUILT_ETC=$STAGING_DIR_HOST/etc}
++else
++ export TEXTDOMAINDIR=@LOCALEDIR@
++ : ${QUILT_DIR=@QUILT_DIR@}
++ : ${QUILT_ETC=@ETCDIR@}
++fi
++
+ export QUILT_DIR
+
+ if [ -z "$QUILTRC" ]
+ then
+- for QUILTRC in $HOME/.quiltrc @ETCDIR@/quilt.quiltrc; do
++ for QUILTRC in $HOME/.quiltrc $QUILT_ETC/quilt.quiltrc; do
+ [ -e $QUILTRC ] && break
+ done
+ export QUILTRC
+--- a/quilt/scripts/edmail.in
++++ b/quilt/scripts/edmail.in
+@@ -1,4 +1,6 @@
+-#! @PERL@ -w
++#! @PERL@
++
++use warnings;
+
+ # RFCs important for this script:
+ #
+@@ -29,7 +31,7 @@ BEGIN {
+ }
+
+ setlocale(LC_MESSAGES, "");
+-bindtextdomain("quilt", "@LOCALEDIR@");
++bindtextdomain("quilt", $ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/locale' : "@LOCALEDIR@");
+ textdomain("quilt");
+
+ sub _($) {
+--- a/quilt/scripts/patchfns.in
++++ b/quilt/scripts/patchfns.in
+@@ -8,7 +8,11 @@
+ # See the COPYING and AUTHORS files for more details.
+
+ export TEXTDOMAIN=quilt
+-export TEXTDOMAINDIR=@LOCALEDIR@
++if [ -n "$STAGING_DIR_HOST" ]; then
++ export TEXTDOMAINDIR="$STAGING_DIR_HOST/share/locale"
++else
++ export TEXTDOMAINDIR=@LOCALEDIR@
++fi
+
+ : ${LC_CTYPE:=$LANG}
+ : ${LC_MESSAGES:=$LANG}
+--- a/quilt/scripts/remove-trailing-ws.in
++++ b/quilt/scripts/remove-trailing-ws.in
+@@ -1,4 +1,6 @@
+-#! @PERL@ -w
++#! @PERL@
++
++use warnings;
+
+ # Remove trailing whitespace from modified lines in working files.
+ #
+@@ -31,7 +33,7 @@ BEGIN {
+ }
+
+ setlocale(LC_MESSAGES, "");
+-bindtextdomain("quilt", "@LOCALEDIR@");
++bindtextdomain("quilt", $ENV{'STAGING_DIR_HOST'} ? $ENV{'STAGING_DIR_HOST'} . '/share/locale' : "@LOCALEDIR@");
+ textdomain("quilt");
+
+ sub _($) {
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -21,8 +21,8 @@ COLUMN := @COLUMN@
+ GETOPT := @GETOPT@
+ CP := @CP@
+ DATE := @DATE@
+-PERL := @PERL@
+-BASH := @BASH@
++PERL := /usr/bin/env perl
++BASH := /usr/bin/env bash
+ SHELL:= @BASH@ # It does not work if dash is used as a shell, for example
+ GREP := @GREP@
+ TAIL := @TAIL@
+@@ -33,7 +33,7 @@ AWK := @AWK@
+ FIND := @FIND@
+ XARGS := @XARGS@
+ DIFF := @DIFF@
+-PATCH := @PATCH@
++PATCH := /usr/bin/env patch
+ MKTEMP := @MKTEMP@
+ MSGMERGE := @MSGMERGE@
+ MSGFMT := @MSGFMT@
+@@ -50,8 +50,8 @@ USE_NLS := @USE_NLS@
+ STAT_HARDLINK := @STAT_HARDLINK@
+ PATCH_WRAPPER := @PATCH_WRAPPER@
+
+-COMPAT_SYMLINKS := @COMPAT_SYMLINKS@
+-COMPAT_PROGRAMS := @COMPAT_PROGRAMS@
++COMPAT_SYMLINKS :=
++COMPAT_PROGRAMS :=
+
+ default: all
+
+--- a/quilt/scripts/backup-files.in
++++ b/quilt/scripts/backup-files.in
+@@ -53,7 +53,12 @@ usage ()
+ "
+ }
+
+-: ${QUILT_DIR=@QUILT_DIR@}
++if test -n "$STAGING_DIR_HOST"; then
++ : ${QUILT_DIR="$STAGING_DIR_HOST/share/quilt"}
++else
++ : ${QUILT_DIR=@QUILT_DIR@}
++fi
++
+ . $QUILT_DIR/scripts/utilfns
+
+ ensure_nolinks()
+--- a/bin/guards.in
++++ b/bin/guards.in
+@@ -1,4 +1,6 @@
+-#!@PERL@ -w
++#!@PERL@
++
++use warnings;
+
+ # This script is free software; you can redistribute it and/or modify
+ # it under the terms of the GNU General Public License version 2 as
+--- a/compat/date.in
++++ b/compat/date.in
+@@ -1,4 +1,6 @@
+-#! @PERL@ -w
++#! @PERL@
++
++use warnings;
+
+ # This script is free software; you can redistribute it and/or modify
+ # it under the terms of the GNU General Public License version 2 as
+--- a/compat/getopt.in
++++ b/compat/getopt.in
+@@ -1,4 +1,6 @@
+-#! @PERL@ -w
++#! @PERL@
++
++use warnings;
+
+ # This script is free software; you can redistribute it and/or modify
+ # it under the terms of the GNU General Public License version 2 as
+--- a/quilt/scripts/dependency-graph.in
++++ b/quilt/scripts/dependency-graph.in
+@@ -1,4 +1,6 @@
+-#!@PERL@ -w
++#!@PERL@
++
++use warnings;
+
+ # This script is free software; you can redistribute it and/or modify
+ # it under the terms of the GNU General Public License version 2 as
diff --git a/tools/quilt/patches/001-fix_compile.patch b/tools/quilt/patches/001-fix_compile.patch
new file mode 100644
index 0000000..ef6f8ff
--- /dev/null
+++ b/tools/quilt/patches/001-fix_compile.patch
@@ -0,0 +1,18 @@
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -276,13 +276,10 @@ $(patsubst %.in,%,$(wildcard bin/*.in qu
+ @$(if $(filter $@,$(NON_EXEC_IN)),,chmod +x $@)
+
+ configure : configure.ac aclocal.m4
+- autoconf
+- @echo "Please run ./configure"
+- @false
++ @touch $@
+
+ Makefile : Makefile.in configure
+- @echo "Please run ./configure"
+- @false
++ @touch $@
+
+ compat_leftover := $(filter-out $(COMPAT),$(shell $(FIND) compat -type f -perm -0100))
+
diff --git a/tools/sdimage/Makefile b/tools/sdimage/Makefile
new file mode 100644
index 0000000..e09b1e0
--- /dev/null
+++ b/tools/sdimage/Makefile
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=imx-uuc
+PKG_RELEASE:=1
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL:=https://github.com/mhei/fsl-imx-uuc.git
+PKG_SOURCE_DATE:=2018-11-18
+PKG_SOURCE_VERSION:=c6536ac5b4388b33c217bde2c3a76a4e96d64176
+PKG_MIRROR_HASH:=c4487635ea06ea6311a28739c58f7f889b888c91b7ccc0398d225b4bcdeb76a3
+
+PKG_LICENSE:=GPL-2.0+
+PKG_LICENSE_FILES:=LICENSE
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Configure
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/sdimage $(STAGING_DIR_HOST)/bin/sdimage
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/sdimage
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/sdimage/patches/100-deactivate-ufb.patch b/tools/sdimage/patches/100-deactivate-ufb.patch
new file mode 100644
index 0000000..2bf6ad2
--- /dev/null
+++ b/tools/sdimage/patches/100-deactivate-ufb.patch
@@ -0,0 +1,13 @@
+Deactivate ufb, this needs the UAPI Linux kernel headers from >= 3.18,
+this tools is currently not used, so just remove it for now.
+
+--- a/Makefile
++++ b/Makefile
+@@ -1,6 +1,6 @@
+ CC ?= $(CROSS_COMPILE)gcc
+ BINDIR ?= /usr/sbin
+-PROGRAMS = uuc sdimage ufb
++PROGRAMS = uuc sdimage
+ LIBS ?= -lpthread
+
+ all: $(PROGRAMS)
diff --git a/tools/sed/Makefile b/tools/sed/Makefile
new file mode 100644
index 0000000..f6bb61e
--- /dev/null
+++ b/tools/sed/Makefile
@@ -0,0 +1,50 @@
+#
+# Copyright (C) 2006-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=sed
+PKG_VERSION:=4.9
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/$(PKG_NAME)
+PKG_HASH:=d1478a18f033a73ac16822901f6533d30b6be561bcbce46ffd7abce93602282e
+PKG_CPE_ID:=cpe:/a:gnu:sed
+
+export SED:=
+
+HOST_BUILD_PARALLEL:=1
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOSTCXX := $(HOSTCXX_NOCACHE)
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += \
+ --disable-acl \
+ --disable-nls \
+ --enable-threads=posix \
+ --disable-i18n \
+ --without-selinux
+
+HOST_CONFIGURE_VARS += \
+ ac_cv_search_setfilecon=no \
+ ac_cv_header_selinux_context_h=no \
+ ac_cv_header_selinux_selinux_h=no \
+
+define Host/Compile
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR) SHELL="$(BASH)"
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/sed/sed $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/sed
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/sed/patches/001-sed-fix-handling-of-symlinks-pointing-to-path-with-1.patch b/tools/sed/patches/001-sed-fix-handling-of-symlinks-pointing-to-path-with-1.patch
new file mode 100644
index 0000000..96ae5bd
--- /dev/null
+++ b/tools/sed/patches/001-sed-fix-handling-of-symlinks-pointing-to-path-with-1.patch
@@ -0,0 +1,47 @@
+From 8f600f2df293d539e9e9137f6f82faa1633b97c1 Mon Sep 17 00:00:00 2001
+From: Paul Eggert <eggert@cs.ucla.edu>
+Date: Sat, 17 Dec 2022 20:56:29 -0800
+Subject: [PATCH] sed: fix symlink bufsize readlink check
+
+Problem reported by Hauke Mehrtens.
+* sed/utils.c (follow_symlink): Fix typo when checking size of
+second and later symlink, when that symlink is so large that it
+does not fit into the buffer. Although the bug is not a buffer
+overflow, it does cause sed to mishandle the symlink.
+* testsuite/follow-symlinks.sh: Test for the bug.
+---
+ sed/utils.c | 2 +-
+ testsuite/follow-symlinks.sh | 13 +++++++++++++
+ 3 files changed, 18 insertions(+), 1 deletion(-)
+
+--- a/sed/utils.c
++++ b/sed/utils.c
+@@ -345,7 +345,7 @@ follow_symlink (const char *fname)
+ while ((linklen = (buf_used < buf_size
+ ? readlink (fn, buf + buf_used, buf_size - buf_used)
+ : 0))
+- == buf_size)
++ == buf_size - buf_used)
+ {
+ buf = xpalloc (buf, &buf_size, 1, SSIZE_IDX_MAX, 1);
+ if (num_links)
+--- a/testsuite/follow-symlinks.sh
++++ b/testsuite/follow-symlinks.sh
+@@ -73,4 +73,17 @@ compare_ exp-la-abs out-la-abs || fail=1
+ ln -s la-loop la-loop || framework_failure_
+ sed --follow-symlinks -i s/a/b/ la-loop && fail=1
+
++# symlink of length 128
++long=d/
++for i in 2 3 4 5 6 7; do
++ long=$long$long
++done
++dir=${long%/d/}
++file=$dir/xx
++mkdir -p $dir &&
++echo x >$file &&
++ln -s $file yy &&
++ln -s yy xx || framework_failure_
++sed -i --follow-symlinks s/x/y/ xx || fail=1
++
+ Exit $fail
diff --git a/tools/sparse/Makefile b/tools/sparse/Makefile
new file mode 100644
index 0000000..a46e495
--- /dev/null
+++ b/tools/sparse/Makefile
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2014 Qualcomm-Atheros Inc.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=sparse
+
+PKG_VERSION:=0.6.4
+PKG_HASH:=8b907c007459a66db110496f0a02fcff1c3c8b67ddff37b959fb102a28424209
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@KERNEL/software/devel/sparse/dist/
+
+PKG_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/sparse $(STAGING_DIR_HOST)/bin
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/sparse
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/sparse/patches/010-llvm15.patch b/tools/sparse/patches/010-llvm15.patch
new file mode 100644
index 0000000..54fddc7
--- /dev/null
+++ b/tools/sparse/patches/010-llvm15.patch
@@ -0,0 +1,128 @@
+From 0544c547682b878758eea731ef4b8e64e5ec91fb Mon Sep 17 00:00:00 2001
+From: Luc Van Oostenryck <lucvoo@kernel.org>
+Date: Sat, 20 Jan 2024 01:24:12 +0100
+Subject: llvm: fix LLVM 15 deprecation warnings
+
+LLVM 15 switched to opaque pointers by default and no longer supports typed pointers.
+Remove deprecated LLVM calls and update test.
+
+Original-patch-by: Vladimir Petko <vladimir.petko@canonical.com>
+Signed-off-by: Luc Van Oostenryck <lucvoo@kernel.org>
+---
+ sparse-llvm.c | 35 ++++++++++++++++++++++++++++++++++-
+ validation/backend/call-variadic.c | 16 ++++------------
+ 2 files changed, 38 insertions(+), 13 deletions(-)
+
+--- a/sparse-llvm.c
++++ b/sparse-llvm.c
+@@ -32,6 +32,20 @@ static LLVMTypeRef func_return_type(stru
+ return symbol_type(sym->ctype.base_type);
+ }
+
++#if LLVM_VERSION_MAJOR > 14
++// A call can be done either with a SYM_FN or a SYM_PTR (pointing to a SYM_FN).
++// Return the type corresponding to the SYM_FN.
++static LLVMTypeRef func_full_type(struct symbol *type)
++{
++ if (type->type == SYM_NODE) {
++ struct symbol *btype = type->ctype.base_type;
++ if (btype->type == SYM_PTR)
++ type = btype->ctype.base_type;
++ }
++ return symbol_type(type);
++}
++#endif
++
+ static LLVMTypeRef sym_func_type(struct symbol *sym)
+ {
+ int n_arg = symbol_list_size(sym->arguments);
+@@ -302,7 +316,11 @@ static LLVMValueRef get_sym_value(LLVMMo
+ LLVMSetGlobalConstant(data, 1);
+ LLVMSetInitializer(data, LLVMConstString(strdup(s), strlen(s) + 1, true));
+
++#if LLVM_VERSION_MAJOR > 14
++ result = LLVMConstGEP2(LLVMTypeOf(data), data, indices, ARRAY_SIZE(indices));
++#else
+ result = LLVMConstGEP(data, indices, ARRAY_SIZE(indices));
++#endif
+ return result;
+ }
+ default:
+@@ -485,7 +503,11 @@ static LLVMValueRef calc_gep(LLVMBuilder
+ /* convert base to char* type */
+ base = LLVMBuildPointerCast(builder, base, bytep, name);
+ /* addr = base + off */
++#if LLVM_VERSION_MAJOR > 14
++ addr = LLVMBuildInBoundsGEP2(builder, LLVMTypeOf(base), base, &off, 1, name);
++#else
+ addr = LLVMBuildInBoundsGEP(builder, base, &off, 1, name);
++#endif
+ /* convert back to the actual pointer type */
+ addr = LLVMBuildPointerCast(builder, addr, type, name);
+ return addr;
+@@ -711,7 +733,11 @@ static void output_op_load(struct functi
+
+ /* perform load */
+ pseudo_name(insn->target, name);
++#if LLVM_VERSION_MAJOR > 14
++ target = LLVMBuildLoad2(fn->builder, symbol_type(insn->type), addr, name);
++#else
+ target = LLVMBuildLoad(fn->builder, addr, name);
++#endif
+
+ insn->target->priv = target;
+ }
+@@ -797,6 +823,7 @@ static void output_op_switch(struct func
+ static void output_op_call(struct function *fn, struct instruction *insn)
+ {
+ LLVMValueRef target, func;
++ struct symbol *fntype;
+ struct symbol *ctype;
+ int n_arg = 0, i;
+ struct pseudo *arg;
+@@ -812,14 +839,20 @@ static void output_op_call(struct functi
+ else
+ func = pseudo_to_value(fn, ctype, insn->func);
+ i = 0;
++ fntype = ctype; // first symbol in the list is the function 'true' type
+ FOR_EACH_PTR(insn->arguments, arg) {
+- NEXT_PTR_LIST(ctype);
++ NEXT_PTR_LIST(ctype); // the remaining ones are the arguments' type
+ args[i++] = pseudo_to_rvalue(fn, ctype, arg);
+ } END_FOR_EACH_PTR(arg);
+ FINISH_PTR_LIST(ctype);
+
+ pseudo_name(insn->target, name);
++#if LLVM_VERSION_MAJOR > 14
++ target = LLVMBuildCall2(fn->builder, func_full_type(fntype), func, args, n_arg, name);
++#else
++ (void) fntype;
+ target = LLVMBuildCall(fn->builder, func, args, n_arg, name);
++#endif
+
+ insn->target->priv = target;
+ }
+--- a/validation/backend/call-variadic.c
++++ b/validation/backend/call-variadic.c
+@@ -11,17 +11,9 @@ int foo(const char *fmt, int a, long l,
+ /*
+ * check-name: call-variadic
+ * check-command: sparse-llvm-dis -m64 $file
++ * check-output-ignore
++ * check-output-contains: , ...) @print(\\(i8\\*\\|ptr\\) %ARG1., i32 120, i32 %ARG2., i32 8, i64 %ARG3., i64 0, \\(i32\\*\\|ptr\\) %ARG4., \\(i8\\*\\|ptr\\) null)
++ * check-output-contains: define i32 @foo(
++ * check-output-contains: declare i32 @print(
+ *
+- * check-output-start
+-; ModuleID = '<stdin>'
+-source_filename = "sparse"
+-
+-define i32 @foo(i8* %ARG1., i32 %ARG2., i64 %ARG3., i32* %ARG4.) {
+-L0:
+- %R5. = call i32 (i8*, ...) @print(i8* %ARG1., i32 120, i32 %ARG2., i32 8, i64 %ARG3., i64 0, i32* %ARG4., i8* null)
+- ret i32 %R5.
+-}
+-
+-declare i32 @print(i8*, ...)
+- * check-output-end
+ */
diff --git a/tools/squashfs3-lzma/Makefile b/tools/squashfs3-lzma/Makefile
new file mode 100644
index 0000000..b020186
--- /dev/null
+++ b/tools/squashfs3-lzma/Makefile
@@ -0,0 +1,46 @@
+#
+# Copyright (C) 2006-2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=squashfs3-lzma
+PKG_CPE_ID:=cpe:/a:phillip_lougher:squashfs
+PKG_VERSION:=3.0
+
+PKG_SOURCE:=squashfs$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@SF/squashfs
+PKG_HASH:=39dbda43cf118536deb746c7730b468702d514a19f4cfab73b710e32908ddf20
+
+# Tar directory is squashfs3.0 that conflict with any pattern
+# currently using for host tools. (PKG_NAME-PKG_VERSION)
+# Also this got renamed to a more correct name
+# from squashfs to squashfs3-lzma.
+# Use tar transform to rename the root directory to this new
+# name.
+TAR_OPTIONS+=--transform=s/^squashfs/$(PKG_NAME)-/
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ $(MAKE) -C $(HOST_BUILD_DIR)/squashfs-tools \
+ CC="$(HOSTCC)" \
+ CFLAGS="$(HOST_CFLAGS) -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -I." \
+ CXX="$(CXX)" \
+ LZMAPATH=$(STAGING_DIR_HOST)/lib \
+ mksquashfs-lzma unsquashfs-lzma
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/squashfs-tools/mksquashfs-lzma $(STAGING_DIR_HOST)/bin/mksquashfs3-lzma
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/squashfs-tools/unsquashfs-lzma $(STAGING_DIR_HOST)/bin/unsquashfs3-lzma
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/mksquashfs3-lzma
+ rm -f $(STAGING_DIR_HOST)/bin/unsquashfs3-lzma
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/squashfs3-lzma/patches/100-lzma.patch b/tools/squashfs3-lzma/patches/100-lzma.patch
new file mode 100644
index 0000000..73f6a4e
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/100-lzma.patch
@@ -0,0 +1,22 @@
+--- a/squashfs-tools/Makefile
++++ b/squashfs-tools/Makefile
+@@ -7,6 +7,9 @@ all: mksquashfs unsquashfs
+ mksquashfs: mksquashfs.o read_fs.o sort.o
+ $(CC) mksquashfs.o read_fs.o sort.o -lz -o $@
+
++mksquashfs-lzma: mksquashfs.o read_fs.o sort.o
++ $(CXX) mksquashfs.o read_fs.o sort.o -L$(LZMAPATH) -llzma-old -o $@
++
+ mksquashfs.o: mksquashfs.c squashfs_fs.h mksquashfs.h global.h sort.h
+
+ read_fs.o: read_fs.c squashfs_fs.h read_fs.h global.h
+@@ -16,4 +19,9 @@ sort.o: sort.c squashfs_fs.h global.h so
+ unsquashfs: unsquashfs.o
+ $(CC) unsquashfs.o -lz -o $@
+
++unsquashfs-lzma: unsquashfs.o
++ $(CXX) unsquashfs.o -L$(LZMAPATH) -llzma-old -o $@
++
+ unsquashfs.o: unsquashfs.c squashfs_fs.h read_fs.h global.h
++
++clean:
diff --git a/tools/squashfs3-lzma/patches/110-no_nonstatic_inline.patch b/tools/squashfs3-lzma/patches/110-no_nonstatic_inline.patch
new file mode 100644
index 0000000..8e288f3
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/110-no_nonstatic_inline.patch
@@ -0,0 +1,11 @@
+--- a/squashfs-tools/mksquashfs.c
++++ b/squashfs-tools/mksquashfs.c
+@@ -1347,7 +1347,7 @@ struct inode_info *lookup_inode(struct s
+ }
+
+
+-inline void add_dir_entry(char *name, char *pathname, struct dir_info *sub_dir, struct inode_info *inode_info, void *data, struct dir_info *dir)
++static inline void add_dir_entry(char *name, char *pathname, struct dir_info *sub_dir, struct inode_info *inode_info, void *data, struct dir_info *dir)
+ {
+ if((dir->count % DIR_ENTRIES) == 0)
+ if((dir->list = realloc(dir->list, (dir->count + DIR_ENTRIES) * sizeof(struct dir_ent *))) == NULL)
diff --git a/tools/squashfs3-lzma/patches/120-add-fixed-timestamp-support.patch b/tools/squashfs3-lzma/patches/120-add-fixed-timestamp-support.patch
new file mode 100644
index 0000000..e2f4bb2
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/120-add-fixed-timestamp-support.patch
@@ -0,0 +1,79 @@
+--- a/squashfs-tools/mksquashfs.c
++++ b/squashfs-tools/mksquashfs.c
+@@ -117,6 +117,9 @@ unsigned int inode_bytes = 0, inode_size
+ char *data_cache = NULL;
+ unsigned int cache_bytes = 0, cache_size = 0, inode_count = 0;
+
++/* override all timestamps */
++time_t fixed_time = -1;
++
+ /* in memory directory data */
+ #define I_COUNT_SIZE 128
+ #define DIR_ENTRIES 32
+@@ -1554,6 +1557,11 @@ void dir_scan(squashfs_inode *inode, cha
+ perror(buffer);
+ return;
+ }
++
++ /* override timestamp of lstat if fixed_time is given */
++ if(fixed_time != -1)
++ inode_info->buf.st_mtime = fixed_time;
++
+ if(sorted)
+ sort_files_and_write(dir_info);
+ dir_scan2(inode, dir_info);
+@@ -1582,6 +1590,10 @@ struct dir_info *dir_scan1(char *pathnam
+ perror(buffer);
+ continue;
+ }
++
++ if(fixed_time != -1)
++ buf.st_mtime = fixed_time;
++
+ if(excluded(filename, &buf))
+ continue;
+
+@@ -1621,6 +1633,9 @@ int dir_scan2(squashfs_inode *inode, str
+ char *dir_name = dir_ent->name;
+ unsigned int inode_number = ((buf->st_mode & S_IFMT) == S_IFDIR) ? dir_ent->inode->inode_number : dir_ent->inode->inode_number + dir_inode_no;
+
++ if(fixed_time != -1)
++ buf->st_mtime = fixed_time;
++
+ if(dir_ent->inode->inode == SQUASHFS_INVALID_BLK) {
+ switch(buf->st_mode & S_IFMT) {
+ case S_IFREG:
+@@ -1898,6 +1913,16 @@ int main(int argc, char *argv[])
+ exit(1);
+ }
+ }
++ } else if(strcmp(argv[i], "-fixed-time") == 0) {
++ if(++i == argc) {
++ ERROR("%s: -fixed-time missing a timestamp\n", argv[0]);
++ exit(1);
++ }
++ fixed_time = strtoll(argv[i], &b, 10);
++ if(*b != '\0') {
++ ERROR("%s: -fixed-time has an invalid number\n", argv[0]);
++ exit(1);
++ }
+ } else if(strcmp(argv[i], "-noI") == 0 ||
+ strcmp(argv[i], "-noInodeCompression") == 0)
+ noI = TRUE;
+@@ -1967,6 +1992,7 @@ printOptions:
+ ERROR("-all-root\t\tmake all files owned by root\n");
+ ERROR("-force-uid uid\t\tset all file uids to uid\n");
+ ERROR("-force-gid gid\t\tset all file gids to gid\n");
++ ERROR("-fixed-time timestamp\tset all timestamps to timestamp\n");
+ ERROR("-le\t\t\tcreate a little endian filesystem\n");
+ ERROR("-be\t\t\tcreate a big endian filesystem\n");
+ ERROR("-nopad\t\t\tdo not pad filesystem to a multiple of 4K\n");
+@@ -2190,7 +2216,7 @@ printOptions:
+ sBlk.block_size = block_size;
+ sBlk.block_log = block_log;
+ sBlk.flags = SQUASHFS_MKFLAGS(noI, noD, check_data, noF, no_fragments, always_use_fragments, duplicate_checking);
+- sBlk.mkfs_time = time(NULL);
++ sBlk.mkfs_time = fixed_time != -1 ? fixed_time : time(NULL);
+
+ restore_filesystem:
+ write_fragment();
diff --git a/tools/squashfs3-lzma/patches/130-include_sysmacros.patch b/tools/squashfs3-lzma/patches/130-include_sysmacros.patch
new file mode 100644
index 0000000..f0149d6
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/130-include_sysmacros.patch
@@ -0,0 +1,20 @@
+--- a/squashfs-tools/mksquashfs.c
++++ b/squashfs-tools/mksquashfs.c
+@@ -30,6 +30,7 @@
+ #include <unistd.h>
+ #include <stdio.h>
+ #include <sys/types.h>
++#include <sys/sysmacros.h>
+ #include <sys/stat.h>
+ #include <fcntl.h>
+ #include <errno.h>
+--- a/squashfs-tools/unsquashfs.c
++++ b/squashfs-tools/unsquashfs.c
+@@ -25,6 +25,7 @@
+ #define FALSE 0
+ #include <stdio.h>
+ #include <sys/types.h>
++#include <sys/sysmacros.h>
+ #include <sys/stat.h>
+ #include <fcntl.h>
+ #include <errno.h>
diff --git a/tools/squashfs3-lzma/patches/140-gcc-10-fix.patch b/tools/squashfs3-lzma/patches/140-gcc-10-fix.patch
new file mode 100644
index 0000000..a02641f
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/140-gcc-10-fix.patch
@@ -0,0 +1,25 @@
+Fixes the following build error with GCC 10:
+ /usr/bin/ld: read_fs.o:(.bss+0x0): multiple definition of `swap'; mksquashfs.o:(.bss+0x1b2a88): first defined here
+And a compile warning.
+
+--- a/squashfs-tools/read_fs.c
++++ b/squashfs-tools/read_fs.c
+@@ -61,7 +61,7 @@ extern int add_file(long long, long long
+ fprintf(stderr, s, ## args); \
+ } while(0)
+
+-int swap;
++static int swap;
+
+ int read_block(int fd, long long start, long long *next, unsigned char *block, squashfs_super_block *sBlk)
+ {
+--- a/squashfs-tools/mksquashfs.c
++++ b/squashfs-tools/mksquashfs.c
+@@ -258,6 +258,7 @@ int read_sort_file(char *filename, int s
+ void sort_files_and_write(struct dir_info *dir);
+ struct file_info *duplicate(char *(get_next_file_block)(struct duplicate_buffer_handle *, unsigned int), struct duplicate_buffer_handle *file_start, long long bytes, unsigned int **block_list, long long *start, int blocks, struct fragment **fragment, char *frag_data, int frag_bytes);
+ struct dir_info *dir_scan1(char *, int (_readdir)(char *, char *, struct dir_info *));
++int dir_scan2(squashfs_inode *inode, struct dir_info *dir_info);
+
+ #define MKINODE(A) ((squashfs_inode)(((squashfs_inode) inode_bytes << 16) + (((char *)A) - data_cache)))
+
diff --git a/tools/squashfs3-lzma/patches/150-fix-unitialized-memory.patch b/tools/squashfs3-lzma/patches/150-fix-unitialized-memory.patch
new file mode 100644
index 0000000..ad3b820
--- /dev/null
+++ b/tools/squashfs3-lzma/patches/150-fix-unitialized-memory.patch
@@ -0,0 +1,11 @@
+--- a/squashfs-tools/mksquashfs.c
++++ b/squashfs-tools/mksquashfs.c
+@@ -1822,7 +1822,7 @@ int main(int argc, char *argv[])
+ {
+ struct stat buf, source_buf;
+ int i;
+- squashfs_super_block sBlk;
++ squashfs_super_block sBlk = {};
+ char *b, *root_name = NULL;
+ int be, nopad = FALSE, keep_as_directory = FALSE, orig_be;
+ squashfs_inode inode;
diff --git a/tools/squashfs4/Makefile b/tools/squashfs4/Makefile
new file mode 100644
index 0000000..a5c0c93
--- /dev/null
+++ b/tools/squashfs4/Makefile
@@ -0,0 +1,50 @@
+#
+# Copyright (C) 2009-2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=squashfs4
+PKG_CPE_ID:=cpe:/a:phillip_lougher:squashfs
+PKG_VERSION:=4.6.1
+PKG_RELEASE=3
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL:=https://github.com/plougher/squashfs-tools
+PKG_SOURCE_DATE:=2023-03-26
+PKG_SOURCE_VERSION:=d8cb82d9840330f9344ec37b992595b5d7b44184
+PKG_SOURCE:=squashfs$(PKG_VERSION)-$(PKG_SOURCE_VERSION).tar.gz
+PKG_SOURCE_SUBDIR:=squashfs$(PKG_VERSION)
+PKG_MIRROR_HASH:=e84026de1ab187f3f76d1b781a29259d818f887e1651225f850a62d6f90b1b9e
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/squashfs$(PKG_VERSION)
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ +$(HOST_MAKE_VARS) \
+ $(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/squashfs-tools \
+ XZ_SUPPORT=1 \
+ LZMA_XZ_SUPPORT=1 \
+ XATTR_SUPPORT=1 \
+ XZ_EXTENDED_OPTIONS=1 \
+ LZMA_LIB="$(STAGING_DIR_HOST)/lib/liblzma.a" \
+ EXTRA_CFLAGS="-I$(STAGING_DIR_HOST)/include" \
+ mksquashfs unsquashfs
+endef
+
+define Host/Install
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/squashfs-tools/mksquashfs $(STAGING_DIR_HOST)/bin/mksquashfs4
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/squashfs-tools/unsquashfs $(STAGING_DIR_HOST)/bin/unsquashfs4
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/mksquashfs4
+ rm -f $(STAGING_DIR_HOST)/bin/unsquashfs4
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/squashfs4/patches/001-xz_wrapper-support-multiple-lzma-configuration-optio.patch b/tools/squashfs4/patches/001-xz_wrapper-support-multiple-lzma-configuration-optio.patch
new file mode 100644
index 0000000..bcc962a
--- /dev/null
+++ b/tools/squashfs4/patches/001-xz_wrapper-support-multiple-lzma-configuration-optio.patch
@@ -0,0 +1,187 @@
+From dcb976fe4ee40e4bac8ae0dcc836629c625a6fd4 Mon Sep 17 00:00:00 2001
+From: Christian Marangi <ansuelsmth@gmail.com>
+Date: Fri, 14 Oct 2022 15:59:16 +0200
+Subject: [PATCH] xz_wrapper: support multiple lzma configuration options
+
+Add option to configure preset, lc, lp and pb lzma parameters.
+-Xpreset can be used to set the compression level.
+-Xe can be used to set the 'EXTREME' flag to use the lzma compression
+options tweaking additional settings on top of the compression level set.
+
+New option added:
+ -Xpreset
+ -Xe
+ -Xlc
+ -Xlp
+ -Xpb
+
+Signed-off-by: Christian Marangi <ansuelsmth@gmail.com>
+---
+ squashfs-tools/xz_wrapper.c | 119 ++++++++++++++++++++++++++++++++++--
+ 1 file changed, 115 insertions(+), 4 deletions(-)
+
+--- a/squashfs-tools/xz_wrapper.c
++++ b/squashfs-tools/xz_wrapper.c
+@@ -44,7 +44,10 @@ static struct bcj bcj[] = {
+ static int filter_count = 1;
+ static int dictionary_size = 0;
+ static float dictionary_percent = 0;
+-
++static int preset = LZMA_PRESET_DEFAULT;
++static int lc = -1;
++static int lp = -1;
++static int pb = -1;
+
+ /*
+ * This function is called by the options parsing code in mksquashfs.c
+@@ -53,6 +56,11 @@ static float dictionary_percent = 0;
+ * Two specific options are supported:
+ * -Xbcj
+ * -Xdict-size
++ * -Xpreset
++ * -Xe
++ * -Xlc
++ * -Xlp
++ * -Xpb
+ *
+ * This function returns:
+ * >=0 (number of additional args parsed) on success
+@@ -141,6 +149,85 @@ static int xz_options(char *argv[], int
+ }
+
+ return 1;
++ } else if(strcmp(argv[0], "-Xpreset") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xpreset missing preset-level "
++ "(valid value 0-9)\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < 0 || (int) val & ~LZMA_PRESET_LEVEL_MASK) {
++ fprintf(stderr, "xz: -Xpreset can't be "
++ "negative or more than the max preset\n");
++ goto failed;
++ }
++
++ preset &= ~LZMA_PRESET_LEVEL_MASK;
++ preset |= (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xe") == 0) {
++ preset |= LZMA_PRESET_EXTREME;
++
++ return 0;
++ } else if(strcmp(argv[0], "-Xlc") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xlc missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
++ fprintf(stderr, "xz: -Xlc invalid value\n");
++ goto failed;
++ }
++
++ lc = (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xlp") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xlp missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
++ fprintf(stderr, "xz: -Xlp invalid value\n");
++ goto failed;
++ }
++
++ lp = (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xpb") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xpb missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_PB_MIN || (int) val > LZMA_PB_MAX) {
++ fprintf(stderr, "xz: -Xpb invalid value\n");
++ goto failed;
++ }
++
++ pb = (int) val;
++
++ return 1;
+ }
+
+ return -1;
+@@ -446,11 +533,20 @@ static int xz_compress(void *strm, void
+ for(i = 0; i < stream->filters; i++) {
+ struct filter *filter = &stream->filter[i];
+
+- if(lzma_lzma_preset(&stream->opt, LZMA_PRESET_DEFAULT))
+- goto failed;
++ if(lzma_lzma_preset(&stream->opt, preset))
++ goto failed;
+
+ stream->opt.dict_size = stream->dictionary_size;
+
++ if (lc >= 0)
++ stream->opt.lc = lc;
++
++ if (lp >= 0)
++ stream->opt.lp = lp;
++
++ if (pb >= 0)
++ stream->opt.pb = pb;
++
+ filter->length = 0;
+ res = lzma_stream_buffer_encode(filter->filter,
+ LZMA_CHECK_CRC32, NULL, src, size, filter->buffer,
+@@ -521,13 +617,28 @@ static void xz_usage(FILE *stream)
+ fprintf(stream, " header as either 2^n or as 2^n+2^(n+1).\n\t\t");
+ fprintf(stream, "Example dict-sizes are 75%%, 50%%, 37.5%%, 25%%, or");
+ fprintf(stream, " 32K, 16K, 8K\n\t\tetc.\n");
++ fprintf(stream, "\t -Xpreset <preset-level>\n");
++ fprintf(stream, "\t\tUse <preset-value> as the custom preset to use");
++ fprintf(stream, " on compress.\n\t\t<preset-level> should be 0 .. 9");
++ fprintf(stream, " (default 6)\n");
++ fprintf(stream, "\t -Xe\n");
++ fprintf(stream, "\t\tEnable additional compression settings by passing");
++ fprintf(stream, " the EXTREME\n\t\tflag to the compression flags.\n");
++ fprintf(stream, "\t -Xlc <value>\n");
++ fprintf(stream, "\t -Xlp <value>\n");
++ fprintf(stream, "\t -Xpb <value>\n");
+ }
+
+
+ static int option_args(char *option)
+ {
+ if(strcmp(option, "-Xbcj") == 0 ||
+- strcmp(option, "-Xdict-size") == 0)
++ strcmp(option, "-Xdict-size") == 0 ||
++ strcmp(option, "-Xpreset") == 0 ||
++ strcmp(option, "-Xe") == 0 ||
++ strcmp(option, "-Xlc") == 0 ||
++ strcmp(option, "-Xlp") == 0 ||
++ strcmp(option, "-Xpb") == 0)
+ return 1;
+
+ return 0;
diff --git a/tools/squashfs4/patches/002-xz_wrapper-make-new-OpenWrt-extended-options-non-def.patch b/tools/squashfs4/patches/002-xz_wrapper-make-new-OpenWrt-extended-options-non-def.patch
new file mode 100644
index 0000000..92b6a1a
--- /dev/null
+++ b/tools/squashfs4/patches/002-xz_wrapper-make-new-OpenWrt-extended-options-non-def.patch
@@ -0,0 +1,898 @@
+From 5fb9fdfb8757fc9afb6318a3dcf9dce0a97de352 Mon Sep 17 00:00:00 2001
+From: Phillip Lougher <phillip@squashfs.org.uk>
+Date: Wed, 19 Apr 2023 18:35:53 +0100
+Subject: [PATCH] xz_wrapper: make new OpenWrt extended options non-default
+
+The reason why these options are being made non-default are
+described here:
+
+https://github.com/plougher/squashfs-tools/pull/218#issuecomment-1515197256
+
+The new options can be enabled by editing the Makefile or by defining
+XZ_EXTENDED_OPTIONS on the Make command line, e.g.
+
+% CONFIG=1 XZ_SUPPORT=1 XZ_EXTENDED_OPTIONS=1 make
+
+Signed-off-by: Phillip Lougher <phillip@squashfs.org.uk>
+---
+ squashfs-tools/Makefile | 12 +
+ squashfs-tools/xz_wrapper.c | 117 +----
+ squashfs-tools/xz_wrapper_extended.c | 664 +++++++++++++++++++++++++++
+ 3 files changed, 679 insertions(+), 114 deletions(-)
+ create mode 100644 squashfs-tools/xz_wrapper_extended.c
+
+--- a/squashfs-tools/Makefile
++++ b/squashfs-tools/Makefile
+@@ -39,6 +39,10 @@ GZIP_SUPPORT = 1
+ #
+ #XZ_SUPPORT = 1
+
++# Enable support for OpenWrt extended compression options by uncommenting
++# next line. Do not do this unless you understand the implications.
++#XZ_EXTENDED_OPTIONS = 1
++
+
+ ############ Building LZO support ##############
+ #
+@@ -197,6 +201,7 @@ INSTALL_MANPAGES_DIR ?= $(INSTALL_PREFIX
+ LZMA_XZ_SUPPORT ?= 0
+ LZMA_SUPPORT ?= 0
+ LZMA_DIR ?= ../../../../LZMA/lzma465
++XZ_EXTENDED_OPTIONS ?= 0
+ endif
+
+
+@@ -248,8 +253,13 @@ endif
+
+ ifeq ($(XZ_SUPPORT),1)
+ CFLAGS += -DXZ_SUPPORT
++ifeq ($(XZ_EXTENDED_OPTIONS),1)
++MKSQUASHFS_OBJS += xz_wrapper_extended.o
++UNSQUASHFS_OBJS += xz_wrapper_extended.o
++else
+ MKSQUASHFS_OBJS += xz_wrapper.o
+ UNSQUASHFS_OBJS += xz_wrapper.o
++endif
+ LIBS += -llzma
+ COMPRESSORS += xz
+ endif
+@@ -428,6 +438,8 @@ lz4_wrapper.o: lz4_wrapper.c squashfs_fs
+
+ xz_wrapper.o: xz_wrapper.c squashfs_fs.h xz_wrapper.h compressor.h
+
++xz_wrapper_extended.o: xz_wrapper_extended.c squashfs_fs.h xz_wrapper.h compressor.h
++
+ unsquashfs: $(UNSQUASHFS_OBJS)
+ $(CC) $(LDFLAGS) $(EXTRA_LDFLAGS) $(UNSQUASHFS_OBJS) $(LIBS) -o $@
+ ln -sf unsquashfs sqfscat
+--- a/squashfs-tools/xz_wrapper.c
++++ b/squashfs-tools/xz_wrapper.c
+@@ -44,10 +44,7 @@ static struct bcj bcj[] = {
+ static int filter_count = 1;
+ static int dictionary_size = 0;
+ static float dictionary_percent = 0;
+-static int preset = LZMA_PRESET_DEFAULT;
+-static int lc = -1;
+-static int lp = -1;
+-static int pb = -1;
++
+
+ /*
+ * This function is called by the options parsing code in mksquashfs.c
+@@ -56,11 +53,6 @@ static int pb = -1;
+ * Two specific options are supported:
+ * -Xbcj
+ * -Xdict-size
+- * -Xpreset
+- * -Xe
+- * -Xlc
+- * -Xlp
+- * -Xpb
+ *
+ * This function returns:
+ * >=0 (number of additional args parsed) on success
+@@ -149,85 +141,6 @@ static int xz_options(char *argv[], int
+ }
+
+ return 1;
+- } else if(strcmp(argv[0], "-Xpreset") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xpreset missing preset-level "
+- "(valid value 0-9)\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < 0 || (int) val & ~LZMA_PRESET_LEVEL_MASK) {
+- fprintf(stderr, "xz: -Xpreset can't be "
+- "negative or more than the max preset\n");
+- goto failed;
+- }
+-
+- preset &= ~LZMA_PRESET_LEVEL_MASK;
+- preset |= (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xe") == 0) {
+- preset |= LZMA_PRESET_EXTREME;
+-
+- return 0;
+- } else if(strcmp(argv[0], "-Xlc") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xlc missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
+- fprintf(stderr, "xz: -Xlc invalid value\n");
+- goto failed;
+- }
+-
+- lc = (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xlp") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xlp missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
+- fprintf(stderr, "xz: -Xlp invalid value\n");
+- goto failed;
+- }
+-
+- lp = (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xpb") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xpb missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_PB_MIN || (int) val > LZMA_PB_MAX) {
+- fprintf(stderr, "xz: -Xpb invalid value\n");
+- goto failed;
+- }
+-
+- pb = (int) val;
+-
+- return 1;
+ }
+
+ return -1;
+@@ -533,20 +446,11 @@ static int xz_compress(void *strm, void
+ for(i = 0; i < stream->filters; i++) {
+ struct filter *filter = &stream->filter[i];
+
+- if(lzma_lzma_preset(&stream->opt, preset))
++ if(lzma_lzma_preset(&stream->opt, LZMA_PRESET_DEFAULT))
+ goto failed;
+
+ stream->opt.dict_size = stream->dictionary_size;
+
+- if (lc >= 0)
+- stream->opt.lc = lc;
+-
+- if (lp >= 0)
+- stream->opt.lp = lp;
+-
+- if (pb >= 0)
+- stream->opt.pb = pb;
+-
+ filter->length = 0;
+ res = lzma_stream_buffer_encode(filter->filter,
+ LZMA_CHECK_CRC32, NULL, src, size, filter->buffer,
+@@ -617,28 +521,13 @@ static void xz_usage(FILE *stream)
+ fprintf(stream, " header as either 2^n or as 2^n+2^(n+1).\n\t\t");
+ fprintf(stream, "Example dict-sizes are 75%%, 50%%, 37.5%%, 25%%, or");
+ fprintf(stream, " 32K, 16K, 8K\n\t\tetc.\n");
+- fprintf(stream, "\t -Xpreset <preset-level>\n");
+- fprintf(stream, "\t\tUse <preset-value> as the custom preset to use");
+- fprintf(stream, " on compress.\n\t\t<preset-level> should be 0 .. 9");
+- fprintf(stream, " (default 6)\n");
+- fprintf(stream, "\t -Xe\n");
+- fprintf(stream, "\t\tEnable additional compression settings by passing");
+- fprintf(stream, " the EXTREME\n\t\tflag to the compression flags.\n");
+- fprintf(stream, "\t -Xlc <value>\n");
+- fprintf(stream, "\t -Xlp <value>\n");
+- fprintf(stream, "\t -Xpb <value>\n");
+ }
+
+
+ static int option_args(char *option)
+ {
+ if(strcmp(option, "-Xbcj") == 0 ||
+- strcmp(option, "-Xdict-size") == 0 ||
+- strcmp(option, "-Xpreset") == 0 ||
+- strcmp(option, "-Xe") == 0 ||
+- strcmp(option, "-Xlc") == 0 ||
+- strcmp(option, "-Xlp") == 0 ||
+- strcmp(option, "-Xpb") == 0)
++ strcmp(option, "-Xdict-size") == 0)
+ return 1;
+
+ return 0;
+--- /dev/null
++++ b/squashfs-tools/xz_wrapper_extended.c
+@@ -0,0 +1,664 @@
++/*
++ * Copyright (c) 2010, 2011, 2012, 2013, 2021, 2022
++ * Phillip Lougher <phillip@squashfs.org.uk>
++ *
++ * 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 2,
++ * 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, write to the Free Software
++ * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
++ *
++ * xz_wrapper_extended.c
++ *
++ * Support for XZ (LZMA2) compression using XZ Utils liblzma
++ * http://tukaani.org/xz/
++ *
++ * This file supports OpenWrt extended XZ compression options.
++ */
++
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++#include <lzma.h>
++
++#include "squashfs_fs.h"
++#include "xz_wrapper.h"
++#include "compressor.h"
++
++static struct bcj bcj[] = {
++ { "x86", LZMA_FILTER_X86, 0 },
++ { "powerpc", LZMA_FILTER_POWERPC, 0 },
++ { "ia64", LZMA_FILTER_IA64, 0 },
++ { "arm", LZMA_FILTER_ARM, 0 },
++ { "armthumb", LZMA_FILTER_ARMTHUMB, 0 },
++ { "sparc", LZMA_FILTER_SPARC, 0 },
++ { NULL, LZMA_VLI_UNKNOWN, 0 }
++};
++
++static int filter_count = 1;
++static int dictionary_size = 0;
++static float dictionary_percent = 0;
++static int preset = LZMA_PRESET_DEFAULT;
++static int lc = -1;
++static int lp = -1;
++static int pb = -1;
++
++/*
++ * This function is called by the options parsing code in mksquashfs.c
++ * to parse any -X compressor option.
++ *
++ * Two specific options are supported:
++ * -Xbcj
++ * -Xdict-size
++ * -Xpreset
++ * -Xe
++ * -Xlc
++ * -Xlp
++ * -Xpb
++ *
++ * This function returns:
++ * >=0 (number of additional args parsed) on success
++ * -1 if the option was unrecognised, or
++ * -2 if the option was recognised, but otherwise bad in
++ * some way (e.g. invalid parameter)
++ *
++ * Note: this function sets internal compressor state, but does not
++ * pass back the results of the parsing other than success/failure.
++ * The xz_dump_options() function is called later to get the options in
++ * a format suitable for writing to the filesystem.
++ */
++static int xz_options(char *argv[], int argc)
++{
++ int i;
++ char *name;
++
++ if(strcmp(argv[0], "-Xbcj") == 0) {
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xbcj missing filter\n");
++ goto failed;
++ }
++
++ name = argv[1];
++ while(name[0] != '\0') {
++ for(i = 0; bcj[i].name; i++) {
++ int n = strlen(bcj[i].name);
++ if((strncmp(name, bcj[i].name, n) == 0) &&
++ (name[n] == '\0' ||
++ name[n] == ',')) {
++ if(bcj[i].selected == 0) {
++ bcj[i].selected = 1;
++ filter_count++;
++ }
++ name += name[n] == ',' ? n + 1 : n;
++ break;
++ }
++ }
++ if(bcj[i].name == NULL) {
++ fprintf(stderr, "xz: -Xbcj unrecognised "
++ "filter\n");
++ goto failed;
++ }
++ }
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xdict-size") == 0) {
++ char *b;
++ float size;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xdict-size missing dict-size\n");
++ goto failed;
++ }
++
++ size = strtof(argv[1], &b);
++ if(*b == '%') {
++ if(size <= 0 || size > 100) {
++ fprintf(stderr, "xz: -Xdict-size percentage "
++ "should be 0 < dict-size <= 100\n");
++ goto failed;
++ }
++
++ dictionary_percent = size;
++ dictionary_size = 0;
++ } else {
++ if((float) ((int) size) != size) {
++ fprintf(stderr, "xz: -Xdict-size can't be "
++ "fractional unless a percentage of the"
++ " block size\n");
++ goto failed;
++ }
++
++ dictionary_percent = 0;
++ dictionary_size = (int) size;
++
++ if(*b == 'k' || *b == 'K')
++ dictionary_size *= 1024;
++ else if(*b == 'm' || *b == 'M')
++ dictionary_size *= 1024 * 1024;
++ else if(*b != '\0') {
++ fprintf(stderr, "xz: -Xdict-size invalid "
++ "dict-size\n");
++ goto failed;
++ }
++ }
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xpreset") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xpreset missing preset-level "
++ "(valid value 0-9)\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < 0 || (int) val & ~LZMA_PRESET_LEVEL_MASK) {
++ fprintf(stderr, "xz: -Xpreset can't be "
++ "negative or more than the max preset\n");
++ goto failed;
++ }
++
++ preset &= ~LZMA_PRESET_LEVEL_MASK;
++ preset |= (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xe") == 0) {
++ preset |= LZMA_PRESET_EXTREME;
++
++ return 0;
++ } else if(strcmp(argv[0], "-Xlc") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xlc missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
++ fprintf(stderr, "xz: -Xlc invalid value\n");
++ goto failed;
++ }
++
++ lc = (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xlp") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xlp missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
++ fprintf(stderr, "xz: -Xlp invalid value\n");
++ goto failed;
++ }
++
++ lp = (int) val;
++
++ return 1;
++ } else if(strcmp(argv[0], "-Xpb") == 0) {
++ char *b;
++ long val;
++
++ if(argc < 2) {
++ fprintf(stderr, "xz: -Xpb missing value\n");
++ goto failed;
++ }
++
++ val = strtol(argv[1], &b, 10);
++ if (*b != '\0' || (int) val < LZMA_PB_MIN || (int) val > LZMA_PB_MAX) {
++ fprintf(stderr, "xz: -Xpb invalid value\n");
++ goto failed;
++ }
++
++ pb = (int) val;
++
++ return 1;
++ }
++
++ return -1;
++
++failed:
++ return -2;
++}
++
++
++/*
++ * This function is called after all options have been parsed.
++ * It is used to do post-processing on the compressor options using
++ * values that were not expected to be known at option parse time.
++ *
++ * In this case block_size may not be known until after -Xdict-size has
++ * been processed (in the case where -b is specified after -Xdict-size)
++ *
++ * This function returns 0 on successful post processing, or
++ * -1 on error
++ */
++static int xz_options_post(int block_size)
++{
++ /*
++ * if -Xdict-size has been specified use this to compute the datablock
++ * dictionary size
++ */
++ if(dictionary_size || dictionary_percent) {
++ int n;
++
++ if(dictionary_size) {
++ if(dictionary_size > block_size) {
++ fprintf(stderr, "xz: -Xdict-size is larger than"
++ " block_size\n");
++ goto failed;
++ }
++ } else
++ dictionary_size = block_size * dictionary_percent / 100;
++
++ if(dictionary_size < 8192) {
++ fprintf(stderr, "xz: -Xdict-size should be 8192 bytes "
++ "or larger\n");
++ goto failed;
++ }
++
++ /*
++ * dictionary_size must be storable in xz header as either
++ * 2^n or as 2^n+2^(n+1)
++ */
++ n = ffs(dictionary_size) - 1;
++ if(dictionary_size != (1 << n) &&
++ dictionary_size != ((1 << n) + (1 << (n + 1)))) {
++ fprintf(stderr, "xz: -Xdict-size is an unsupported "
++ "value, dict-size must be storable in xz "
++ "header\n");
++ fprintf(stderr, "as either 2^n or as 2^n+2^(n+1). "
++ "Example dict-sizes are 75%%, 50%%, 37.5%%, "
++ "25%%,\n");
++ fprintf(stderr, "or 32K, 16K, 8K etc.\n");
++ goto failed;
++ }
++
++ } else
++ /* No -Xdict-size specified, use defaults */
++ dictionary_size = block_size;
++
++ return 0;
++
++failed:
++ return -1;
++}
++
++
++/*
++ * This function is called by mksquashfs to dump the parsed
++ * compressor options in a format suitable for writing to the
++ * compressor options field in the filesystem (stored immediately
++ * after the superblock).
++ *
++ * This function returns a pointer to the compression options structure
++ * to be stored (and the size), or NULL if there are no compression
++ * options
++ */
++static void *xz_dump_options(int block_size, int *size)
++{
++ static struct comp_opts comp_opts;
++ int flags = 0, i;
++
++ /*
++ * don't store compressor specific options in file system if the
++ * default options are being used - no compressor options in the
++ * file system means the default options are always assumed
++ *
++ * Defaults are:
++ * metadata dictionary size: SQUASHFS_METADATA_SIZE
++ * datablock dictionary size: block_size
++ * 1 filter
++ */
++ if(dictionary_size == block_size && filter_count == 1)
++ return NULL;
++
++ for(i = 0; bcj[i].name; i++)
++ flags |= bcj[i].selected << i;
++
++ comp_opts.dictionary_size = dictionary_size;
++ comp_opts.flags = flags;
++
++ SQUASHFS_INSWAP_COMP_OPTS(&comp_opts);
++
++ *size = sizeof(comp_opts);
++ return &comp_opts;
++}
++
++
++/*
++ * This function is a helper specifically for the append mode of
++ * mksquashfs. Its purpose is to set the internal compressor state
++ * to the stored compressor options in the passed compressor options
++ * structure.
++ *
++ * In effect this function sets up the compressor options
++ * to the same state they were when the filesystem was originally
++ * generated, this is to ensure on appending, the compressor uses
++ * the same compression options that were used to generate the
++ * original filesystem.
++ *
++ * Note, even if there are no compressor options, this function is still
++ * called with an empty compressor structure (size == 0), to explicitly
++ * set the default options, this is to ensure any user supplied
++ * -X options on the appending mksquashfs command line are over-ridden
++ *
++ * This function returns 0 on sucessful extraction of options, and
++ * -1 on error
++ */
++static int xz_extract_options(int block_size, void *buffer, int size)
++{
++ struct comp_opts *comp_opts = buffer;
++ int flags, i, n;
++
++ if(size == 0) {
++ /* set defaults */
++ dictionary_size = block_size;
++ flags = 0;
++ } else {
++ /* check passed comp opts struct is of the correct length */
++ if(size != sizeof(struct comp_opts))
++ goto failed;
++
++ SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
++
++ dictionary_size = comp_opts->dictionary_size;
++ flags = comp_opts->flags;
++
++ /*
++ * check that the dictionary size seems correct - the dictionary
++ * size should 2^n or 2^n+2^(n+1)
++ */
++ n = ffs(dictionary_size) - 1;
++ if(dictionary_size != (1 << n) &&
++ dictionary_size != ((1 << n) + (1 << (n + 1))))
++ goto failed;
++ }
++
++ filter_count = 1;
++ for(i = 0; bcj[i].name; i++) {
++ if((flags >> i) & 1) {
++ bcj[i].selected = 1;
++ filter_count ++;
++ } else
++ bcj[i].selected = 0;
++ }
++
++ return 0;
++
++failed:
++ fprintf(stderr, "xz: error reading stored compressor options from "
++ "filesystem!\n");
++
++ return -1;
++}
++
++
++static void xz_display_options(void *buffer, int size)
++{
++ struct comp_opts *comp_opts = buffer;
++ int dictionary_size, flags, printed;
++ int i, n;
++
++ /* check passed comp opts struct is of the correct length */
++ if(size != sizeof(struct comp_opts))
++ goto failed;
++
++ SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
++
++ dictionary_size = comp_opts->dictionary_size;
++ flags = comp_opts->flags;
++
++ /*
++ * check that the dictionary size seems correct - the dictionary
++ * size should 2^n or 2^n+2^(n+1)
++ */
++ n = ffs(dictionary_size) - 1;
++ if(dictionary_size != (1 << n) &&
++ dictionary_size != ((1 << n) + (1 << (n + 1))))
++ goto failed;
++
++ printf("\tDictionary size %d\n", dictionary_size);
++
++ printed = 0;
++ for(i = 0; bcj[i].name; i++) {
++ if((flags >> i) & 1) {
++ if(printed)
++ printf(", ");
++ else
++ printf("\tFilters selected: ");
++ printf("%s", bcj[i].name);
++ printed = 1;
++ }
++ }
++
++ if(!printed)
++ printf("\tNo filters specified\n");
++ else
++ printf("\n");
++
++ return;
++
++failed:
++ fprintf(stderr, "xz: error reading stored compressor options from "
++ "filesystem!\n");
++}
++
++
++/*
++ * This function is called by mksquashfs to initialise the
++ * compressor, before compress() is called.
++ *
++ * This function returns 0 on success, and
++ * -1 on error
++ */
++static int xz_init(void **strm, int block_size, int datablock)
++{
++ int i, j, filters = datablock ? filter_count : 1;
++ struct filter *filter = malloc(filters * sizeof(struct filter));
++ struct xz_stream *stream;
++
++ if(filter == NULL)
++ goto failed;
++
++ stream = *strm = malloc(sizeof(struct xz_stream));
++ if(stream == NULL)
++ goto failed2;
++
++ stream->filter = filter;
++ stream->filters = filters;
++
++ memset(filter, 0, filters * sizeof(struct filter));
++
++ stream->dictionary_size = datablock ? dictionary_size :
++ SQUASHFS_METADATA_SIZE;
++
++ filter[0].filter[0].id = LZMA_FILTER_LZMA2;
++ filter[0].filter[0].options = &stream->opt;
++ filter[0].filter[1].id = LZMA_VLI_UNKNOWN;
++
++ for(i = 0, j = 1; datablock && bcj[i].name; i++) {
++ if(bcj[i].selected) {
++ filter[j].buffer = malloc(block_size);
++ if(filter[j].buffer == NULL)
++ goto failed3;
++ filter[j].filter[0].id = bcj[i].id;
++ filter[j].filter[1].id = LZMA_FILTER_LZMA2;
++ filter[j].filter[1].options = &stream->opt;
++ filter[j].filter[2].id = LZMA_VLI_UNKNOWN;
++ j++;
++ }
++ }
++
++ return 0;
++
++failed3:
++ for(i = 1; i < filters; i++)
++ free(filter[i].buffer);
++ free(stream);
++
++failed2:
++ free(filter);
++
++failed:
++ return -1;
++}
++
++
++static int xz_compress(void *strm, void *dest, void *src, int size,
++ int block_size, int *error)
++{
++ int i;
++ lzma_ret res = 0;
++ struct xz_stream *stream = strm;
++ struct filter *selected = NULL;
++
++ stream->filter[0].buffer = dest;
++
++ for(i = 0; i < stream->filters; i++) {
++ struct filter *filter = &stream->filter[i];
++
++ if(lzma_lzma_preset(&stream->opt, preset))
++ goto failed;
++
++ stream->opt.dict_size = stream->dictionary_size;
++
++ if (lc >= 0)
++ stream->opt.lc = lc;
++
++ if (lp >= 0)
++ stream->opt.lp = lp;
++
++ if (pb >= 0)
++ stream->opt.pb = pb;
++
++ filter->length = 0;
++ res = lzma_stream_buffer_encode(filter->filter,
++ LZMA_CHECK_CRC32, NULL, src, size, filter->buffer,
++ &filter->length, block_size);
++
++ if(res == LZMA_OK) {
++ if(!selected || selected->length > filter->length)
++ selected = filter;
++ } else if(res != LZMA_BUF_ERROR)
++ goto failed;
++ }
++
++ if(!selected)
++ /*
++ * Output buffer overflow. Return out of buffer space
++ */
++ return 0;
++
++ if(selected->buffer != dest)
++ memcpy(dest, selected->buffer, selected->length);
++
++ return (int) selected->length;
++
++failed:
++ /*
++ * All other errors return failure, with the compressor
++ * specific error code in *error
++ */
++ *error = res;
++ return -1;
++}
++
++
++static int xz_uncompress(void *dest, void *src, int size, int outsize,
++ int *error)
++{
++ size_t src_pos = 0;
++ size_t dest_pos = 0;
++ uint64_t memlimit = MEMLIMIT;
++
++ lzma_ret res = lzma_stream_buffer_decode(&memlimit, 0, NULL,
++ src, &src_pos, size, dest, &dest_pos, outsize);
++
++ if(res == LZMA_OK && size == (int) src_pos)
++ return (int) dest_pos;
++ else {
++ *error = res;
++ return -1;
++ }
++}
++
++
++static void xz_usage(FILE *stream)
++{
++ fprintf(stream, "\t -Xbcj filter1,filter2,...,filterN\n");
++ fprintf(stream, "\t\tCompress using filter1,filter2,...,filterN in");
++ fprintf(stream, " turn\n\t\t(in addition to no filter), and choose");
++ fprintf(stream, " the best compression.\n");
++ fprintf(stream, "\t\tAvailable filters: x86, arm, armthumb,");
++ fprintf(stream, " powerpc, sparc, ia64\n");
++ fprintf(stream, "\t -Xdict-size <dict-size>\n");
++ fprintf(stream, "\t\tUse <dict-size> as the XZ dictionary size. The");
++ fprintf(stream, " dictionary size\n\t\tcan be specified as a");
++ fprintf(stream, " percentage of the block size, or as an\n\t\t");
++ fprintf(stream, "absolute value. The dictionary size must be less");
++ fprintf(stream, " than or equal\n\t\tto the block size and 8192 bytes");
++ fprintf(stream, " or larger. It must also be\n\t\tstorable in the xz");
++ fprintf(stream, " header as either 2^n or as 2^n+2^(n+1).\n\t\t");
++ fprintf(stream, "Example dict-sizes are 75%%, 50%%, 37.5%%, 25%%, or");
++ fprintf(stream, " 32K, 16K, 8K\n\t\tetc.\n");
++ fprintf(stream, "\t -Xpreset <preset-level>\n");
++ fprintf(stream, "\t\tUse <preset-value> as the custom preset to use");
++ fprintf(stream, " on compress.\n\t\t<preset-level> should be 0 .. 9");
++ fprintf(stream, " (default 6)\n");
++ fprintf(stream, "\t -Xe\n");
++ fprintf(stream, "\t\tEnable additional compression settings by passing");
++ fprintf(stream, " the EXTREME\n\t\tflag to the compression flags.\n");
++ fprintf(stream, "\t -Xlc <value>\n");
++ fprintf(stream, "\t -Xlp <value>\n");
++ fprintf(stream, "\t -Xpb <value>\n");
++}
++
++
++static int option_args(char *option)
++{
++ if(strcmp(option, "-Xbcj") == 0 ||
++ strcmp(option, "-Xdict-size") == 0 ||
++ strcmp(option, "-Xpreset") == 0 ||
++ strcmp(option, "-Xe") == 0 ||
++ strcmp(option, "-Xlc") == 0 ||
++ strcmp(option, "-Xlp") == 0 ||
++ strcmp(option, "-Xpb") == 0)
++ return 1;
++
++ return 0;
++}
++
++
++struct compressor xz_comp_ops = {
++ .init = xz_init,
++ .compress = xz_compress,
++ .uncompress = xz_uncompress,
++ .options = xz_options,
++ .options_post = xz_options_post,
++ .dump_options = xz_dump_options,
++ .extract_options = xz_extract_options,
++ .display_options = xz_display_options,
++ .usage = xz_usage,
++ .option_args = option_args,
++ .id = XZ_COMPRESSION,
++ .name = "xz",
++ .supported = 1
++};
diff --git a/tools/squashfs4/patches/110-allow_static_liblzma.patch b/tools/squashfs4/patches/110-allow_static_liblzma.patch
new file mode 100644
index 0000000..4e5cc07
--- /dev/null
+++ b/tools/squashfs4/patches/110-allow_static_liblzma.patch
@@ -0,0 +1,30 @@
+--- a/squashfs-tools/Makefile
++++ b/squashfs-tools/Makefile
+@@ -247,7 +247,6 @@ ifeq ($(LZMA_XZ_SUPPORT),1)
+ CFLAGS += -DLZMA_SUPPORT
+ MKSQUASHFS_OBJS += lzma_xz_wrapper.o
+ UNSQUASHFS_OBJS += lzma_xz_wrapper.o
+-LIBS += -llzma
+ COMPRESSORS += lzma
+ endif
+
+@@ -260,10 +259,18 @@ else
+ MKSQUASHFS_OBJS += xz_wrapper.o
+ UNSQUASHFS_OBJS += xz_wrapper.o
+ endif
+-LIBS += -llzma
+ COMPRESSORS += xz
+ endif
+
++ifneq ($(LZMA_XZ_SUPPORT)$(XZ_SUPPORT),)
++ifneq ($(LZMA_LIB),)
++MKSQUASHFS_OBJS += $(LZMA_LIB)
++UNSQUASHFS_OBJS += $(LZMA_LIB)
++else
++LIBS += -llzma
++endif
++endif
++
+ ifeq ($(LZO_SUPPORT),1)
+ CFLAGS += -DLZO_SUPPORT
+ MKSQUASHFS_OBJS += lzo_wrapper.o
diff --git a/tools/squashfs4/patches/160-expose_lzma_xz_options.patch b/tools/squashfs4/patches/160-expose_lzma_xz_options.patch
new file mode 100644
index 0000000..b7fe8d7
--- /dev/null
+++ b/tools/squashfs4/patches/160-expose_lzma_xz_options.patch
@@ -0,0 +1,920 @@
+--- /dev/null
++++ b/squashfs-tools/lzma_xz_options.h
+@@ -0,0 +1,115 @@
++#ifndef LZMA_XZ_OPTIONS_H
++#define LZMA_XZ_OPTIONS_H
++/*
++ * Copyright (c) 2011
++ * Jonas Gorski <jonas.gorski@gmail.com>
++ *
++ * 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 2,
++ * 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, write to the Free Software
++ * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
++ *
++ * lzma_options.h
++ */
++
++#include <stdint.h>
++
++#ifndef linux
++#ifdef __FreeBSD__
++#include <machine/endian.h>
++#endif
++#define __BYTE_ORDER BYTE_ORDER
++#define __BIG_ENDIAN BIG_ENDIAN
++#define __LITTLE_ENDIAN LITTLE_ENDIAN
++#else
++#include <endian.h>
++#endif
++
++
++
++struct lzma_opts {
++ uint32_t dict_size;
++ uint32_t flags;
++#define LZMA_OPT_FLT_MASK 0xffff
++#define LZMA_OPT_PRE_OFF 16
++#define LZMA_OPT_PRE_MASK (0xf << LZMA_OPT_PRE_OFF)
++#define LZMA_OPT_EXTREME 20
++ uint16_t bit_opts;
++#define LZMA_OPT_LC_OFF 0
++#define LZMA_OPT_LC_MASK (0x7 << LZMA_OPT_LC_OFF)
++#define LZMA_OPT_LP_OFF 3
++#define LZMA_OPT_LP_MASK (0x7 << LZMA_OPT_LP_OFF)
++#define LZMA_OPT_PB_OFF 6
++#define LZMA_OPT_PB_MASK (0x7 << LZMA_OPT_PB_OFF)
++ uint16_t fb;
++};
++
++#if __BYTE_ORDER == __BIG_ENDIAN
++extern unsigned int inswap_le32(unsigned int);
++
++#define SQUASHFS_INSWAP_LZMA_COMP_OPTS(s) { \
++ (s)->flags = inswap_le32((s)->flags); \
++ (s)->bit_opts = inswap_le16((s)->bit_opts); \
++ (s)->fb = inswap_le16((s)->fb); \
++ (s)->dict_size = inswap_le32((s)->dict_size); \
++}
++#else
++#define SQUASHFS_INSWAP_LZMA_COMP_OPTS(s)
++#endif
++
++#define MEMLIMIT (32 * 1024 * 1024)
++
++#define LZMA_OPT_LC_MIN 0
++#define LZMA_OPT_LC_MAX 4
++#define LZMA_OPT_LC_DEFAULT 3
++
++#define LZMA_OPT_LP_MIN 0
++#define LZMA_OPT_LP_MAX 4
++#define LZMA_OPT_LP_DEFAULT 0
++
++#define LZMA_OPT_PB_MIN 0
++#define LZMA_OPT_PB_MAX 4
++#define LZMA_OPT_PB_DEFAULT 2
++
++#define LZMA_OPT_FB_MIN 5
++#define LZMA_OPT_FB_MAX 273
++#define LZMA_OPT_FB_DEFAULT 64
++
++enum {
++ LZMA_OPT_LZMA = 1,
++ LZMA_OPT_XZ
++};
++
++struct lzma_xz_options {
++ int preset;
++ int extreme;
++ int lc;
++ int lp;
++ int pb;
++ int fb;
++ int dict_size;
++ int flags;
++};
++
++struct lzma_xz_options *lzma_xz_get_options(void);
++
++int lzma_xz_options(char *argv[], int argc, int lzmaver);
++
++int lzma_xz_options_post(int block_size, int lzmaver);
++
++void *lzma_xz_dump_options(int block_size, int *size, int flags);
++
++int lzma_xz_extract_options(int block_size, void *buffer, int size, int lzmaver);
++
++void lzma_xz_usage(int lzmaver);
++
++#endif
+--- /dev/null
++++ b/squashfs-tools/lzma_xz_options.c
+@@ -0,0 +1,365 @@
++/*
++ * Copyright (c) 2011
++ * Jonas Gorski <jonas.gorski@gmail.com>
++ *
++ * 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 2,
++ * 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, write to the Free Software
++ * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
++ *
++ * lzma_options.c
++ *
++ * Common options for LZMA1 and 2 compressors. Based on xz_wrapper.c
++ */
++
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++#include <lzma.h>
++
++#include "lzma_xz_options.h"
++
++static const char const *lzmaver_str[] = { "", "lzma", "xz" };
++
++static struct lzma_xz_options options = {
++ .flags = 0,
++ .preset = 6,
++ .extreme = 0,
++ .lc = LZMA_OPT_LC_DEFAULT,
++ .lp = LZMA_OPT_LP_DEFAULT,
++ .pb = LZMA_OPT_PB_DEFAULT,
++ .fb = LZMA_OPT_FB_DEFAULT,
++ .dict_size = 0,
++};
++
++static float lzma_dict_percent = 0;
++
++struct lzma_xz_options *lzma_xz_get_options(void)
++{
++ return &options;
++}
++
++
++int lzma_xz_options(char *argv[], int argc, int lzmaver)
++{
++ const char *comp_name = lzmaver_str[lzmaver];
++
++ if(strcmp(argv[0], "-Xpreset") == 0) {
++ int preset;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xpreset missing preset\n", comp_name);
++ goto failed;
++ }
++
++ preset = atoi(argv[1]);
++
++ if (preset < 0 || preset > 9) {
++ fprintf(stderr, "%s: -Xpreset invalid value\n", comp_name);
++ goto failed;
++ }
++ options.preset = preset;
++ return 1;
++ } else if(strcmp(argv[0], "-Xe") == 0) {
++ options.extreme = 1;
++ return 0;
++ } else if(strcmp(argv[0], "-Xlc") == 0) {
++ int lc;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xlc missing lc\n", comp_name);
++ goto failed;
++ }
++
++ lc = atoi(argv[1]);
++
++ if (lc < LZMA_OPT_LC_MIN || lc > LZMA_OPT_LC_MAX) {
++ fprintf(stderr, "%s: -Xlc invalid value\n", comp_name);
++ goto failed;
++ }
++ options.lc = lc;
++ return 1;
++ } else if(strcmp(argv[0], "-Xlp") == 0) {
++ int lp;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xlp missing lp\n", comp_name);
++ goto failed;
++ }
++
++ lp = atoi(argv[1]);
++
++ if (lp < LZMA_OPT_LP_MIN || lp > LZMA_OPT_LP_MAX) {
++ fprintf(stderr, "%s: -Xlp invalid value\n", comp_name);
++ goto failed;
++ }
++ options.lp = lp;
++ return 1;
++ } else if(strcmp(argv[0], "-Xpb") == 0) {
++ int pb;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xpb missing pb\n", comp_name);
++ goto failed;
++ }
++
++ pb = atoi(argv[1]);
++
++ if (pb < LZMA_OPT_PB_MIN || pb > LZMA_OPT_PB_MAX) {
++ fprintf(stderr, "%s: -Xbp invalid value\n", comp_name);
++ goto failed;
++ }
++ options.pb = pb;
++ return 1;
++ } else if(strcmp(argv[0], "-Xfb") == 0) {
++ int fb;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xfb missing fb\n", comp_name);
++ goto failed;
++ }
++
++ fb = atoi(argv[1]);
++
++ if (fb < LZMA_OPT_FB_MIN || fb > LZMA_OPT_FB_MAX) {
++ fprintf(stderr, "%s: -Xfb invalid value\n", comp_name);
++ goto failed;
++ }
++ options.fb = fb;
++ return 1;
++ } else if(strcmp(argv[0], "-Xdict-size") == 0) {
++ char *b;
++ float size;
++
++ if(argc < 2) {
++ fprintf(stderr, "%s: -Xdict-size missing dict-size\n", comp_name);
++ goto failed;
++ }
++
++ size = strtof(argv[1], &b);
++ if(*b == '%') {
++ if(size <= 0 || size > 100) {
++ fprintf(stderr, "%s: -Xdict-size percentage "
++ "should be 0 < dict-size <= 100\n", comp_name);
++ goto failed;
++ }
++
++ lzma_dict_percent = size;
++ options.dict_size = 0;
++ } else {
++ if((float) ((int) size) != size) {
++ fprintf(stderr, "%s: -Xdict-size can't be "
++ "fractional unless a percentage of the"
++ " block size\n", comp_name);
++ goto failed;
++ }
++
++ lzma_dict_percent = 0;
++ options.dict_size = (int) size;
++
++ if(*b == 'k' || *b == 'K')
++ options.dict_size *= 1024;
++ else if(*b == 'm' || *b == 'M')
++ options.dict_size *= 1024 * 1024;
++ else if(*b != '\0') {
++ fprintf(stderr, "%s: -Xdict-size invalid "
++ "dict-size\n", comp_name);
++ goto failed;
++ }
++ }
++
++ return 1;
++ }
++
++ return -1;
++
++failed:
++ return -2;
++
++}
++
++int lzma_xz_options_post(int block_size, int lzmaver)
++{
++ const char *comp_name = lzmaver_str[lzmaver];
++ /*
++ * if -Xdict-size has been specified use this to compute the datablock
++ * dictionary size
++ */
++ if(options.dict_size || lzma_dict_percent) {
++ int dict_size_min = (lzmaver == 1 ? 4096 : 8192);
++ int n;
++
++ if(options.dict_size) {
++ if(options.dict_size > block_size) {
++ fprintf(stderr, "%s: -Xdict-size is larger than"
++ " block_size\n", comp_name);
++ goto failed;
++ }
++ } else
++ options.dict_size = block_size * lzma_dict_percent / 100;
++
++ if(options.dict_size < dict_size_min) {
++ fprintf(stderr, "%s: -Xdict-size should be %i bytes "
++ "or larger\n", comp_name, dict_size_min);
++ goto failed;
++ }
++
++ /*
++ * dictionary_size must be storable in xz header as either
++ * 2^n or as 2^n+2^(n+1)
++ */
++ n = ffs(options.dict_size) - 1;
++ if(options.dict_size != (1 << n) &&
++ options.dict_size != ((1 << n) + (1 << (n + 1)))) {
++ fprintf(stderr, "%s: -Xdict-size is an unsupported "
++ "value, dict-size must be storable in %s "
++ "header\n", comp_name, comp_name);
++ fprintf(stderr, "as either 2^n or as 2^n+2^(n+1). "
++ "Example dict-sizes are 75%%, 50%%, 37.5%%, "
++ "25%%,\n");
++ fprintf(stderr, "or 32K, 16K, 8K etc.\n");
++ goto failed;
++ }
++
++ } else
++ /* No -Xdict-size specified, use defaults */
++ options.dict_size = block_size;
++
++ return 0;
++
++failed:
++ return -1;
++}
++
++static struct lzma_opts lzma_comp_opts;
++
++void *lzma_xz_dump_options(int block_size, int *size, int flags)
++{
++ /* No need to store default options */
++ if (options.preset == 6 &&
++ options.extreme == 0 &&
++ options.lc == LZMA_OPT_LC_DEFAULT &&
++ options.lp == LZMA_OPT_LC_DEFAULT &&
++ options.pb == LZMA_OPT_PB_DEFAULT &&
++ options.fb == 0 &&
++ options.dict_size == block_size &&
++ flags == 0)
++ return NULL;
++
++ *size = sizeof(struct lzma_opts);
++
++ lzma_comp_opts.flags |= flags;
++
++ if (options.extreme)
++ lzma_comp_opts.flags |= LZMA_OPT_EXTREME;
++
++ lzma_comp_opts.flags |= ((options.preset << LZMA_OPT_PRE_OFF) & LZMA_OPT_PRE_MASK);
++
++ lzma_comp_opts.bit_opts =
++ ((options.lc << LZMA_OPT_LC_OFF) & LZMA_OPT_LC_MASK) |
++ ((options.lp << LZMA_OPT_LP_OFF) & LZMA_OPT_LP_MASK) |
++ ((options.pb << LZMA_OPT_PB_OFF) & LZMA_OPT_PB_MASK);
++ lzma_comp_opts.fb = options.fb;
++ lzma_comp_opts.dict_size = options.dict_size;
++
++ SQUASHFS_INSWAP_LZMA_COMP_OPTS(&lzma_comp_opts);
++
++ return &lzma_comp_opts;
++}
++
++int lzma_xz_extract_options(int block_size, void *buffer, int size, int lzmaver)
++{
++ if (size == 0) {
++ /* default options */
++ options.preset = 6;
++ options.extreme = 0;
++ options.lc = LZMA_OPT_LC_DEFAULT;
++ options.lp = LZMA_OPT_LC_DEFAULT;
++ options.pb = LZMA_OPT_PB_DEFAULT;
++ options.fb = LZMA_OPT_FB_DEFAULT;
++ options.dict_size = block_size;
++ options.flags = 0;
++ } else {
++ struct lzma_opts *comp_opts = buffer;
++ int n;
++
++ if (size != sizeof(struct lzma_opts))
++ goto failed;
++
++ SQUASHFS_INSWAP_LZMA_COMP_OPTS(comp_opts);
++
++ options.flags = comp_opts->flags & LZMA_OPT_FLT_MASK;
++ options.preset = (comp_opts->flags & LZMA_OPT_PRE_MASK) >> LZMA_OPT_PRE_OFF;
++ options.extreme = !!(comp_opts->flags & LZMA_OPT_EXTREME);
++
++ options.lc = (comp_opts->bit_opts & LZMA_OPT_LC_MASK) >> LZMA_OPT_LC_OFF;
++ options.lp = (comp_opts->bit_opts & LZMA_OPT_LP_MASK) >> LZMA_OPT_LP_OFF;
++ options.pb = (comp_opts->bit_opts & LZMA_OPT_PB_MASK) >> LZMA_OPT_PB_OFF;
++ options.fb = comp_opts->fb;
++ options.dict_size = comp_opts->dict_size;
++
++ /* check that the LZMA bit options are in range */
++ if (options.lc < LZMA_OPT_LC_MIN || options.lc > LZMA_OPT_LC_MAX ||
++ options.lp < LZMA_OPT_LP_MIN || options.lp > LZMA_OPT_LP_MAX ||
++ options.pb < LZMA_OPT_PB_MIN || options.pb > LZMA_OPT_PB_MAX ||
++ options.fb < LZMA_OPT_FB_MIN || options.fb > LZMA_OPT_FB_MAX)
++ goto failed;
++
++ /*
++ * check that the dictionary size seems correct - the dictionary
++ * size should 2^n or 2^n+2^(n+1)
++ */
++ n = ffs(options.dict_size) - 1;
++ if(options.dict_size != (1 << n) &&
++ options.dict_size != ((1 << n) + (1 << (n + 1))))
++ goto failed;
++
++ }
++
++ return 0;
++
++failed:
++ fprintf(stderr, "%s: error reading stored compressor options from "
++ "filesystem!\n", lzmaver_str[lzmaver]);
++ return -1;
++}
++
++void lzma_xz_usage(int lzmaver)
++{
++ fprintf(stderr, "\t -Xpreset <preset>\n");
++ fprintf(stderr, "\t\tcompression preset (0-9, default 6)\n");
++ fprintf(stderr, "\t -Xe\n");
++ fprintf(stderr, "\t\tTry to improve compression ratio by using more ");
++ fprintf(stderr, "CPU time.\n");
++ fprintf(stderr, "\t -Xlc <lc>\n");
++ fprintf(stderr, "\t\tNumber of literal context bits (0-4, default 3)\n");
++ fprintf(stderr, "\t -Xlp <lp>\n");
++ fprintf(stderr, "\t\tNumber of literal position bits (0-4, default 0)\n");
++ fprintf(stderr, "\t -Xpb <pb>\n");
++ fprintf(stderr, "\t\tNumber of position bits (0-4, default 2)\n");
++ fprintf(stderr, "\t -Xnice <nice>\n");
++ fprintf(stderr, "\t\tNice length of a match (5-273, default 64)\n");
++ fprintf(stderr, "\t -Xdict-size <dict-size>\n");
++ fprintf(stderr, "\t\tUse <dict-size> as the %s dictionary size. The",
++ lzmaver == LZMA_OPT_LZMA ? "LZMA" : "XZ");
++ fprintf(stderr, " dictionary size\n\t\tcan be specified as a");
++ fprintf(stderr, " percentage of the block size, or as an\n\t\t");
++ fprintf(stderr, "absolute value. The dictionary size must be less");
++ fprintf(stderr, " than or equal\n\t\tto the block size and %d bytes",
++ lzmaver == LZMA_OPT_LZMA ? 4096 : 8192);
++ fprintf(stderr, " or larger. It must also be\n\t\tstorable in the lzma");
++ fprintf(stderr, " header as either 2^n or as 2^n+2^(n+1).\n\t\t");
++ fprintf(stderr, "Example dict-sizes are 75%%, 50%%, 37.5%%, 25%%, or");
++ fprintf(stderr, " 32K, 16K, 8K\n\t\tetc.\n");
++
++}
+--- a/squashfs-tools/xz_wrapper_extended.c
++++ b/squashfs-tools/xz_wrapper_extended.c
+@@ -32,6 +32,7 @@
+ #include "squashfs_fs.h"
+ #include "xz_wrapper.h"
+ #include "compressor.h"
++#include "lzma_xz_options.h"
+
+ static struct bcj bcj[] = {
+ { "x86", LZMA_FILTER_X86, 0 },
+@@ -44,12 +45,6 @@ static struct bcj bcj[] = {
+ };
+
+ static int filter_count = 1;
+-static int dictionary_size = 0;
+-static float dictionary_percent = 0;
+-static int preset = LZMA_PRESET_DEFAULT;
+-static int lc = -1;
+-static int lp = -1;
+-static int pb = -1;
+
+ /*
+ * This function is called by the options parsing code in mksquashfs.c
+@@ -77,13 +72,13 @@ static int pb = -1;
+ */
+ static int xz_options(char *argv[], int argc)
+ {
+- int i;
+- char *name;
+-
+ if(strcmp(argv[0], "-Xbcj") == 0) {
++ int i;
++ char *name;
++
+ if(argc < 2) {
+ fprintf(stderr, "xz: -Xbcj missing filter\n");
+- goto failed;
++ return -2;
+ }
+
+ name = argv[1];
+@@ -104,138 +99,14 @@ static int xz_options(char *argv[], int argc)
+ if(bcj[i].name == NULL) {
+ fprintf(stderr, "xz: -Xbcj unrecognised "
+ "filter\n");
+- goto failed;
+- }
+- }
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xdict-size") == 0) {
+- char *b;
+- float size;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xdict-size missing dict-size\n");
+- goto failed;
+- }
+-
+- size = strtof(argv[1], &b);
+- if(*b == '%') {
+- if(size <= 0 || size > 100) {
+- fprintf(stderr, "xz: -Xdict-size percentage "
+- "should be 0 < dict-size <= 100\n");
+- goto failed;
+- }
+-
+- dictionary_percent = size;
+- dictionary_size = 0;
+- } else {
+- if((float) ((int) size) != size) {
+- fprintf(stderr, "xz: -Xdict-size can't be "
+- "fractional unless a percentage of the"
+- " block size\n");
+- goto failed;
++ return -2;
+ }
+-
+- dictionary_percent = 0;
+- dictionary_size = (int) size;
+-
+- if(*b == 'k' || *b == 'K')
+- dictionary_size *= 1024;
+- else if(*b == 'm' || *b == 'M')
+- dictionary_size *= 1024 * 1024;
+- else if(*b != '\0') {
+- fprintf(stderr, "xz: -Xdict-size invalid "
+- "dict-size\n");
+- goto failed;
+- }
+- }
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xpreset") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xpreset missing preset-level "
+- "(valid value 0-9)\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < 0 || (int) val & ~LZMA_PRESET_LEVEL_MASK) {
+- fprintf(stderr, "xz: -Xpreset can't be "
+- "negative or more than the max preset\n");
+- goto failed;
+- }
+-
+- preset &= ~LZMA_PRESET_LEVEL_MASK;
+- preset |= (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xe") == 0) {
+- preset |= LZMA_PRESET_EXTREME;
+-
+- return 0;
+- } else if(strcmp(argv[0], "-Xlc") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xlc missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
+- fprintf(stderr, "xz: -Xlc invalid value\n");
+- goto failed;
+- }
+-
+- lc = (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xlp") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xlp missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_LCLP_MIN || (int) val > LZMA_LCLP_MAX) {
+- fprintf(stderr, "xz: -Xlp invalid value\n");
+- goto failed;
+- }
+-
+- lp = (int) val;
+-
+- return 1;
+- } else if(strcmp(argv[0], "-Xpb") == 0) {
+- char *b;
+- long val;
+-
+- if(argc < 2) {
+- fprintf(stderr, "xz: -Xpb missing value\n");
+- goto failed;
+- }
+-
+- val = strtol(argv[1], &b, 10);
+- if (*b != '\0' || (int) val < LZMA_PB_MIN || (int) val > LZMA_PB_MAX) {
+- fprintf(stderr, "xz: -Xpb invalid value\n");
+- goto failed;
+ }
+
+- pb = (int) val;
+-
+ return 1;
++ } else {
++ return lzma_xz_options(argv, argc, LZMA_OPT_XZ);
+ }
+-
+- return -1;
+-
+-failed:
+- return -2;
+ }
+
+
+@@ -252,53 +123,7 @@ failed:
+ */
+ static int xz_options_post(int block_size)
+ {
+- /*
+- * if -Xdict-size has been specified use this to compute the datablock
+- * dictionary size
+- */
+- if(dictionary_size || dictionary_percent) {
+- int n;
+-
+- if(dictionary_size) {
+- if(dictionary_size > block_size) {
+- fprintf(stderr, "xz: -Xdict-size is larger than"
+- " block_size\n");
+- goto failed;
+- }
+- } else
+- dictionary_size = block_size * dictionary_percent / 100;
+-
+- if(dictionary_size < 8192) {
+- fprintf(stderr, "xz: -Xdict-size should be 8192 bytes "
+- "or larger\n");
+- goto failed;
+- }
+-
+- /*
+- * dictionary_size must be storable in xz header as either
+- * 2^n or as 2^n+2^(n+1)
+- */
+- n = ffs(dictionary_size) - 1;
+- if(dictionary_size != (1 << n) &&
+- dictionary_size != ((1 << n) + (1 << (n + 1)))) {
+- fprintf(stderr, "xz: -Xdict-size is an unsupported "
+- "value, dict-size must be storable in xz "
+- "header\n");
+- fprintf(stderr, "as either 2^n or as 2^n+2^(n+1). "
+- "Example dict-sizes are 75%%, 50%%, 37.5%%, "
+- "25%%,\n");
+- fprintf(stderr, "or 32K, 16K, 8K etc.\n");
+- goto failed;
+- }
+-
+- } else
+- /* No -Xdict-size specified, use defaults */
+- dictionary_size = block_size;
+-
+- return 0;
+-
+-failed:
+- return -1;
++ return lzma_xz_options_post(block_size, LZMA_OPT_XZ);
+ }
+
+
+@@ -314,32 +139,12 @@ failed:
+ */
+ static void *xz_dump_options(int block_size, int *size)
+ {
+- static struct comp_opts comp_opts;
+ int flags = 0, i;
+
+- /*
+- * don't store compressor specific options in file system if the
+- * default options are being used - no compressor options in the
+- * file system means the default options are always assumed
+- *
+- * Defaults are:
+- * metadata dictionary size: SQUASHFS_METADATA_SIZE
+- * datablock dictionary size: block_size
+- * 1 filter
+- */
+- if(dictionary_size == block_size && filter_count == 1)
+- return NULL;
+-
+ for(i = 0; bcj[i].name; i++)
+ flags |= bcj[i].selected << i;
+
+- comp_opts.dictionary_size = dictionary_size;
+- comp_opts.flags = flags;
+-
+- SQUASHFS_INSWAP_COMP_OPTS(&comp_opts);
+-
+- *size = sizeof(comp_opts);
+- return &comp_opts;
++ return lzma_xz_dump_options(block_size, size, flags);
+ }
+
+
+@@ -365,49 +170,20 @@ static void *xz_dump_options(int block_size, int *size)
+ */
+ static int xz_extract_options(int block_size, void *buffer, int size)
+ {
+- struct comp_opts *comp_opts = buffer;
+- int flags, i, n;
+-
+- if(size == 0) {
+- /* set defaults */
+- dictionary_size = block_size;
+- flags = 0;
+- } else {
+- /* check passed comp opts struct is of the correct length */
+- if(size != sizeof(struct comp_opts))
+- goto failed;
+-
+- SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
+-
+- dictionary_size = comp_opts->dictionary_size;
+- flags = comp_opts->flags;
+-
+- /*
+- * check that the dictionary size seems correct - the dictionary
+- * size should 2^n or 2^n+2^(n+1)
+- */
+- n = ffs(dictionary_size) - 1;
+- if(dictionary_size != (1 << n) &&
+- dictionary_size != ((1 << n) + (1 << (n + 1))))
+- goto failed;
+- }
+-
+- filter_count = 1;
+- for(i = 0; bcj[i].name; i++) {
+- if((flags >> i) & 1) {
+- bcj[i].selected = 1;
+- filter_count ++;
+- } else
+- bcj[i].selected = 0;
++ int ret = lzma_xz_extract_options(block_size, buffer, size, LZMA_OPT_XZ);
++
++ if (!ret) {
++ int i;
++ struct lzma_xz_options *opts = lzma_xz_get_options();
++ for(i = 0; bcj[i].name; i++) {
++ if((opts->flags >> i) & 1) {
++ bcj[i].selected = 1;
++ filter_count ++;
++ } else
++ bcj[i].selected = 0;
++ }
+ }
+-
+- return 0;
+-
+-failed:
+- fprintf(stderr, "xz: error reading stored compressor options from "
+- "filesystem!\n");
+-
+- return -1;
++ return ret;
+ }
+
+
+@@ -474,6 +250,7 @@ static int xz_init(void **strm, int block_size, int datablock)
+ int i, j, filters = datablock ? filter_count : 1;
+ struct filter *filter = malloc(filters * sizeof(struct filter));
+ struct xz_stream *stream;
++ struct lzma_xz_options *opts = lzma_xz_get_options();
+
+ if(filter == NULL)
+ goto failed;
+@@ -487,7 +264,7 @@ static int xz_init(void **strm, int block_size, int datablock)
+
+ memset(filter, 0, filters * sizeof(struct filter));
+
+- stream->dictionary_size = datablock ? dictionary_size :
++ stream->dictionary_size = datablock ? opts->dict_size :
+ SQUASHFS_METADATA_SIZE;
+
+ filter[0].filter[0].id = LZMA_FILTER_LZMA2;
+@@ -529,25 +306,27 @@ static int xz_compress(void *strm, void *dest, void *src, int size,
+ lzma_ret res = 0;
+ struct xz_stream *stream = strm;
+ struct filter *selected = NULL;
++ struct lzma_xz_options *opts = lzma_xz_get_options();
+
+ stream->filter[0].buffer = dest;
+
+ for(i = 0; i < stream->filters; i++) {
++ uint32_t preset = opts->preset;
+ struct filter *filter = &stream->filter[i];
+
++ if (opts->extreme)
++ preset |= LZMA_PRESET_EXTREME;
++
+ if(lzma_lzma_preset(&stream->opt, preset))
+ goto failed;
+
+- stream->opt.dict_size = stream->dictionary_size;
++ stream->opt.lc = opts->lc;
++ stream->opt.lp = opts->lp;
++ stream->opt.pb = opts->pb;
++ if (opts->fb)
++ stream->opt.nice_len = opts->fb;
+
+- if (lc >= 0)
+- stream->opt.lc = lc;
+-
+- if (lp >= 0)
+- stream->opt.lp = lp;
+-
+- if (pb >= 0)
+- stream->opt.pb = pb;
++ stream->opt.dict_size = stream->dictionary_size;
+
+ filter->length = 0;
+ res = lzma_stream_buffer_encode(filter->filter,
+@@ -603,32 +382,13 @@ static int xz_uncompress(void *dest, void *src, int size, int outsize,
+
+ static void xz_usage(FILE *stream)
+ {
++ lzma_xz_usage(LZMA_OPT_XZ);
+ fprintf(stream, "\t -Xbcj filter1,filter2,...,filterN\n");
+ fprintf(stream, "\t\tCompress using filter1,filter2,...,filterN in");
+ fprintf(stream, " turn\n\t\t(in addition to no filter), and choose");
+ fprintf(stream, " the best compression.\n");
+ fprintf(stream, "\t\tAvailable filters: x86, arm, armthumb,");
+ fprintf(stream, " powerpc, sparc, ia64\n");
+- fprintf(stream, "\t -Xdict-size <dict-size>\n");
+- fprintf(stream, "\t\tUse <dict-size> as the XZ dictionary size. The");
+- fprintf(stream, " dictionary size\n\t\tcan be specified as a");
+- fprintf(stream, " percentage of the block size, or as an\n\t\t");
+- fprintf(stream, "absolute value. The dictionary size must be less");
+- fprintf(stream, " than or equal\n\t\tto the block size and 8192 bytes");
+- fprintf(stream, " or larger. It must also be\n\t\tstorable in the xz");
+- fprintf(stream, " header as either 2^n or as 2^n+2^(n+1).\n\t\t");
+- fprintf(stream, "Example dict-sizes are 75%%, 50%%, 37.5%%, 25%%, or");
+- fprintf(stream, " 32K, 16K, 8K\n\t\tetc.\n");
+- fprintf(stream, "\t -Xpreset <preset-level>\n");
+- fprintf(stream, "\t\tUse <preset-value> as the custom preset to use");
+- fprintf(stream, " on compress.\n\t\t<preset-level> should be 0 .. 9");
+- fprintf(stream, " (default 6)\n");
+- fprintf(stream, "\t -Xe\n");
+- fprintf(stream, "\t\tEnable additional compression settings by passing");
+- fprintf(stream, " the EXTREME\n\t\tflag to the compression flags.\n");
+- fprintf(stream, "\t -Xlc <value>\n");
+- fprintf(stream, "\t -Xlp <value>\n");
+- fprintf(stream, "\t -Xpb <value>\n");
+ }
+
+
+--- a/squashfs-tools/Makefile
++++ b/squashfs-tools/Makefile
+@@ -263,6 +263,8 @@ COMPRESSORS += xz
+ endif
+
+ ifneq ($(LZMA_XZ_SUPPORT)$(XZ_SUPPORT),)
++MKSQUASHFS_OBJS += lzma_xz_options.o
++UNSQUASHFS_OBJS += lzma_xz_options.o
+ ifneq ($(LZMA_LIB),)
+ MKSQUASHFS_OBJS += $(LZMA_LIB)
+ UNSQUASHFS_OBJS += $(LZMA_LIB)
diff --git a/tools/sstrip/Makefile b/tools/sstrip/Makefile
new file mode 100644
index 0000000..55a7fa7
--- /dev/null
+++ b/tools/sstrip/Makefile
@@ -0,0 +1,29 @@
+#
+# Copyright (C) 2006-2012 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=sstrip
+PKG_VERSION:=3.2
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/ELFkickers-$(PKG_VERSION)
+PKG_SOURCE_URL:=https://www.muppetlabs.com/~breadbox/pub/software
+PKG_SOURCE:=ELFkickers-$(PKG_VERSION).tar.gz
+PKG_HASH:=9b81e6c53e0c94fc198d9882eb737156f36d565152dc32118897c77b06a2687c
+
+PKG_RELEASE:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Install
+ $(CP) $(HOST_BUILD_DIR)/bin/sstrip $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -f $(STAGING_DIR_HOST)/bin/sstrip
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/sstrip/patches/001-disable-elftoc-compilation.patch b/tools/sstrip/patches/001-disable-elftoc-compilation.patch
new file mode 100644
index 0000000..787c51c
--- /dev/null
+++ b/tools/sstrip/patches/001-disable-elftoc-compilation.patch
@@ -0,0 +1,28 @@
+From: Rui Salvaterra <rsalvaterra@gmail.com>
+Subject: sstrip: don't try to compile elftoc
+
+We only need sstrip itself and elftoc doesn't compile with musl's elf.h, so
+disable the elftoc compilation in the makefile.
+
+Signed-off-by: Rui Salvaterra <rsalvaterra@gmail.com>
+---
+
+--- a/Makefile
++++ b/Makefile
+@@ -2,7 +2,7 @@
+
+ prefix = /usr/local
+
+-PROGRAMS = elfls objres rebind sstrip elftoc ebfc infect
++PROGRAMS = elfls objres rebind sstrip ebfc infect
+
+ all: $(PROGRAMS)
+
+@@ -19,7 +19,6 @@ elfls: bin/elfls doc/elfls.1
+ objres: bin/objres doc/objres.1
+ rebind: bin/rebind doc/rebind.1
+ sstrip: bin/sstrip doc/sstrip.1
+-elftoc: bin/elftoc doc/elftoc.1
+ ebfc: bin/ebfc doc/ebfc.1
+ infect: bin/infect doc/infect.1
+
diff --git a/tools/tar/Makefile b/tools/tar/Makefile
new file mode 100644
index 0000000..8bedb8e
--- /dev/null
+++ b/tools/tar/Makefile
@@ -0,0 +1,35 @@
+#
+# Copyright (C) 2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=tar
+PKG_CPE_ID:=cpe:/a:gnu:tar
+PKG_VERSION:=1.35
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=@GNU/tar
+PKG_HASH:=14d55e32063ea9526e057fbf35fcabd53378e769787eff7919c3755b02d2b57e
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOSTCXX := $(HOSTCXX_NOCACHE)
+
+HOST_CONFIGURE_ARGS += \
+ --without-posix-acls \
+ --without-selinux \
+ --without-xattrs \
+ --disable-acl \
+ --disable-nls
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/tar/patches/0001-Fix-savannah-bug-64441.patch b/tools/tar/patches/0001-Fix-savannah-bug-64441.patch
new file mode 100644
index 0000000..1c10e54
--- /dev/null
+++ b/tools/tar/patches/0001-Fix-savannah-bug-64441.patch
@@ -0,0 +1,35 @@
+From 6bec1e7e7fe0ae5bbeb66fc9f32b0b1dd156957d Mon Sep 17 00:00:00 2001
+From: Sergey Poznyakoff <gray@gnu.org>
+Date: Tue, 18 Jun 2024 14:31:17 +0200
+Subject: [PATCH] Fix savannah bug #64441
+
+* src/Makefile.am (tar_LDADD): Add libiconv libraries.
+
+Adapted upstream commit 8632df398b2f548465ebe68b8f494c0d6f8d913d to patch
+the pregenerated Makefile.in instead of Makefile.am to avoid invoking
+automake which requires m4.
+
+This is required for macOS, as otherwise it will fail with:
+Undefined symbols for architecture arm64:
+ "_iconv", referenced from:
+ _utf8_convert in utf8.o
+ "_iconv_open", referenced from:
+ _utf8_convert in utf8.o
+ld: symbol(s) not found for architecture arm64
+clang: error: linker command failed with exit code 1 (use -v to see invocation)
+---
+ src/Makefile.in | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+--- a/src/Makefile.in
++++ b/src/Makefile.in
+@@ -1793,7 +1793,8 @@ AM_CFLAGS = $(WARN_CFLAGS) $(WERROR_CFLA
+ tar_LDADD = $(LIBS) ../lib/libtar.a ../gnu/libgnu.a\
+ $(LIB_ACL) $(LIB_CLOCK_GETTIME) $(LIB_EACCESS)\
+ $(LIB_GETRANDOM) $(LIB_HARD_LOCALE) $(FILE_HAS_ACL_LIB) $(LIB_MBRTOWC)\
+- $(LIB_SELINUX) $(LIB_SETLOCALE_NULL)
++ $(LIB_SELINUX) $(LIB_SETLOCALE_NULL) \
++ $(LIBINTL) $(LIBICONV)
+
+ all: all-am
+
diff --git a/tools/tar/patches/100-symlink-force-root-name.patch b/tools/tar/patches/100-symlink-force-root-name.patch
new file mode 100644
index 0000000..93f8897
--- /dev/null
+++ b/tools/tar/patches/100-symlink-force-root-name.patch
@@ -0,0 +1,27 @@
+Force root/root as names for uid0/gid0 instead of using the system
+names. This helps make packed download tarballs more reproducible
+
+Signed-off-by: Felix Fietkau <nbd@nbd.name>
+---
+--- a/src/create.c
++++ b/src/create.c
+@@ -544,17 +544,8 @@ write_gnu_long_link (struct tar_stat_inf
+ union block *header;
+
+ header = start_private_header ("././@LongLink", size, 0);
+- if (! numeric_owner_option)
+- {
+- static char *uname, *gname;
+- if (!uname)
+- {
+- uid_to_uname (0, &uname);
+- gid_to_gname (0, &gname);
+- }
+- UNAME_TO_CHARS (uname, header->header.uname);
+- GNAME_TO_CHARS (gname, header->header.gname);
+- }
++ UNAME_TO_CHARS ("root", header->header.uname);
++ GNAME_TO_CHARS ("root", header->header.gname);
+
+ strcpy (header->buffer + offsetof (struct posix_header, magic),
+ OLDGNU_MAGIC);
diff --git a/tools/tar/patches/110-symlink-force-permissions.patch b/tools/tar/patches/110-symlink-force-permissions.patch
new file mode 100644
index 0000000..ec64afe
--- /dev/null
+++ b/tools/tar/patches/110-symlink-force-permissions.patch
@@ -0,0 +1,10 @@
+--- a/src/create.c
++++ b/src/create.c
+@@ -1855,6 +1855,7 @@ dump_file0 (struct tar_stat_info *st, ch
+ #ifdef HAVE_READLINK
+ else if (S_ISLNK (st->stat.st_mode))
+ {
++ st->stat.st_mode |= 0777; /* make permissions portable */
+ st->link_name = areadlinkat_with_size (parentfd, name, st->stat.st_size);
+ if (!st->link_name)
+ {
diff --git a/tools/util-linux/Makefile b/tools/util-linux/Makefile
new file mode 100644
index 0000000..f9aadba
--- /dev/null
+++ b/tools/util-linux/Makefile
@@ -0,0 +1,55 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=util-linux
+PKG_VERSION:=2.40.2
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=@KERNEL/linux/utils/$(PKG_NAME)/v2.40
+PKG_HASH:=d78b37a66f5922d70edf3bdfb01a6b33d34ed3c3cafd6628203b2a2b67c8e8b3
+PKG_CPE_ID:=cpe:/a:kernel:util-linux
+
+PKG_FIXUP:=autoreconf
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOST_CONFIGURE_ARGS += \
+ --with-pic \
+ --disable-shared \
+ --disable-nls \
+ --disable-all-programs \
+ --enable-hexdump \
+ --enable-libuuid \
+ --without-util \
+ --without-selinux \
+ --without-audit \
+ --without-udev \
+ --without-ncursesw \
+ --without-ncurses \
+ --without-slang \
+ --without-tinfo \
+ --without-readline \
+ --without-utempter \
+ --without-cap-ng \
+ --without-libz \
+ --without-libmagic \
+ --without-user \
+ --without-btrfs \
+ --without-systemd \
+ --without-smack \
+ --without-econf \
+ --without-python \
+ --without-cryptsetup
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/util-linux/patches/0001-hexdump-allow-enabling-with-disable-all-programs.patch b/tools/util-linux/patches/0001-hexdump-allow-enabling-with-disable-all-programs.patch
new file mode 100644
index 0000000..a8f1b5e
--- /dev/null
+++ b/tools/util-linux/patches/0001-hexdump-allow-enabling-with-disable-all-programs.patch
@@ -0,0 +1,28 @@
+From 37641f246ee9df7289b4e3054b3ded3912773722 Mon Sep 17 00:00:00 2001
+From: Robert Marko <robimarko@gmail.com>
+Date: Tue, 25 Jun 2024 17:32:08 +0200
+Subject: [PATCH] hexdump: allow enabling with --disable-all-programs
+
+Currently, if --disable-all-programs is used hexdump cannot be built
+as --enable-hexdump is not recognized, so lets add support for it.
+
+Signed-off-by: Robert Marko <robimarko@gmail.com>
+---
+ configure.ac | 6 +++++-
+ 1 file changed, 5 insertions(+), 1 deletion(-)
+
+--- a/configure.ac
++++ b/configure.ac
+@@ -2240,7 +2240,11 @@ UL_BUILD_INIT([column], [check])
+ UL_REQUIRES_BUILD([column], [libsmartcols])
+ AM_CONDITIONAL([BUILD_COLUMN], [test "x$build_column" = xyes])
+
+-UL_BUILD_INIT([hexdump], [yes])
++AC_ARG_ENABLE([hexdump],
++ AS_HELP_STRING([--disable-hexdump], [do not build hexdump]),
++ [], [UL_DEFAULT_ENABLE([hexdump], [check])]
++)
++UL_BUILD_INIT([hexdump])
+ AM_CONDITIONAL([BUILD_HEXDUMP], [test "x$build_hexdump" = xyes])
+
+ UL_BUILD_INIT([rev], [yes])
diff --git a/tools/util-linux/patches/101-macos-weak-aliases.patch b/tools/util-linux/patches/101-macos-weak-aliases.patch
new file mode 100644
index 0000000..e5d0f9d
--- /dev/null
+++ b/tools/util-linux/patches/101-macos-weak-aliases.patch
@@ -0,0 +1,26 @@
+From 9445f477cfcfb3615ffde8f93b1b98c809ee4eca Mon Sep 17 00:00:00 2001
+From: Eugene Gershnik <gershnik@users.noreply.github.com>
+Date: Mon, 6 May 2024 09:29:39 -0700
+Subject: [PATCH] This re-enables build on macOS.
+
+Weak aliases are not supported by clang on Darwin.
+Instead this fix uses inline asm to make `_uuid_time` and alias to `___uuid_time`
+
+Fixes util-linux/util-linux#2873
+---
+ libuuid/src/uuid_time.c | 4 ++++
+ 1 file changed, 4 insertions(+)
+
+--- a/libuuid/src/uuid_time.c
++++ b/libuuid/src/uuid_time.c
+@@ -85,6 +85,10 @@ time_t __uuid_time(const uuid_t uu, stru
+ }
+ #if defined(__USE_TIME_BITS64) && defined(__GLIBC__)
+ extern time_t uuid_time64(const uuid_t uu, struct timeval *ret_tv) __attribute__((weak, alias("__uuid_time")));
++#elif defined(__clang__) && defined(__APPLE__)
++__asm__(".globl _uuid_time");
++__asm__(".set _uuid_time, ___uuid_time");
++extern time_t uuid_time(const uuid_t uu, struct timeval *ret_tv);
+ #else
+ extern time_t uuid_time(const uuid_t uu, struct timeval *ret_tv) __attribute__((weak, alias("__uuid_time")));
+ #endif
diff --git a/tools/util-linux/patches/110-pkgconfig-static.patch b/tools/util-linux/patches/110-pkgconfig-static.patch
new file mode 100644
index 0000000..d61ae31
--- /dev/null
+++ b/tools/util-linux/patches/110-pkgconfig-static.patch
@@ -0,0 +1,24 @@
+From 81ea117e0396274808a77d40bf11af44ea047285 Mon Sep 17 00:00:00 2001
+From: Rosen Penev <rosenp@gmail.com>
+Date: Mon, 23 Sep 2024 12:01:40 +0200
+Subject: [PATCH] pkgconfig: adjust for static libraries
+
+OpenWrt builds only static libuuid for tools. Adjust the pkgconfig file
+accordingly.
+
+Addresses: https://github.com/util-linux/util-linux/issues/3210
+Signed-off-by: Rosen Penev <rosenp@gmail.com>
+---
+ libuuid/uuid.pc.in | 2 +-
+ 1 file changed, 1 insertions(+), 2 deletions(-)
+
+--- a/libuuid/uuid.pc.in
++++ b/libuuid/uuid.pc.in
+@@ -6,6 +6,5 @@ includedir=@includedir@
+ Name: uuid
+ Description: Universally unique id library
+ Version: @LIBUUID_VERSION@
+-Requires:
+ Cflags: -I${includedir}/uuid
+-Libs: -L${libdir} -luuid
++Libs: -L${libdir} -luuid -lpthread
diff --git a/tools/xz/Makefile b/tools/xz/Makefile
new file mode 100644
index 0000000..a90cec8
--- /dev/null
+++ b/tools/xz/Makefile
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2006-2015 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=xz
+PKG_VERSION:=5.4.6
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@SF/lzmautils \
+ http://tukaani.org/xz
+PKG_HASH:=913851b274e8e1d31781ec949f1c23e8dbcf0ecf6e73a2436dc21769dd3e6f49
+PKG_CPE_ID:=cpe:/a:tukaani:xz
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOSTCXX := $(HOSTCXX_NOCACHE)
+
+HOST_CONFIGURE_ARGS += \
+ --enable-static=yes \
+ --enable-shared=no \
+ --disable-doc \
+ --disable-nls \
+ --with-pic
+
+define Host/Install
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR) install xzlinks="unxz xzcat"
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/yafut/Makefile b/tools/yafut/Makefile
new file mode 100644
index 0000000..a7e36e5
--- /dev/null
+++ b/tools/yafut/Makefile
@@ -0,0 +1,20 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=yafut
+PKG_RELEASE:=1
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL=https://github.com/kempniu/yafut.git
+PKG_MIRROR_HASH:=9cc6b4c485ce16d44b67ebf79e8bee1e07aecde112da739cf33e8714ac3842e7
+PKG_SOURCE_DATE:=2024-05-13
+PKG_SOURCE_VERSION:=2b45baaf1cced47af8f22dd3acbf1df2f04c7510
+
+PKG_LICENSE:=GPL-2.0
+PKG_LICENSE_FILES:=LICENSE
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/cmake.mk
+
+CMAKE_INSTALL:=1
+
+$(eval $(call HostBuild))
diff --git a/tools/zip/Makefile b/tools/zip/Makefile
new file mode 100644
index 0000000..5ad124d
--- /dev/null
+++ b/tools/zip/Makefile
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2007-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=zip
+PKG_REV:=30
+PKG_VERSION:=3.0
+
+PKG_SOURCE:=$(PKG_NAME)$(PKG_REV).tar.gz
+PKG_SOURCE_URL:=@SF/infozip
+PKG_HASH:=f0e8bb1f9b7eb0b01285495a2699df3a4b766784c1765a8f1aeedf63c0806369
+
+PKG_LICENSE:=BSD-4-Clause
+PKG_LICENSE_FILES:=LICENSE
+PKG_CPE_ID:=cpe:/a:zip_project:zip
+
+HOST_BUILD_DIR:=$(BUILD_DIR_HOST)/$(PKG_NAME)-$(PKG_VERSION)/zip$(PKG_REV)
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+define Host/Compile
+ +$(HOST_MAKE_VARS) $(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR) -I. -f unix/Makefile zip
+endef
+
+define Host/Install
+ $(INSTALL_DIR) $(STAGING_DIR_HOST)/bin/
+ $(INSTALL_BIN) $(HOST_BUILD_DIR)/zip $(STAGING_DIR_HOST)/bin/
+endef
+
+define Host/Clean
+ rm -rf $(STAGING_DIR_HOST)/bin/zip
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/zip/patches/001-unix-configure-borrow-the-LFS-test-from-autotools.patch b/tools/zip/patches/001-unix-configure-borrow-the-LFS-test-from-autotools.patch
new file mode 100644
index 0000000..ef0de6f
--- /dev/null
+++ b/tools/zip/patches/001-unix-configure-borrow-the-LFS-test-from-autotools.patch
@@ -0,0 +1,89 @@
+From fc392c939b9a18959482f588aff0afc29dd6d30a Mon Sep 17 00:00:00 2001
+From: Romain Naour <romain.naour at openwide.fr>
+Date: Fri, 23 Jan 2015 22:20:18 +0100
+Subject: [PATCH 6/6] unix/configure: borrow the LFS test from autotools.
+
+Infozip's LFS check can't work for cross-compilation
+since it try to run a target's binary on the host system.
+
+Instead, use to LFS test used by autotools which is a
+compilation test.
+(see autotools/lib/autoconf/specific.m4)
+
+Reported-by: Richard Genoud <richard.genoud at gmail.com>
+Signed-off-by: Romain Naour <romain.naour at openwide.fr>
+---
+ configure | 46 +++++++++++++++-------------------------------
+ 1 file changed, 15 insertions(+), 31 deletions(-)
+
+--- a/unix/configure
++++ b/unix/configure
+@@ -399,9 +399,8 @@ else
+ fi
+
+
+-# Now we set the 64-bit file environment and check the size of off_t
+-# Added 11/4/2003 EG
+-# Revised 8/12/2004 EG
++# LFS check borrowed from autotools sources
++# lib/autoconf/specific.m4
+
+ echo Check for Large File Support
+ cat > conftest.c << _EOF_
+@@ -410,23 +409,19 @@ cat > conftest.c << _EOF_
+ # define _FILE_OFFSET_BITS 64 /* select default interface as 64 bit */
+ # define _LARGE_FILES /* some OSes need this for 64-bit off_t */
+ #include <sys/types.h>
+-#include <sys/stat.h>
+-#include <unistd.h>
+-#include <stdio.h>
++
++ /* Check that off_t can represent 2**63 - 1 correctly.
++ We can't simply define LARGE_OFF_T to be 9223372036854775807,
++ since some C++ compilers masquerading as C compilers
++ incorrectly reject 9223372036854775807. */
++#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
++ int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
++ && LARGE_OFF_T % 2147483647 == 1)
++ ? 1 : -1];
++
+ int main()
+ {
+- off_t offset;
+- struct stat s;
+- /* see if have 64-bit off_t */
+- if (sizeof(offset) < 8)
+- return 1;
+- printf(" off_t is %d bytes\n", sizeof(off_t));
+- /* see if have 64-bit stat */
+- if (sizeof(s.st_size) < 8) {
+- printf(" s.st_size is %d bytes\n", sizeof(s.st_size));
+- return 2;
+- }
+- return 3;
++ return 0;
+ }
+ _EOF_
+ # compile it
+@@ -434,19 +429,8 @@ $CC -o conftest conftest.c >/dev/null 2>
+ if [ $? -ne 0 ]; then
+ echo -- no Large File Support
+ else
+-# run it
+- ./conftest
+- r=$?
+- if [ $r -eq 1 ]; then
+- echo -- no Large File Support - no 64-bit off_t
+- elif [ $r -eq 2 ]; then
+- echo -- no Large File Support - no 64-bit stat
+- elif [ $r -eq 3 ]; then
+- echo -- yes we have Large File Support!
+- CFLAGS="${CFLAGS} -DLARGE_FILE_SUPPORT"
+- else
+- echo -- no Large File Support - conftest returned $r
+- fi
++ echo -- yes we have Large File Support!
++ CFLAGS="${CFLAGS} -DLARGE_FILE_SUPPORT"
+ fi
+
+
diff --git a/tools/zip/patches/004-do-not-set-unwanted-cflags.patch b/tools/zip/patches/004-do-not-set-unwanted-cflags.patch
new file mode 100644
index 0000000..bfd2260
--- /dev/null
+++ b/tools/zip/patches/004-do-not-set-unwanted-cflags.patch
@@ -0,0 +1,15 @@
+From: Santiago Vila <sanvila@debian.org>
+Subject: Do not set unwanted CFLAGS, as it breaks DEB_BUILD_OPTIONS
+X-Debian-version: 2.32-1
+
+--- a/unix/configure
++++ b/unix/configure
+@@ -98,7 +98,7 @@ int main()
+ _EOF_
+ $CC $CFLAGS -c conftest.c > /dev/null 2>/dev/null
+ if test $? -eq 0; then
+- CFLAGS_OPT='-O3'
++ # CFLAGS_OPT='-O3'
+ echo " GNU C ($CFLAGS_OPT)"
+ # Special Mac OS X shared library "ld" option?
+ if test ` uname -s 2> /dev/null ` = 'Darwin'; then
diff --git a/tools/zip/patches/006-stack-markings-to-avoid-executable-stack.patch b/tools/zip/patches/006-stack-markings-to-avoid-executable-stack.patch
new file mode 100644
index 0000000..8b479fa
--- /dev/null
+++ b/tools/zip/patches/006-stack-markings-to-avoid-executable-stack.patch
@@ -0,0 +1,21 @@
+From: Kees Cook <kees@debian.org>
+Subject: put stack markings in i386 assembly to avoid executable stack
+Bug-Debian: http://bugs.debian.org/528280
+X-Debian-version: 3.0-2
+
+--- a/crc_i386.S
++++ b/crc_i386.S
+@@ -302,3 +302,5 @@ _crc32: /* ulg c
+ #endif /* i386 || _i386 || _I386 || __i386 */
+
+ #endif /* !USE_ZLIB && !CRC_TABLE_ONLY */
++.section .note.GNU-stack, "", @progbits
++.previous
+--- a/match.S
++++ b/match.S
+@@ -405,3 +405,5 @@ L__return:
+ #endif /* i386 || _I386 || _i386 || __i386 */
+
+ #endif /* !USE_ZLIB */
++.section .note.GNU-stack, "", @progbits
++.previous
diff --git a/tools/zip/patches/007-fclose-in-file-not-fclose-x.patch b/tools/zip/patches/007-fclose-in-file-not-fclose-x.patch
new file mode 100644
index 0000000..402f90a
--- /dev/null
+++ b/tools/zip/patches/007-fclose-in-file-not-fclose-x.patch
@@ -0,0 +1,16 @@
+From: Christian Spieler
+Subject: zipnote.c: Close in_file instead of undefined file x
+Bug-Debian: http://bugs.debian.org/628594
+X-Debian-version: 3.0-4
+
+--- a/zipnote.c
++++ b/zipnote.c
+@@ -661,7 +661,7 @@ char **argv; /* command line
+ if ((r = zipcopy(z)) != ZE_OK)
+ ziperr(r, "was copying an entry");
+ }
+- fclose(x);
++ fclose(in_file);
+
+ /* Write central directory and end of central directory with new comments */
+ if ((c = zftello(y)) == (zoff_t)-1) /* get start of central */
diff --git a/tools/zip/patches/008-hardening-build-fix-1.patch b/tools/zip/patches/008-hardening-build-fix-1.patch
new file mode 100644
index 0000000..a0c3a91
--- /dev/null
+++ b/tools/zip/patches/008-hardening-build-fix-1.patch
@@ -0,0 +1,25 @@
+From: Santiago Vila <sanvila@debian.org>
+Subject: Use format specifier %s to print strings, not the string itself
+Bug-Debian: http://bugs.debian.org/673476
+X-Debian-version: 3.0-5
+
+--- a/zip.c
++++ b/zip.c
+@@ -1028,7 +1028,7 @@ local void help_extended()
+
+ for (i = 0; i < sizeof(text)/sizeof(char *); i++)
+ {
+- printf(text[i]);
++ printf("%s", text[i]);
+ putchar('\n');
+ }
+ #ifdef DOS
+@@ -1225,7 +1225,7 @@ local void version_info()
+ CR_MAJORVER, CR_MINORVER, CR_BETA_VER, CR_VERSION_DATE);
+ for (i = 0; i < sizeof(cryptnote)/sizeof(char *); i++)
+ {
+- printf(cryptnote[i]);
++ printf("%s", cryptnote[i]);
+ putchar('\n');
+ }
+ ++i; /* crypt support means there IS at least one compilation option */
diff --git a/tools/zip/patches/009-hardening-build-fix-2.patch b/tools/zip/patches/009-hardening-build-fix-2.patch
new file mode 100644
index 0000000..e295ffb
--- /dev/null
+++ b/tools/zip/patches/009-hardening-build-fix-2.patch
@@ -0,0 +1,16 @@
+From: Santiago Vila <sanvila@debian.org>
+Subject: unix/configure: Take linking flags from the environment
+Bug-Debian: http://bugs.debian.org/673476
+X-Debian-version: 3.0-5
+
+--- a/unix/configure
++++ b/unix/configure
+@@ -18,7 +18,7 @@ trap "rm -f conftest* core a.out; exit 1
+
+ CC=${1-cc}
+ CFLAGS=${2-"-I. -DUNIX"}
+-LFLAGS1=''
++LFLAGS1=${LDFLAGS}
+ LFLAGS2=''
+ LN="ln -s"
+
diff --git a/tools/zip/patches/010-remove-build-date.patch b/tools/zip/patches/010-remove-build-date.patch
new file mode 100644
index 0000000..5fc3852
--- /dev/null
+++ b/tools/zip/patches/010-remove-build-date.patch
@@ -0,0 +1,15 @@
+From: Santiago Vila <sanvila@debian.org>
+Subject: Remove (optional) build date to make the build reproducible
+Bug-Debian: http://bugs.debian.org/779042
+
+--- a/unix/unix.c
++++ b/unix/unix.c
+@@ -1020,7 +1020,7 @@ void version_local()
+
+
+ /* Define the compile date string */
+-#ifdef __DATE__
++#if 0
+ # define COMPILE_DATE " on " __DATE__
+ #else
+ # define COMPILE_DATE ""
diff --git a/tools/zip/patches/011-reproducible-mtime.patch b/tools/zip/patches/011-reproducible-mtime.patch
new file mode 100644
index 0000000..6ce8445
--- /dev/null
+++ b/tools/zip/patches/011-reproducible-mtime.patch
@@ -0,0 +1,41 @@
+From 501ae4e93fd6fa2f7d20d00d1b011f9006802eae Mon Sep 17 00:00:00 2001
+From: "Bernhard M. Wiedemann" <bwiedemann@suse.de>
+Date: Fri, 3 May 2019 16:32:24 +0200
+Subject: [PATCH] Override mtime with zip -X
+
+with SOURCE_DATE_EPOCH
+to allow for reproducible builds of .zip files
+
+See https://reproducible-builds.org/ for why this is good
+and https://reproducible-builds.org/specs/source-date-epoch/
+for the definition of this variable.
+
+Uses clamping to keep older mtimes than SOURCE_DATE_EPOCH intact.
+---
+ zipup.c | 8 ++++++++
+ 1 file changed, 8 insertions(+)
+
+--- a/zipup.c
++++ b/zipup.c
+@@ -414,6 +414,7 @@ struct zlist far *z; /* zip entry to
+ ush tempcext = 0;
+ char *tempextra = NULL;
+ char *tempcextra = NULL;
++ const char *source_date_epoch;
+
+
+ #ifdef WINDLL
+@@ -674,6 +675,13 @@ struct zlist far *z; /* zip entry to
+
+ } /* strcmp(z->name, "-") == 0 */
+
++ if (extra_fields == 0 && (source_date_epoch = getenv("SOURCE_DATE_EPOCH")) != NULL) {
++ time_t epoch = strtoull(source_date_epoch, NULL, 10);
++ if (epoch > 0) {
++ ulg epochtim = unix2dostime(&epoch);
++ if (z->tim > epochtim) z->tim = epochtim;
++ }
++ }
+ if (extra_fields == 2) {
+ unsigned len;
+ char *p;
diff --git a/tools/zip/patches/012-make-encrypted-archives-reproducible.patch b/tools/zip/patches/012-make-encrypted-archives-reproducible.patch
new file mode 100644
index 0000000..a6259d3
--- /dev/null
+++ b/tools/zip/patches/012-make-encrypted-archives-reproducible.patch
@@ -0,0 +1,75 @@
+From db9165814823401d57383a8f9e82642129cf4223 Mon Sep 17 00:00:00 2001
+From: Sungbo Eo <mans0n@gorani.run>
+Date: Sat, 12 Feb 2022 16:42:14 +0900
+Subject: [PATCH] make encrypted archives reproducible
+
+Zip always try to generate new encryption header depending on execution
+time and process id, which is far from being reproducible. This commit
+changes the zip srand() seed to a predictable value to generate
+reproducible random bytes for the encryption header. This will compromise
+the goal of secure archive encryption, but it would not be a big problem
+for our purpose.
+
+Signed-off-by: Sungbo Eo <mans0n@gorani.run>
+---
+ crypt.c | 8 ++++++--
+ globals.c | 1 +
+ zip.h | 1 +
+ zipup.c | 2 +-
+ 4 files changed, 9 insertions(+), 3 deletions(-)
+
+--- a/crypt.c
++++ b/crypt.c
+@@ -29,7 +29,6 @@
+ version without encryption capabilities).
+ */
+
+-#define ZCRYPT_INTERNAL
+ #include "zip.h"
+ #include "crypt.h"
+ #include "ttyio.h"
+@@ -219,7 +218,12 @@ void crypthead(passwd, crc)
+ * often poorly implemented.
+ */
+ if (++calls == 1) {
+- srand((unsigned)time(NULL) ^ ZCR_SEED2);
++ unsigned zcr_seed1 = (unsigned)time(NULL);
++#ifndef ZCRYPT_INTERNAL
++ if (epoch > 0)
++ zcr_seed1 = (unsigned)epoch;
++#endif
++ srand(zcr_seed1 ^ ZCR_SEED2);
+ }
+ init_keys(passwd);
+ for (n = 0; n < RAND_HEAD_LEN-2; n++) {
+--- a/globals.c
++++ b/globals.c
+@@ -206,6 +206,7 @@ int read_split_archive = 0; /* 1=s
+ int split_method = 0; /* 0=no splits, 1=seekable, 2=data desc, -1=no */
+ uzoff_t split_size = 0; /* how big each split should be */
+ int split_bell = 0; /* when pause for next split ring bell */
++time_t epoch = 0; /* timestamp from SOURCE_DATE_EPOCH */
+ uzoff_t bytes_prev_splits = 0; /* total bytes written to all splits before this */
+ uzoff_t bytes_this_entry = 0; /* bytes written for this entry across all splits */
+ int noisy_splits = 0; /* note when splits are being created */
+--- a/zip.h
++++ b/zip.h
+@@ -502,6 +502,7 @@ extern uzoff_t bytes_this_split; /* byte
+ extern int read_split_archive; /* 1=scanzipf_reg detected spanning signature */
+ extern int split_method; /* 0=no splits, 1=seekable, 2=data descs, -1=no */
+ extern uzoff_t split_size; /* how big each split should be */
++extern time_t epoch; /* timestamp from SOURCE_DATE_EPOCH */
+ extern int split_bell; /* when pause for next split ring bell */
+ extern uzoff_t bytes_prev_splits; /* total bytes written to all splits before this */
+ extern uzoff_t bytes_this_entry; /* bytes written for this entry across all splits */
+--- a/zipup.c
++++ b/zipup.c
+@@ -676,7 +676,7 @@ struct zlist far *z; /* zip entry to
+ } /* strcmp(z->name, "-") == 0 */
+
+ if (extra_fields == 0 && (source_date_epoch = getenv("SOURCE_DATE_EPOCH")) != NULL) {
+- time_t epoch = strtoull(source_date_epoch, NULL, 10);
++ epoch = strtoull(source_date_epoch, NULL, 10);
+ if (epoch > 0) {
+ ulg epochtim = unix2dostime(&epoch);
+ if (z->tim > epochtim) z->tim = epochtim;
diff --git a/tools/zlib/Makefile b/tools/zlib/Makefile
new file mode 100644
index 0000000..6786e14
--- /dev/null
+++ b/tools/zlib/Makefile
@@ -0,0 +1,41 @@
+#
+# Copyright (C) 2006-2013 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=zlib
+PKG_VERSION:=1.3.1
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
+PKG_SOURCE_URL:=https://github.com/madler/zlib/releases/download/v$(PKG_VERSION)
+PKG_HASH:=38ef96b8dfe510d42707d9c781877914792541133e1870841463bfa73f883e32
+
+PKG_LICENSE:=Zlib
+PKG_LICENSE_FILES:=README
+PKG_CPE_ID:=cpe:/a:gnu:zlib
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC := $(HOSTCC_NOCACHE)
+HOST_CFLAGS += $(HOST_FPIC)
+
+HOST_CONFIGURE_ARGS = \
+ --prefix=$(STAGING_DIR_HOST) \
+ --sysconfdir=$(STAGING_DIR_HOST)/etc \
+ --localstatedir=$(STAGING_DIR_HOST)/var \
+ --libdir=$(STAGING_DIR_HOST)/lib \
+ --includedir=$(STAGING_DIR_HOST)/include \
+ --static
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/zlib/patches/900-overridable-pc-exec-prefix.patch b/tools/zlib/patches/900-overridable-pc-exec-prefix.patch
new file mode 100644
index 0000000..4f1e376
--- /dev/null
+++ b/tools/zlib/patches/900-overridable-pc-exec-prefix.patch
@@ -0,0 +1,14 @@
+--- a/zlib.pc.cmakein
++++ b/zlib.pc.cmakein
+@@ -1,8 +1,8 @@
+ prefix=@CMAKE_INSTALL_PREFIX@
+ exec_prefix=@CMAKE_INSTALL_PREFIX@
+-libdir=@INSTALL_LIB_DIR@
+-sharedlibdir=@INSTALL_LIB_DIR@
+-includedir=@INSTALL_INC_DIR@
++libdir=${prefix}/lib
++sharedlibdir=${prefix}/lib
++includedir=${prefix}/include
+
+ Name: zlib
+ Description: zlib compression library
diff --git a/tools/zstd/Makefile b/tools/zstd/Makefile
new file mode 100644
index 0000000..e1d36c5
--- /dev/null
+++ b/tools/zstd/Makefile
@@ -0,0 +1,45 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=zstd
+PKG_VERSION:=1.5.6
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=https://github.com/facebook/zstd/releases/download/v$(PKG_VERSION)
+PKG_HASH:=8c29e06cf42aacc1eafc4077ae2ec6c6fcb96a626157e0593d5e82a34fd403c1
+
+PKG_LICENSE:=BSD-3-Clause
+PKG_LICENSE_FILES:=LICENSE
+PKG_CPE_ID:=cpe:/a:facebook:zstandard
+
+HOST_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+
+HOSTCC:= $(HOSTCC_NOCACHE)
+
+HOST_CFLAGS += $(HOST_FPIC)
+
+HOST_MAKE_FLAGS += \
+ BACKTRACE=0 \
+ HAVE_THREAD=1 \
+ HAVE_ZLIB=0 \
+ HAVE_LZMA=0 \
+ HAVE_LZ4=0 \
+ PREFIX=$(HOST_BUILD_PREFIX)
+
+define Host/Compile
+ $(call Host/Compile/Default,lib-mt)
+ $(call Host/Compile/Default,zstd)
+endef
+
+define Host/Install
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/lib install-static install-includes PREFIX=$(HOST_BUILD_PREFIX)
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/lib install-pc MT=1 PREFIX=$(HOST_BUILD_PREFIX)
+ +$(MAKE) $(HOST_JOBS) -C $(HOST_BUILD_DIR)/programs install PREFIX=$(HOST_BUILD_PREFIX)
+endef
+
+define Host/Uninstall
+ -$(call Host/Compile/Default,uninstall)
+endef
+
+$(eval $(call HostBuild))
diff --git a/tools/zstd/patches/001-Provide-variant-pkg-config-file-for-multi-threaded-s.patch b/tools/zstd/patches/001-Provide-variant-pkg-config-file-for-multi-threaded-s.patch
new file mode 100644
index 0000000..1bbcaf4
--- /dev/null
+++ b/tools/zstd/patches/001-Provide-variant-pkg-config-file-for-multi-threaded-s.patch
@@ -0,0 +1,126 @@
+From f1f1ae369a4cefd3474b3528e8d1847b18750605 Mon Sep 17 00:00:00 2001
+From: Christian Marangi <ansuelsmth@gmail.com>
+Date: Sat, 6 Apr 2024 14:41:54 +0200
+Subject: [PATCH] Provide variant pkg-config file for multi-threaded static lib
+
+Multi-threaded static library require -pthread to correctly link and works.
+The pkg-config we provide tho only works with dynamic multi-threaded library
+and won't provide the correct libs and cflags values if lib-mt is used.
+
+To handle this, introduce an env variable MT to permit advanced user to
+install and generate a correct pkg-config file for lib-mt or detect if
+lib-mt target is called.
+
+With MT env set on calling make install-pc, libzstd.pc.in is a
+pkg-config file for a multi-threaded static library.
+
+On calling make lib-mt, a libzstd.pc is generated for a multi-threaded
+static library as it's what asked by the user by forcing it.
+
+libzstd.pc is changed to PHONY to force regeneration of it on calling
+lib targets or install-pc to handle case where the same directory is
+used for mixed compilation.
+
+This was notice while migrating from meson to make build system where
+meson generates a correct .pc file while make doesn't.
+
+Signed-off-by: Christian Marangi <ansuelsmth@gmail.com>
+---
+ lib/Makefile | 20 +++++++++++++++++++-
+ lib/README.md | 4 ++++
+ lib/libzstd.pc.in | 4 ++--
+ 3 files changed, 25 insertions(+), 3 deletions(-)
+
+--- a/lib/Makefile
++++ b/lib/Makefile
+@@ -63,6 +63,8 @@ CPPFLAGS_DYNLIB += -DZSTD_MULTITHREAD #
+ LDFLAGS_DYNLIB += -pthread
+ CPPFLAGS_STATICLIB += # static library build defaults to single-threaded
+
++# pkg-config Libs.private points to LDFLAGS_DYNLIB
++PCLIB := $(LDFLAGS_DYNLIB)
+
+ ifeq ($(findstring GCC,$(CCVER)),GCC)
+ decompress/zstd_decompress_block.o : CFLAGS+=-fno-tree-vectorize
+@@ -186,12 +188,15 @@ lib : libzstd.a libzstd
+ %-mt : CPPFLAGS_DYNLIB := -DZSTD_MULTITHREAD
+ %-mt : CPPFLAGS_STATICLIB := -DZSTD_MULTITHREAD
+ %-mt : LDFLAGS_DYNLIB := -pthread
++%-mt : PCLIB :=
++%-mt : PCMTLIB := $(LDFLAGS_DYNLIB)
+ %-mt : %
+ @echo multi-threaded build completed
+
+ %-nomt : CPPFLAGS_DYNLIB :=
+ %-nomt : LDFLAGS_DYNLIB :=
+ %-nomt : CPPFLAGS_STATICLIB :=
++%-nomt : PCLIB :=
+ %-nomt : %
+ @echo single-threaded build completed
+
+@@ -292,6 +297,14 @@ PCLIBPREFIX := $(if $(findstring $(LIBDI
+ # to PREFIX, rather than as a resolved value.
+ PCEXEC_PREFIX := $(if $(HAS_EXPLICIT_EXEC_PREFIX),$(EXEC_PREFIX),$${prefix})
+
++
++ifneq ($(MT),)
++ PCLIB :=
++ PCMTLIB := $(LDFLAGS_DYNLIB)
++else
++ PCLIB := $(LDFLAGS_DYNLIB)
++endif
++
+ ifneq (,$(filter $(UNAME),FreeBSD NetBSD DragonFly))
+ PKGCONFIGDIR ?= $(PREFIX)/libdata/pkgconfig
+ else
+@@ -308,6 +321,10 @@ INSTALL_PROGRAM ?= $(INSTALL)
+ INSTALL_DATA ?= $(INSTALL) -m 644
+
+
++# pkg-config library define.
++# For static single-threaded library declare -pthread in Libs.private
++# For static multi-threaded library declare -pthread in Libs and Cflags
++.PHONY: libzstd.pc
+ libzstd.pc: libzstd.pc.in
+ @echo creating pkgconfig
+ @sed \
+@@ -316,7 +333,8 @@ libzstd.pc: libzstd.pc.in
+ -e 's|@INCLUDEDIR@|$(PCINCPREFIX)$(PCINCDIR)|' \
+ -e 's|@LIBDIR@|$(PCLIBPREFIX)$(PCLIBDIR)|' \
+ -e 's|@VERSION@|$(VERSION)|' \
+- -e 's|@LIBS_PRIVATE@|$(LDFLAGS_DYNLIB)|' \
++ -e 's|@LIBS_MT@|$(PCMTLIB)|' \
++ -e 's|@LIBS_PRIVATE@|$(PCLIB)|' \
+ $< >$@
+
+ .PHONY: install
+--- a/lib/README.md
++++ b/lib/README.md
+@@ -27,12 +27,16 @@ Enabling multithreading requires 2 condi
+
+ For convenience, we provide a build target to generate multi and single threaded libraries:
+ - Force enable multithreading on both dynamic and static libraries by appending `-mt` to the target, e.g. `make lib-mt`.
++ Note that the `.pc` generated on calling `make lib-mt` will already include the require Libs and Cflags.
+ - Force disable multithreading on both dynamic and static libraries by appending `-nomt` to the target, e.g. `make lib-nomt`.
+ - By default, as mentioned before, dynamic library is multithreaded, and static library is single-threaded, e.g. `make lib`.
+
+ When linking a POSIX program with a multithreaded version of `libzstd`,
+ note that it's necessary to invoke the `-pthread` flag during link stage.
+
++The `.pc` generated from `make install` or `make install-pc` always assume a single-threaded static library
++is compiled. To correctly generate a `.pc` for the multi-threaded static library, set `MT=1` as ENV variable.
++
+ Multithreading capabilities are exposed
+ via the [advanced API defined in `lib/zstd.h`](https://github.com/facebook/zstd/blob/v1.4.3/lib/zstd.h#L351).
+
+--- a/lib/libzstd.pc.in
++++ b/lib/libzstd.pc.in
+@@ -11,6 +11,6 @@ Name: zstd
+ Description: fast lossless compression algorithm library
+ URL: https://facebook.github.io/zstd/
+ Version: @VERSION@
+-Libs: -L${libdir} -lzstd
++Libs: -L${libdir} -lzstd @LIBS_MT@
+ Libs.private: @LIBS_PRIVATE@
+-Cflags: -I${includedir}
++Cflags: -I${includedir} @LIBS_MT@